查看本例之前首先要大概了解struts2的理论知识(点击查看)
本例实现了一个权限拦截器!
需求:要求用户登录,且必须为指定用户名才可以查看系统中的某个视图资源,如果不满足这两个条件,系统直接转入登录页面!
问题:怎样检查用户登录?
答:跟踪用户的HTTP Session
实现方式有两种:
1.在每个action执行处理逻辑之前,先执行权限检查!但是多了很多重复代码,这是我们不愿意看到的!
2.将权限检查逻辑放在拦截器中,解决了方法一种重复代码的问题!
下面以第二种实现方式实现这个实例:
步骤:
1.搭建struts2环境(点击查看详细搭建过程)
2.实现拦截器类(继承AbstractInterceptor)

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;public class AuthorityInterceptor extends AbstractInterceptor{//拦截action处理的拦截方法@Overridepublic String intercept(ActionInvocation invocation) throws Exception {//取得请求相关的ActionContext实例ActionContext act=invocation.getInvocationContext();//取出名为user的session属性String  user = (String)act.getSession().get("user");//如果user不为空且用户名是testif(user!=null&&"test".equals(user)){//放行到下一个拦截器或者action中的方法return invocation.invoke();}((ActionSupport)invocation.getAction()).addActionError("sorry,还没有登录");//直接返回login逻辑视图return Action.LOGIN;}}

3.实现Action

package action;import java.util.Map;import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.ValueStack;
/*** * @author User**/
public class LoginAction  extends ActionSupport{private String userName;private String pwd;public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}public String execute() throws Exception {
//用户名是lee密码是123或者用户名是test密码是123都是正确的用户名和密码      if("lee".equals(getUserName())||"test".equals(getUserName())&&"123".equals(getPwd())){//获取sessionMap<String, Object> session = ActionContext.getContext().getSession();session.put("user", getUserName());return SUCCESS;}else{ValueStack valueStack = ActionContext.getContext().getValueStack();valueStack.set("error", "请输入正确的用户名和密码");return INPUT;}}//查看图书列表public String view() throws Exception {return SUCCESS;}
}

4.编写jsp页面
4.1loginForm.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!--引入struts2标签  -->
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><base href="<%=basePath%>"><title>My JSP 'traditional.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body>${error}<s:form action="test/loginPro" method="post"> <s:textfield name="userName" label="用户名"/><s:textfield name="pwd" label="密码"/><s:submit value="提交"/></s:form></body>
</html>

4.2viewBook.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!--引入struts2标签  -->
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><base href="<%=basePath%>"><title>My JSP 'traditional.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body>图书展示</body>
</html>

4.3viewRequest.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!--引入struts2标签  -->
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><base href="<%=basePath%>"><title>My JSP 'traditional.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body><a href="test/viewBook">点击查看图书</a></body>
</html>

5.配置struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""http://struts.apache.org/dtds/struts-2.3.dtd">
<struts><!-- 包为lee --><package name="lee"  extends="struts-default" namespace="/test" ><!-- 配置拦截器 --><interceptors><interceptor name="authority" class="interceptor.AuthorityInterceptor"></interceptor></interceptors><!-- 定义全局result (因为大部分action都要跳到loginForm.jsp页面,避免写重复代码,所以定义全局result)--><global-results><result name="login">/WEB-INF/content/loginForm.jsp</result></global-results><!-- 配置action --><!-- 若没有指定class属性 默认使用ActionSupport --><action name="viewBook" class="action.LoginAction" method="view"><!-- 通过拦截器的检查会调到viewBook.jsp页面 --><result name="success">/WEB-INF/content/viewBook.jsp</result><!-- 引用默认拦截器 因为action中显示应用了authority拦截器--><interceptor-ref name="defaultStack"></interceptor-ref><!-- 使用自定义的拦截器 --><interceptor-ref name="authority"></interceptor-ref></action><action name="loginPro" class="action.LoginAction"><!-- 登录成功以后,转到下一个action --><result name="success" type="chain">viewBook</result><!-- 当输入的账号密码是错误的 跳到loginForm.jsp页面 --><result name="input">/WEB-INF/content/loginForm.jsp</result></action><!--配置action  这个action可以处理各种请求  目的是为了保护jsp页面 将jsp页面放在WEB-INF下 这个action一般放在所有action之后  --><action name="*"> <!--直接跳到*所代表的页面  --><result>/WEB-INF/content/{1}.jsp</result></action></package>
</struts>

代码编写完毕,查看文件结构(使用myEclipse作为开发工具,tomcat作为服务器)

发布以后测试:
测试分为六种情况
情况一:用户没有登录直接访问viewBook.jsp页面
地址:http://127.0.0.1:8080/struts2Study37/test/viewBook
结果:跳转到loginForm.jsp页面
分析:当输入这个地址以后,发送test/viewBook请求,该请求被权限拦截器拦截(struts.xml中配置了),拦截器检测到用户没有登录,执行拦截器中的return Action.LOGIN;代码,于是跳转到loginForm.jsp页面!
情况二:用户访问loginForm.jsp页面,输入错误的账号和密码
地址:http://127.0.0.1:8080/struts2Study37/test/loginForm
结果:仍在loginForm.jsp页面,提示请输入正确的账号和密码
分析:点击登录之后,发送的是test/loginPro请求,该请求拦截器不拦截(struts.xml配置了),执行loginAction中的execute方法,用户名和密码不匹配,执行execute方法中的return INPUT;代码,于是跳转到loginForm.jsp页面
情况三:用户访问loginForm.jsp页面,输入正确的账号和密码(账号是lee密码是123)
地址:http://127.0.0.1:8080/struts2Study37/test/loginForm
结果:仍在loginForm.jsp页面
分析:点击登录以后,发送test/loginPro请求,执行loginAction中的execute方法,用户名和密码匹配,执行execute方法中的return SUCCESS;代码,于是跳转到viewBook这个action(struts.xml中配置了),这个请求拦截器会进行拦截,检测到用户虽然登录,但是用户名不匹配,执行拦截器中的return Action.LOGIN;代码,于是跳转到loginForm.jsp页面!
情况四:用户访问loginForm.jsp页面,输入正确的账号和密码(账号是test密码是123)
地址:http://127.0.0.1:8080/struts2Study37/test/loginForm
结果:出现“图书展示”四个大字
分析:点击登录以后,发送test/loginPro请求,执行loginAction中的execute方法,用户名和密码匹配,执行execute方法中的return SUCCESS;代码,于是跳转到viewBook这个action(struts.xml中配置了),这个请求拦截器会进行拦截,检测到用户登录,而且用户名匹配,执行拦截器放行,执行loginAction中的view()方法,于是跳转到viewBook.jsp页面!
情况五:用户直接在地址栏中输入http://127.0.0.1:8080/struts2Study37/test/viewBook
结果:出现“图书展示”四个大字
分析:当输入这个地址以后,发送test/viewBook请求,该请求被权限拦截器拦截(struts.xml中配置了),拦截器检测到用户已经登录且用户名匹配,执行拦截器放行,执行loginAction中的view()方法,于是跳转到viewBook.jsp页面!
情况六:超过一定时间、服务器重启、浏览器关闭后,再输入http://127.0.0.1:8080/struts2Study37/test/viewBook
结果:跳转到loginForm.jsp页面
分析:session已经失效,若要出现情况五的结果,需要再次执行情况四的步骤!

Struts2拦截器实例-权限拦截器相关推荐

  1. python装饰器实例-Python装饰器用法实例总结

    本文实例讲述了Python装饰器用法.分享给大家供大家参考,具体如下: 一.装饰器是什么 python的装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能, ...

  2. python装饰器实例-Python装饰器实用例子

    Python里我们经常能见到@开头的句法,也就是人们常说的装饰器(decorator).装饰器是Python非常重要的一部分,能够产出更易于维护的代码.这篇文章会给大家带来装饰器的介绍以及几个实用的例 ...

  3. python装饰器实例-python装饰器实例大详解

    原标题:python装饰器实例大详解 一.作用域 在python中,作用域分为两种:全局作用域和局部作用域. 全局作用域是定义在文件级别的变量,函数名.而局部作用域,则是定义函数内部. 关于作用域,我 ...

  4. python装饰器实例-Python装饰器原理与简单用法实例分析

    本文实例讲述了Python装饰器原理与简单用法.分享给大家供大家参考,具体如下: 今天整理装饰器,内嵌的装饰器.让装饰器带参数等多种形式,非常复杂,让人头疼不已.但是突然间发现了装饰器的奥秘,原来如此 ...

  5. python装饰器实例-python装饰器案例

    普通装饰器函数 计算函数的运行时间 import requests import time import re # 黑名单 filter_urls = ['www.hao123.com', 'www. ...

  6. python装饰器实例-python装饰器使用实例详解

    这篇文章主要介绍了python装饰器使用实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 python装饰器的作用就是在不想改变原函数代码的情 ...

  7. python装饰器实例-Python 装饰器简单示例

    简单装饰器示例:def servlet(func): print("into servlet")#1 print(servlet)#2 def foo(): print(" ...

  8. python装饰器实例-python 装饰器(三):装饰器实例(一)

    示例 7-15 定义了一个装饰器,它会在每次调用被装饰的函数时计时,然后把经过的时间.传入的参数和调用的结果打印出来. 示例 7-15 一个简单的装饰器,输出函数的运行时间 importtimedef ...

  9. python装饰器实例-Python装饰器简单用法实例小结

    本文总结分析了Python装饰器简单用法.分享给大家供大家参考,具体如下: 装饰器在python中扮演着很重要的作用,例如插入日志等,装饰器可以为添加额外的功能同时又不影响业务函数的功能. 比如,运行 ...

最新文章

  1. nUnit,凑合着测试
  2. 【视频课】图像分割最新内容来了(言有三新录制4部分实例分割算法详解)
  3. 阅读作业:大泥球、敏捷、人件
  4. 浏览器中的WebSocket(ws://127.0.0.1:9988);
  5. uni-app的列表搜索框_微信怎么搜索小程序?小程序能有什么用?
  6. 云服务器之间进行文件转移,windows服务器之间文件如何转移
  7. 诺基亚N8-00测评
  8. Image2LaTeX + AxMath:公式自动识别 + word 编辑公式
  9. java爬虫爬取天眼查_Java爬虫爬取京东商品信息
  10. 【SpringBoot】MultipartResolver文件解析器
  11. android空间深度清理,安卓手机垃圾深度清理技巧
  12. 文本文件里如何快速在每行头尾都加上指定的内容---正则表达式(一)
  13. 2022-06-23 JVM学习
  14. 神通数据库自助在线查询
  15. python 逻辑运算符 and or
  16. 大理石在哪【搜索排序】
  17. SpringBoot练手项目总结
  18. 【从AWS亚马逊平台上的s3存储桶上下载文件到win10电脑上】
  19. 前端插件clipboard 操作剪切板
  20. C++ 纯 OpenCV 实现扑克牌实时识别

热门文章

  1. C语言2048源代码
  2. 【ResNet】Pytorch从零构建ResNet50
  3. java优先级队列(堆)
  4. 关于庞果网数组排序的问题
  5. 获取正整数的每一位数字(C)
  6. android抓包工具——fiddler与charles的基本操作(弱网模拟,map local/remote、breakpoint 等)
  7. 2014腾讯校招面试之一总结
  8. Ubuntu 安装 cnpm
  9. 『原创』教你如何使用Sandcastle Help File Builder建立MSDN风格的代码文档
  10. 手机信号的发射与接收