欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

struts2拦截器与过滤器

程序员文章站 2022-07-02 17:53:19
...
1.拦截器只拦截请求
  过滤器过滤request和response
2.用户登陆拦截器:
/**
 * 用户登陆的拦截器
 * 
 * @author xxx
 * @date 2014-10-22
 * @time 下午3:24:33
 * @version 1.0
 */
@SuppressWarnings("serial")
public class LoginInterceptor extends AbstractInterceptor {
	private static Logger logger = Logger.getLogger(LoginInterceptor.class);

	@Override
	public String intercept(ActionInvocation invocation) throws Exception
	{
//		String className = invocation.getAction().getClass().getName();
//	    String action = className.substring(className.lastIndexOf(".")+1,className.length());
//	    String actionName = invocation.getProxy().getActionName();
//	    logger.info("className="+className+";action="+action+";actionName="+actionName);
		String result;
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		ActionContext ctx = invocation.getInvocationContext();// 取得请求相关的ActionContext实例
		Map<String, Object> session = ctx.getSession();
		Operator user = (Operator) session.get(WebConstant.OPERATOR);
		if (null == user)//session超时
		{
			String type = request.getHeader("X-Requested-With");
			if ("XMLHttpRequest".equalsIgnoreCase(type)|| request.getParameter("ajax") != null)//ajax提交的请求
			{
				response.setHeader("sessionstatus", "timeout");
				logger.warn("Ajax提交,请求超时,请重新登录");
				result = null;
			} else//其他方式提交的请求
			{
				logger.warn("请求超时,请重新登录");
				result = Action.LOGIN;
			}
		} else
		{
			SessionUser.setOperator(user);
			result = invocation.invoke();
		}
		return result;
	}

}

在struts.xml配置:
<package name="default" extends="struts-default"> 
	<!-- 定义一个拦截器  拦截用户必须先登录-->  
	<interceptors>  
		<interceptor name="authority" class="xxxx.filter.LoginInterceptor" />  //自定义的拦截器
		<!-- 拦截器栈 --> 包含自定义拦截器和默认拦截器
	   <interceptor-stack name="mydefault">  
			<interceptor-ref name="defaultStack" />  
			<interceptor-ref name="authority" />  
		</interceptor-stack>  
	</interceptors>  
	<!-- 定义全局Result -->  
	<global-results>  
	   <!-- 当返回login视图名时,转入/login.jsp页面 -->  
	   <!--<result name="login" >user/login.action</result>  --> 
		<result name="login" >/jsp/login.jsp</result>
		<result name="input" >/jsp/login.jsp</result>
	</global-results>  
</package>	

使用:action类上annotation
@InterceptorRefs({
@InterceptorRef("mydefault")
})
3.编码格式过滤器
/**
 * 编码过滤器
 * @author xxx
 * @date 2014-10-22
 * @time 下午3:24:33
 * @version 1.0
 */
public class EncodeFilter implements Filter  {
	private FilterConfig config = null;  
    private String encoding = null;  
	
    @Override
	public void destroy() {
		config = null;  
        encoding = null; 
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		 if (encoding == null) {  
	            encoding = config.getInitParameter("encoding");  
	           }  
	           request.setCharacterEncoding(encoding);  
	           response.setCharacterEncoding(encoding); 
//	           response.setContentType("text/html;charset="+encoding );
	           chain.doFilter(request, response);  
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.config = config;
	}


}

web.xml配置过滤规则
<!-- 编码格式过滤 -->
<filter>   
	<filter-name>encoding</filter-name>   
	<filter-class>xxx.filter.EncodeFilter  </filter-class>   
	<init-param>   
		<param-name>encoding</param-name>   
		<param-value>UTF-8</param-value>   
	</init-param>   
</filter>    
<filter-mapping>  
	   <filter-name>encoding</filter-name>  
	   <url-pattern>/*</url-pattern>  
</filter-mapping>