struts2中用interceptor实现权限控制

    在jsp servlet中我们通常使用Servlet Filter控制用户是否登入, 是否有权限转到某个页面。在struts2中我们应该会想到他的拦截器(Interceptor), Interceptor在struts2中起着非常重要的作用。很多struts2中的功能都是使用Interceptor实现的。

    需求:简单的登入界面,让用户输入用户名,密码,记住密码(remember me)。如果用户选中remember me的话,下次就不需要再登入了(使用cookie实现, 用需要点击logout取消remeber me功能)。如果用户起始输入的地址不是登入页面的话,在用户登入之后需要转到用户输入的起始地址。

功能概图:


项目文件概图:


struts.xml 配置部分:

	<!-- 演示权限控制 --><package name="authority" extends="struts-default" namespace="/authority"><interceptors><interceptor name="loginInterceptor" class="com.gq.action.LoginInterceptor"/><interceptor-stack name="loginDefaultStack"><interceptor-ref name="loginInterceptor"/><interceptor-ref name="defaultStack"/></interceptor-stack></interceptors><default-interceptor-ref name="loginDefaultStack"/><global-results><result name="login" type="redirect">/authority/login.jsp</result></global-results> <action name="Index" class="com.gq.action.IndexAction"><result>/authority/main.jsp</result><interceptor-ref name="loginDefaultStack"/></action><action name="Logout" class="com.gq.action.LogoutAction"></action><action name="Login" class="com.gq.action.LoginAction" method="login"><result type="redirect">${goingToURL}</result><result name="input">/authority/login.jsp</result><interceptor-ref name="defaultStack"/></action><!-- 没有实现 class <action name="Register" class="com.gq.action.LoginAction"><result type="redirect">/authority/login.jsp</result><result name="input">/authority/register.jsp</result><interceptor-ref name="defaultStack"/></action>--></package>
各文件描述和源代码:

IndexAction.java,直接跳转到 main.jsp,该action 名称为 “Index”,并配置有登陆权限验证拦截器

public class IndexAction extends ActionSupport {private static final long serialVersionUID = 7078603236740619967L;@Overridepublic String execute() throws Exception {// Just return to /main.jspreturn SUCCESS;}}
LoginAction.java,验证“登陆名”和“密码”是否正确,保存“用户”到 Session中,并根据参数决定是否保存Cookie

其中要判断:

1、用户直接进入 login.jsp的页面?验证成功后,跳转到 main.jsp页面。

2、用户从其他页面 xxx.jsp,因为没有权限验证失败而回到 login.jsp?则验证成功后,跳转到 xxx.jsp页面。

(这里为了演示简化,xxx.jsp 就指定为 main.jsp 页面)

public class LoginAction extends ActionSupport implements ServletResponseAware, SessionAware {private static final long serialVersionUID = 2965422004870746408L;private String loginName;private String password;private boolean rememberMe;private HttpServletResponse response;private Map session;private String goingToURL;public String getGoingToURL() {return goingToURL;}public void setGoingToURL(String goingToURL) {this.goingToURL = goingToURL;}public boolean isRememberMe() {return rememberMe;}public void setRememberMe(boolean rememberMe) {this.rememberMe = rememberMe;}public String getLoginName() {return loginName;}public void setLoginName(String loginName) {this.loginName = loginName;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public void setServletResponse(HttpServletResponse response) {this.response = response;}public void setSession(Map session) {this.session = session;}public String login() throws Exception {System.out.println("In login..." + getLoginName());try {User user = new UserDAO().attemptLogin(getLoginName(), getPassword());//Add cookieif (rememberMe) {response.addCookie(createCookie(user));}//Add into sessionsession.put(LoginInterceptor.USER_SESSION_KEY, user);String goingToURL = (String) session.get(LoginInterceptor.GOING_TO_URL_KEY);if (StringUtils.isNotBlank(goingToURL)){setGoingToURL(goingToURL);session.remove(LoginInterceptor.GOING_TO_URL_KEY);} else {setGoingToURL("Index.action");}return SUCCESS;} catch (UserNotFoundException e) {addActionMessage("user name or password is not corrected.");return INPUT;}}Cookie createCookie( User user ){int SEVEN_DAYS = 60 * 60 * 24 * 7;Cookie cookie = new Cookie(LoginInterceptor.COOKIE_REMEMBERME_KEY, createValue(user));cookie.setMaxAge(SEVEN_DAYS);return cookie;}String createValue( User user ){return user.getLoginName()+ "==" + user.getPassword();}
}
LoginInterceptor.java,登陆拦截器,根据 Session判断用户是否在线或根据Cookie解析能否登陆。

public class LoginInterceptor extends AbstractInterceptor {private static final long serialVersionUID = -5889213773673649255L;public static final String USER_SESSION_KEY = "wallet.session.user";public static final String COOKIE_REMEMBERME_KEY = "wallet.cookie.rememberme";public static final String GOING_TO_URL_KEY = "GOING_TO";public static final String LOGIN = "login";@Overridepublic String intercept(ActionInvocation invocation) throws Exception {System.out.println("In LoginInterceptor...");ActionContext actionContext = invocation.getInvocationContext();HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);//用户在登录状态Map<String,String> session = actionContext.getSession();if (session != null && session.get(USER_SESSION_KEY) != null) {System.out.println("In user is login, saved information in session...");return invocation.invoke();}//用户从Cookie中解析信息,然后登录return loginFromCookie(request, invocation, session);}String loginFromCookie(HttpServletRequest request, ActionInvocation invocation,Map session) throws Exception{System.out.println("In loginFromCookie...");Cookie[] cookies = request.getCookies();if( cookies == null ){	//No cookiessetGoingToURL(session, invocation);return LOGIN;}Cookie cookie = findCookieByName( cookies );if( cookie == null ){	//No cookie by the namesetGoingToURL(session, invocation);return LOGIN;}String loginName = parseLoginName( cookie );String password  = parsePassword( cookie );if( loginName == null || password == null ){	//parse loginName or password fail...setGoingToURL(session, invocation);return LOGIN;}try {User user = new UserDAO().attemptLogin(loginName, password);session.put(USER_SESSION_KEY, user);return invocation.invoke();} catch (UserNotFoundException e) {setGoingToURL(session, invocation);return LOGIN;}}Cookie findCookieByName(Cookie[] cookies) {for( Cookie cookie : cookies ){if(COOKIE_REMEMBERME_KEY.equals(cookie.getName())){return cookie;}}return null;}String parsePassword(Cookie cookie) {String value = cookie.getValue();if (StringUtils.isBlank(value)) {return null;}String[] split = value.split("==");if( split.length < 2 ){return null;}return split[1];}String parseLoginName(Cookie cookie) {String value = cookie.getValue();if (StringUtils.isBlank(value)) {return null;}String[] split = value.split("==");return split[0];}private void setGoingToURL(Map session, ActionInvocation invocation) {String url = "";String namespace = invocation.getProxy().getNamespace();if (StringUtils.isNotBlank(namespace) && !namespace.equals("/")) {url = url + namespace;}String actionName = invocation.getProxy().getActionName();if (StringUtils.isNotBlank(actionName)) {url = url + "/" + actionName + ".action";}session.put(GOING_TO_URL_KEY, url);}
}
LogoutAction.java,注销,清空Session中的信息,删除Cookie

public class LogoutAction extends ActionSupport implements ServletRequestAware,ServletResponseAware {private static final long serialVersionUID = -7680746852412424580L;private HttpServletRequest request;private HttpServletResponse response;public void setServletRequest(HttpServletRequest request) {this.request = request;}public void setServletResponse(HttpServletResponse response) {this.response = response;}public String execute() throws Exception {System.out.println("In logout..." + getNameForLogout());removeFromSession();removeFromCookies();return "login";}void removeFromSession() {HttpSession session = request.getSession(false);if (session != null)session.removeAttribute(LoginInterceptor.USER_SESSION_KEY);}void removeFromCookies() {Cookie[] cookies = request.getCookies();if (cookies != null) {for (Cookie cookie : cookies) {if (LoginInterceptor.COOKIE_REMEMBERME_KEY.equals(cookie.getName())) {cookie.setValue("");cookie.setMaxAge(0);response.addCookie(cookie);return;}}}}String getNameForLogout(){HttpSession session = request.getSession(false);if( session == null){return "Session is null...";}User user = (User)session.getAttribute(LoginInterceptor.USER_SESSION_KEY);return user.getLoginName();}
}

User.java,一个简单的JavaBean

public class User {// Used for loginprivate String loginName;private String password;// Information of userprivate String name;private String sex;private int age;//get/set 方法@Overridepublic boolean equals(Object object) {if(object==null || getClass()!=object.getClass()){return false;}User user = (User)object;return strEquals(getLoginName(), user.getLoginName()) &&strEquals(getPassword(), user.getPassword()) &&strEquals(getName(), user.getName()) &&strEquals(getSex(), user.getSex()) &&getAge() == user.getAge();}private boolean strEquals( String s1, String s2 ){if( s1 == null ){return false;}return s1.equals(s2);}@Overridepublic int hashCode() {int result = 47;result = 37*result + Integer.valueOf(age).hashCode();result = 37*result + (loginName==null ? 0 : loginName.hashCode());result = 37*result + (password==null ? 0 : password.hashCode());result = 37*result + (name==null ? 0 : name.hashCode());result = 37*result + (sex==null ? 0 : sex.hashCode());return result;}}
UserDAO.java,一个简单的模拟的dao

public class UserDAO {private static Map<String, User> users = new HashMap<String, User>();public UserDAO(){mockUsers();}public User attemptLogin(String loginName, String password) throws UserNotFoundException{User user;if( (user=findUser(loginName)) == null ){throw new UserNotFoundException("Invalid User!");}if( !validPassword(password, user) ){throw new UserNotFoundException("Invalid Password!");}return user;}User findUser( String loginName ){return users.get(loginName);}boolean validPassword( String password, User user ){return password.equals(user.getPassword());}private void mockUsers(){User zhangsan = new User();zhangsan.setLoginName("zhangsan@qq.com");zhangsan.setPassword("zhangsan123");zhangsan.setName("zhangsan");zhangsan.setAge(22);zhangsan.setSex("man");User lisi = new User();lisi.setLoginName("lisi@qq.com");lisi.setPassword("lisi123");lisi.setName("lisi");lisi.setAge(25);lisi.setSex("woman");User wangwu = new User();wangwu.setLoginName("wangwu@qq.com");wangwu.setPassword("wangwu123");wangwu.setName("wangwu");wangwu.setAge(27);wangwu.setSex("man");users.put(zhangsan.getLoginName(), zhangsan);users.put(lisi.getLoginName(), lisi);users.put(wangwu.getLoginName(), wangwu);}
}
UserNotFoundException.java,之定义封装的一个 Exception

public class UserNotFoundException extends Exception{private static final long serialVersionUID = -5207325846250567308L;public UserNotFoundException( String message ){super( message );}}
login.jsp,登陆页面

<%@ page language="java" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><base href="<%=basePath%>"><title>Login</title></head><body>
<h2>Login</h2> 
<s:actionmessage/>
<s:actionerror/>
<s:form action="/authority/Login.action" method="post" validate="false" theme="xhtml"><s:textfield name="loginName" label="Username"></s:textfield><br/><s:password name="password" label="Password"></s:password><br/><s:checkbox label="Remember Me" name="rememberMe"></s:checkbox><s:submit value="%{'Login'}"></s:submit> 
</s:form>
<a href="/test_struct2/authority/register.jsp">Register</a>
</body>
</html>

main.jsp主页面

<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><base href="<%=basePath%>"><title>My JSP 'main.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>This is Main page. <br><a href="/test_struct2/authority/Logout.action">Logout</a></body>
</html>
register.jsp ,未实现。。。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/498063.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

CGAL的三维点集

CGAL提供了几种处理点集的算法&#xff0c;从形状检测到通过标准点集处理工具进行的表面重建。 虽然这些算法不强制使用特定的数据结构&#xff0c;但该软件包提供了一个3D点集结构&#xff0c;使用户更容易处理附加属性&#xff0c;如法向量、颜色、标签&#xff0c;并在其上调…

2018年AI智商将达到多少?未来智能实验室启动第三次世界AI智商评测

来源&#xff1a; 人工智能学家 概要&#xff1a;21世纪以来&#xff0c;人工智能领域陆续爆发很多重要事件。其中最吸引人们眼球的&#xff0c;当属2016年战胜了人类围棋冠军并开始能够从0自我学习的AlphaGo。 一.人工智能能否超越人类智慧的争议 21世纪以来&#xff0c;人工智…

二进制函数_Go二进制文件逆向分析从基础到进阶——MetaInfo、函数符号和源码文件路径列表...

书接前文&#xff0c;本文主要介绍 Go 二进制文件中 Meta Information 的解析&#xff0c;与函数符号和源码文件路径列表的提取。最后详细介绍一下 Moduledata 这个结构。传送门&#xff1a;Go二进制文件逆向分析从基础到进阶——综述05Meta information>>>>5.1 Go…

七大科技巨头统治世界?

来源&#xff1a;亿欧智库 概要&#xff1a;我想无论是业内人士还是普通用户&#xff0c;都会思考为什么是他们成为最大的公司&#xff1f; 2017年秋天&#xff0c;随着腾讯和阿里巴巴两家中国公司市值的不断上涨&#xff0c;全球市值头部公司刚好是七大科技巨头&#xff08;下…

用户权限管理——DB设计篇

来源&#xff1a;http://www.noahweb.net/mail/2/Project.htm#biao B/S系统中的权限比C/S中的更显的重要&#xff0c;C/S系统因为具有特殊的客户端&#xff0c;所以访问用户的权限检测可以通过客户端实现或通过客户端服务器检测实现&#xff0c;而B/S中&#xff0c;浏览器是每一…

雷克世界:Gyrfalcon加入芯片角斗场,又一款改变AI界的产品问世

来源&#xff1a;雷克世界 概要&#xff1a;随着人工智能产业规模扩大&#xff0c;众多巨头和初创公司纷纷加入人工智能芯片领域。 随着人工智能产业规模扩大&#xff0c;众多巨头和初创公司纷纷加入人工智能芯片领域&#xff0c;今天来了解一家旨在开发低成本、低功耗、高性能…

报告怎么看_体检报告怎么看? 超实用的阅读指南来了!

体检报告怎么看&#xff1f;超实用的阅读指南来了&#xff01;要点概括除了禁食禁水可以吞口水吗&#xff1f;这样的问题&#xff0c;还有胆固醇、甘油三酯、胆红素…这些指标都是什么意思&#xff1f;出现升高或降低提示了怎样的身体变化&#xff1f;九图带你读懂&#xff01;…

从基础设施的演变,看人工智能到底需要什么样的底层平台

来源&#xff1a;亿欧 概要&#xff1a;大数据、大容量存储、弹性计算和各类算法的发展&#xff0c;尤其是在深度学习领域的发展&#xff0c;带来了各类脑洞大开的创新应用。 机器学习和人工智能的时代已经到来。大数据、大容量存储、弹性计算和各类算法的发展&#xff0c;尤其…

如何看屈曲因子_Abaqus 非线性屈曲分析方法

通常情况下&#xff0c;我们只用关注产品结构本身的强度和刚度满足一定的要求或标准即可。但实际工程中&#xff0c;对于像细长类的结构、薄壁结构&#xff0c;我们还得考虑它的稳定性问题&#xff0c;这也就是我们通常所说的失稳问题或者塌陷问题。在有限元分析中&#xff0c;…

人类首张脑电波连接全图问世

来源&#xff1a;科技日报 概要&#xff1a;美国宾夕法尼亚大学的神经学家根据300名接受神经外科手术患者大脑中30000个电极的数据&#xff0c;绘制出第一张脑电波连接全图。 美国国防部高级研究计划局&#xff08;DARPA&#xff09;资助的、与“恢复活跃记忆”相关的大脑研究项…

全球半导体产业迁移 中国的机遇与挑战

来源&#xff1a;36氪 概要&#xff1a;商务部24日发布公告说&#xff0c;以附加“限制性条件”的形式批准了日月光半导体收购矽品精密股权案。 商务部24日发布公告说&#xff0c;以附加“限制性条件”的形式批准了日月光半导体收购矽品精密股权案。这个附加的“限制性条件”&…

阿里智能对话交互实践与创新

来源&#xff1a;人工智能头条 作者 &#xff1a;孙健&#xff0c;李永彬&#xff0c;陈海青&#xff0c;邱明辉 概要&#xff1a;过去 20 多年&#xff0c;互联网及移动互联网将人类带到了一个全新的时代&#xff0c;如果用一个词来总结和概括这个时代的话&#xff0c;「连接」…

IDC Future Scape : 2018年全球物联网十大趋势性预测,5G将加速IoT发展

作者&#xff1a;Dudu 概要&#xff1a;预计到2021年前后&#xff0c;5G、物联网数据分析、物联网支出管理、区块链、物联网服务将成为市场主流。 2019年&#xff0c;IoT行业中&#xff0c;边缘基础设施将成为市场主流&#xff0c;多用于单个部门的业务板块中。 到了2020年&am…

mysql 解释 游标赋值_Mysql_游标

MySQL中的游标是一个十分重要的概念。游标提供了一种对从表中检索出的数据进行操作的灵活手段&#xff0c;就本质而言&#xff0c;游标实际上是一种能从包括多条数据记录的结果集中每次提取一条记录的机制。MySQL中的游标的语法如下&#xff1a;DECLARE cursor-name CURSOR FOR…

意见征集,世界AI智商评测量标准2018年新版讨论方案

来源&#xff1a;未来智能实验室 对于本次2018年世界AI智商评测的量表更新 &#xff0c;有两个问题希望得到您的意见&#xff1a;1.如果按上述智力因素进行增加&#xff0c;您认为他们的权重应该是多少&#xff0c;其他已有的智力因素权重应该调整为多少&#xff1b;2.您认为考…

人工智能的价值地图:AI产业增强革命的模式与路径

来源&#xff1a;腾讯研究院 概要&#xff1a;人工智能所蕴含的力量让人向往又恐惧。2016年的两次人机大战第一次让公众认识到人工智能的强大力量。 “智造”并不是一个新词&#xff0c;几年前&#xff0c;我们可以看到数字技术从虚拟世界向实体世界渗透。3D打印、激光切割等一…

那么多GAN哪个好?谷歌大脑泼来冷水:都和原版差不多

来源&#xff1a;量子位 概要&#xff1a;从2014年诞生至今&#xff0c;生成对抗网络&#xff08;GAN&#xff09;热度只增不减&#xff0c;各种各样的变体层出不穷。 从2014年诞生至今&#xff0c;生成对抗网络&#xff08;GAN&#xff09;热度只增不减&#xff0c;各种各样的…

java 中获取file的长度为0_Java核心技术梳理-IO

一、引言IO(输入/输出)&#xff0c;输入是指允许程序读取外部数据(包括来自磁盘、光盘等存储设备的数据)、用户输入数据。输出是指允许程序记录运行状态&#xff0c;将程序数据输出到磁盘、光盘等存储设备中。IO的主要内容包括输入、输出两种IO流&#xff0c;这两种流中又分为字…

福布斯:2018年将改变世界的九股科技大趋势

来源&#xff1a;咕噜网 概要&#xff1a;2018年又会有哪些重要科技趋势会改变世界呢&#xff1f;《福布斯》杂志今天发表文章&#xff0c;公布了将会在明年及日后改变世界的9股科技大趋势。 据《福布斯》杂志北京时间12月4日报道&#xff0c;2017年即将结束。这一年&#xff0…