struts2拦截器实现session会话过滤

笔记之用...

 

首先定义一个拦截器

 

package com.test.intercepter;

import java.io.PrintWriter;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/****************
 * session会话超时处理
 * @author shen
 *
 */
public class SessionIntercepter extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		System.out.println("interceptor拦截......");
		ActionContext ctx=ActionContext.getContext();
		Map session=ctx.getSession();
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		String uri = request.getRequestURI();
		String prefix = request.getContextPath(); // 得到 项目上下文路径
		uri = uri.substring(prefix.length()); // 去除 项目上下文路径
		String queryString = request.getQueryString();
		String requestUri = uri;
		if (queryString!=null) {
			requestUri = requestUri + "?" + queryString;
		}
		if (null!=requestUri&&requestUri.length()>1&&requestUri.startsWith("/")) {
			requestUri = removePrex(requestUri);//移除前面的"//"
		}
		System.out.println("url:"+requestUri);//拦截的都是action
		if(requestUri.indexOf("type=ajax")!=-1){
			return invocation.invoke();
		}
		if("userAction!login.action".equals(requestUri)
				||"userAction!login.action?cookie=yes".equals(requestUri)
			){
			return invocation.invoke();//如果是登录、注销,则放行,不用检查session
		}else{//其它的url则检查session
			String user=(String)session.get("username");
			if(user!=null){
				return invocation.invoke();
			}
			
			response.setContentType("text/html;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");//防止弹出的信息出现乱码
			PrintWriter out = response.getWriter();
	        out.println("<html>");  
	        out.println("<script type=\"text/javascript\">");  
	        out.println("alert('未登录或会话已过期,请重新登录!')");
	        out.println("window.open ('"+prefix+"/login.jsp','_top')");  
	        out.println("</script>");  
	        out.println("</html>");
			return null;
		}
	}

	public String removePrex(String s){
		String patternStr = "([a-zA-Z]+)";
		Pattern pattern = Pattern.compile(patternStr);
	    Matcher matcher = pattern.matcher(s);
	    String replaceStr = null;
	    if (matcher.find()) {
	    	replaceStr = matcher.group();
		}
		int i = s.indexOf(replaceStr)-1;
		if (s.length()>i) {
			s = s.substring(i+1, s.length());
		}
		return s;
	}
}



然后struts.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd" >
<struts>

	<constant name="struts.ui.theme" value="simple" />
	<constant name="struts.ui.templateDir" value="template" />
	<constant name="struts.ui.templateSuffix" value="ftl" />

	<constant name="struts.devMode" value="true"></constant>
	<constant name="struts.configuration.xml.reload" value="true"></constant>
	
	<package name="myIntercepter" extends="struts-default" abstract="true">
		<!-- 拦截器 -->
		<interceptors>
			<!-- 自定义拦截器 -->
			<interceptor name="sessionItercepter" class="com.test.intercepter.SessionIntercepter" />
			<!-- 配制默许的拦截器到拦截器栈 -->
            <interceptor-stack name="sessionStack">
                <!-- 此处先后顺序没影响-->
                <interceptor-ref name="defaultStack" />
                <interceptor-ref name="sessionItercepter" />  <!-- 加上自己定义的拦截器 -->
            </interceptor-stack>
		</interceptors>
	</package>
	
	
	<package name="default" extends="myIntercepter">
	
		<!-- 全局跳转 -->
		<global-results >
			<result name="timeout">sessionout.jsp</result>
		</global-results>
		
		<action name="userAction" class="com.test.user.action.UserAction">
			<!-- 登录成功 -->
			<result name="right">main.jsp</result>
			<!-- 登录失败 -->
			<result name="error">error.jsp</result>
			<!-- 用户列表 -->
			<result name="all">all.jsp</result>
			<!-- 注销后返回登录,注:这里要重定向 -->
			<result name="login" type="redirect">/login.jsp</result>
			
			<result name="updateOK" type="redirect">userAction!getAllUserInit.action</result>
			
			<!-- 使用拦截器,一般配置在result之后, -->
			<interceptor-ref name="sessionStack"></interceptor-ref><!-- 调用拦截器栈 -->
		</action>
	</package>
	
</struts>



你可能感兴趣的:(java,html,Ajax,struts)