增加一个Action、ActionForm & JSP:
login.jsp中为一个登陆表单:
UserActionForm.java为一个Struts的ActionForm。
UserAction.java将用户登陆信息添加到session中。
开发UserLoginedFilter.java:
package bluemoon.crm.systemmanage.struts.Filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.*;
import bluemoon.crm.systemmanage.struts.forms.UserActionForm;
public class UserLoginedFilter extends HttpServlet implements Filter
{
protected FilterConfig config;
public void init(FilterConfig filterConfig) throws ServletException
{
this.config = filterConfig;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
RequestDispatcher dispatcher = request.getRequestDispatcher("userLogin.jsp");
HttpServletRequest userRequest = (HttpServletRequest)request;
UserActionForm userActionForm = (UserActionForm)userRequest.getSession().getAttribute("userActionForm");
if(userActionForm == null || userActionForm.getUser_name() == null || userActionForm.getUser_name().trim().length()<1)
{
System.out.println("用户未登录!");
dispatcher.forward(request,response);
return;
}
System.out.println("用户已登录!");
chain.doFilter(request,response);
}
public void destroy()
{
}
}
三.用户是否登陆过滤器在多模块中的应用:
1.修改上面的过滤器代码:
package bluemoon.crm.systemmanage.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.*;
import bluemoon.crm.systemmanage.struts.forms.UserForm;
//用户未登陆过滤器
public class UserNoLoginedFilter extends HttpServlet implements Filter
{
protected FilterConfig config;
public void init(FilterConfig filterConfig) throws ServletException
{
this.config = filterConfig;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
//首先预定义到要转向的页面,由此带来的问题就是userLogin.jsp页面的图片必须要使用绝对路径,方法见userLogin.jsp页面
RequestDispatcher dispatcher = request.getRequestDispatcher("/toLogin.do?prefix=&page=/userLogin.jsp");
//注意在struts-config.xml中增加一个Action,如下:
/*
*<action
* attribute="userForm"
* name="userForm"
* path="/toLogin"
* scope="request"
* type="org.apache.struts.actions.SwitchAction" />
*/
// 从session中获取用户form
HttpServletRequest userRequest = (HttpServletRequest)request;
UserForm userForm = (UserForm)userRequest.getSession().getAttribute("userForm");
//如果未登陆则没有userFrom信息
if(userForm == null || userForm.getUser_name() == null || userForm.getUser_name().trim().length()<1)
{
System.out.println("用户未登录!");
//分发到登陆页面
dispatcher.forward(request,response);
//((HttpServletResponse)response).sendRedirect("toModule.do?prefix=&page=/userLogin.jsp");
return;
}
System.out.println("用户"+userForm.getUser_name()+"已登录!");
chain.doFilter(request,response);
}
public void destroy()
{
}
}
四.关闭Session过滤器
1.相关的HibernateUtil.java源码:
package com.worklog.util;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class HibernateUtil {
private static SessionFactory sessionFactory;
static
{
try
{
sessionFactory = new Configuration().configure().buildSessionFactory();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static final ThreadLocal<Session> threadLocalSession = new ThreadLocal<Session>();
public static final ThreadLocal<Transaction> threadLocalTransaction = new ThreadLocal<Transaction>();
public static Session currentSession()
{
Session session = threadLocalSession.get();
try
{
if(session == null || !session.isOpen())
{
session = openSession();
threadLocalSession.set(session);
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("获取Session失败");
}
return session;
}
public static Session openSession() throws Exception
{
return getSessionFactory().openSession();
}
public static SessionFactory getSessionFactory() throws Exception
{
return sessionFactory;
}
public static void closeSession()
{
Session session = (Session)threadLocalSession.get();
threadLocalSession.set(null);
try
{
if(session != null && session.isOpen())
{
//System.out.println("HibernateUtil.java--line59,关闭Session!");
session.close();
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("关闭Session失败");
}
}
public static void beginTransaction()
{
Transaction tx = (Transaction)threadLocalTransaction.get();
try
{
if(tx == null)
{
tx = currentSession().beginTransaction();
threadLocalTransaction.set(tx);
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("开始事务失败");
}
}
public static void commitTransaction()
{
Transaction tx = (Transaction)threadLocalTransaction.get();
try
{
if(tx !=null && !tx.wasCommitted() && !tx.wasRolledBack())
{
tx.commit();
}
threadLocalTransaction.set(null);
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("提交失败");
}
}
public static void rollbackTransaction()
{
Transaction tx = (Transaction)threadLocalTransaction.get();
try
{
threadLocalTransaction.set(null);
if(tx != null && !tx.wasCommitted() && !tx.wasRolledBack())
tx.rollback();
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("回滚失败");
}
}
}
2.CloseSessionFilter.java源码:
package com.worklog.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.worklog.util.HibernateUtil;
public class CloseSessionFilter implements Filter{
Log log = LogFactory.getLog(this.getClass());
protected FilterConfig config;
public void init(FilterConfig config) throws ServletException
{
this.config = config;
}
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException,ServletException
{
try
{
//让后面的Filter链处理请求,这个Filter仅仅拦截响应处理Hibernate操作
chain.doFilter((HttpServletRequest)request, (HttpServletResponse)response);
}
finally
{
try
{
//一直没有合适的关闭session的方法
HibernateUtil.closeSession();
//System.out.println("close session success");
log.debug("close session success");
}
catch(Exception e)
{
HibernateUtil.rollbackTransaction();
System.out.println("can not close session!\nerrors:"+e.getMessage());
log.debug("can not close session!\nerrors:"+e.getMessage());
}
finally
{
HibernateUtil.closeSession();
}
}
}
public void destroy()
{
}
}
3.web.xml配置
<?xml version="1.0" encoding="GB2312"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- 关闭Session过滤器 -->
<filter>
<filter-name>closeSessionFilter</filter-name>
<filter-class>com.worklog.filter.CloseSessionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>closeSessionFilter</filter-name>
<servlet-name>action</servlet-name>
</filter-mapping>
<!-- 关闭Session过滤器结束 -->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>