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

发布时间:2020-09-22 07:28:54 作者:rainumdo
来源:脚本之家 阅读:103

题目:使用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>

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

推荐阅读:
  1. Struts2的OGNL标签详解
  2. Struts2参数的封装

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

struts2 拦截器 st

上一篇:使用Redis实现UA池的方案

下一篇:python可视化实现KNN算法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》