web开发程序员技术干货

struts2自定义拦截器

2017-08-16  本文已影响24人  rainumdo

题目:使用struts2自定义拦截器,完成用户登陆才能访问权限的实现

  1. 定义拦截器
    在struts.xml中定义拦截器使用标签<Intercaptors>、<Intercapter>。
    <interceptors>
            <interceptor name="test" class="Intercaptor.Intercaptor" />
            <interceptor-stack name="testStack">
                <interceptor-ref name="defaultStack"/>
                <interceptor-ref name="test" />
            </interceptor-stack>
    </interceptors>

注:当我们为某个action添加Intercaptor时就会放弃struts2的其他的拦截器,所以我们要把自定义的拦截器放在一个一个拦截器栈中。

name属性就是Intercaptor.Intercaptor类在服务器上的一个实例
class属性就是这个拦截器的的类

  1. 实现拦截器
    拦截器的java类要实现Intercaptor这个接口和里面的方法intercept()。我们这里拦截的条件是用户是否登陆,也就是session中的user变量是否为空。
public class Intercaptor implements Interceptor{

    public void destroy() {
    }

    public void init() {

    }

    public String intercept(ActionInvocation invocation) throws Exception {
        Object user=ActionContext.getContext().getSession().get("user");
        if(user!=null){
            return  invocation.invoke();
        }
        ActionContext.getContext().put("message", "请先登陆");
        return "success";
    }
}
  1. 实现业务逻辑
    <action name="Action" class="Action.Action">
            <interceptor-ref name="test"></interceptor-ref>
            <result name="success">Message.jsp</result>
    </action>
  1. 其他
public class Action extends ActionSupport{
    private String message;
    
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String execute() throws Exception {
        return "success";
    }
}
  <body>
    用户状态:${user!=null?"已登陆":"未登陆"}<br>
    <a href="UserLogin.jsp">用户登陆</a>
    <a href="UserQuit.jsp">用户退出</a>
    <form action="<%request.getContextPath(); %>/testIntercaptor/Action">
        <input type="submit" value="登陆后的操作">
    </form>
  </body>
登陆页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

 登陆成功
   <%
    request.getSession().setAttribute("user", "user");
    response.setHeader("refresh", "1;url=index.jsp");
   %>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

 退出成功
   <%
    request.getSession().removeAttribute("user");
        response.setHeader("refresh", "1;url=index.jsp");
   %>
  <body>
    ${message } <br/>
  <s:debug></s:debug>
  </body>
上一篇 下一篇

猜你喜欢

热点阅读