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

struts2自定义拦截器的示例代码

程序员文章站 2024-02-18 21:00:34
题目:使用struts2自定义拦截器,完成用户登陆才能访问权限的实现 在session中存放user变量表示用户登陆,若user为空则用户没有登陆,反之登陆...

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

  1. 在session中存放user变量表示用户登陆,若user为空则用户没有登陆,反之登陆
  2. 显示提示信息(请先登录)

定义拦截器

在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属性就是这个拦截器的的类

实现拦截器

拦截器的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";
  }
}

实现业务逻辑

在action中添加拦截器

  <action name="action" class="action.action">
      <interceptor-ref name="test"></interceptor-ref>
      <result name="success">message.jsp</result>
  </action>

其他

action的实现

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";
  }
}

index.jsp

 <body>
  用户状态:${user!=null?"已登陆":"未登陆"}<br>
  <a href="userlogin.jsp" rel="external nofollow" >用户登陆</a>
  <a href="userquit.jsp" rel="external nofollow" >用户退出</a>
  <form action="<%request.getcontextpath(); %>/testintercaptor/action">
    <input type="submit" value="登陆后的操作">
  </form>
 </body>

struts2自定义拦截器的示例代码

userlogin.jsp

在request.getsesssion中存放user变量

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>

 登陆成功
  <%
  request.getsession().setattribute("user", "user");
  response.setheader("refresh", "1;url=index.jsp");
  %>

userquit.jsp

移除request.getsesssion中user变量

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>

 退出成功
  <%
  request.getsession().removeattribute("user");
    response.setheader("refresh", "1;url=index.jsp");
  %>

message.jsp

简单是输出message和debug

 <body>
  ${message } <br/>
 <s:debug></s:debug>
 </body>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。