拦截器

1、定义Action
   package action;

import com.opensymphony.xwork2.ActionContext;

public class InterceptorAction {
     public String execute(){
         ActionContext.getContext().put("message", "登录成功");
    	 return "message";
     }
}


2、定义拦截器
package util;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

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

public class PessInterceptor implements Interceptor {

	@Override
	public void destroy() {
	}

	@Override
	public void init() {
	}

	@Override
	public String intercept(ActionInvocation process) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		Object user = request.getSession().getAttribute("user");
		 if(user != null)
			 return process.invoke();
		 ActionContext.getContext().put("message", "你没有权限访问此操作");
		 return "message";
	}

}

3、注册拦截器
<?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>
       <package name="default" namespace="/" extends="struts-default">
       <interceptors>
          <interceptor name="pess" class="util.PessInterceptor"/>
          <interceptor-stack name="pessim">
             <interceptor-ref name="defaultStack"/>  <!--必须放在自定义拦截器的前面,里面提供了许多核心功能,在struts-default.xml可以查到-->
             <interceptor-ref name="pess"/>
          </interceptor-stack>
        </interceptors>
        <global-results>
            <result name="message">/message.jsp</result>
        </global-results>
               <action name="interceptor" class="action.InterceptorAction">
           <interceptor-ref name="pess"/>
        </action>
    </package>
</struts>


4、用户登录
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<body>
   <%
     session.setAttribute("user","user");
   %>
   用户登录
</body>
</html>

5、用户注销
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<html>
<body>
   <%
    session.removeAttribute("user");
   %>
   注销成功
</body>
</html>
6、登录访问Action
7、注销反问Action

你可能感兴趣的:(java,apache,jsp,xml,struts)