详解使用Spring3 实现用户登录以及权限认证
使用Spring3 实现用户登录以及权限认证
这里我就简单介绍一下,我在实现的时候处理的一些主要的实现。
1.用户登录
<form action="loginAction.do" method="post"> <div class="header"> <h2 class="logo png"></h2> </div> <ul> <li><label>用户名</label><input name="username" type="text" class="text"/></li> <li/> <li><label>密 码</label><input name="password" type="password" class="text" /></li> <li/> <li class="submits"> <input class="submit" type="submit" value="登录" /> </li> </ul> <div class="copyright">© 2013 - 2014 |</div> </form>
以上是前台页面,后台的就是一个简单的逻辑实现:
@RequestMapping(value="loginAction.do", method=RequestMethod.POST) public ModelAndView loginAction(@RequestParam(value="username") String username, @RequestParam(value="password") String password, HttpSession session, HttpServletResponse resp, @RequestParam(value="savetime", required=false) String savetime) { session.removeAttribute(LogConstant.LOGIN_MESSAGE); SystemUserDataBean user = userDao.getSystemUserByUserName(username); ModelAndView view = null; if(user == null) { view = new ModelAndView(new RedirectView("login.html")); session.setAttribute(LogConstant.LOGIN_MESSAGE, "用户名不正确"); return view; } boolean isPasswordCorrect = EncryptionUtil.compareSHA(password, user.getPassword()); if(isPasswordCorrect){ session.setAttribute(LogConstant.CURRENT_USER, username); } else{ view = new ModelAndView(new RedirectView("login.html")); session.setAttribute(LogConstant.LOGIN_MESSAGE, "密码不正确"); } return view; }
2.登录信息
这里,在登录页面有一段JavaScript,来显示密码错误等信息:
<script type="text/javascript"> var login_username_info = '<%=request.getSession().getAttribute("currentUser") == null ? "" : request.getSession().getAttribute("currentUser")%>'; var login_message_info = '<%=request.getSession().getAttribute("login_message") == null ? "" : request.getSession().getAttribute("login_message")%>'; if(login_message_info != null && login_message_info != ''){ alert(login_message_info); } </script>
3.拦截未登录用户的请求
这里,从页面和后台实现了双重拦截:
页面代码如下:
<% if(session.getAttribute("currentUser")==null){ %> window.parent.location='login.html'; <% } %>
后台是一个拦截器(servlet-config.xml):
<!-- 拦截器 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/*.do" /> <bean class="com..log.report.interceptor.AccessStatisticsIntceptor" /> </mvc:interceptor> </mvc:interceptors>
拦截器的实现是
import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class AccessStatisticsIntceptor implements HandlerInterceptor { @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { // TODO Auto-generated method stub } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { // TODO Auto-generated method stub } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception { String uri = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/") +1); if(!AuthorityController.isAuthorized(uri, request.getSession())) { //校验失败 return false; // throw new CustomException(LogConstant.USER_NOT_LOGIN); } return true; }
具体如何校验的,会根据用户的权限,就不介绍了
4.返回未登录前访问的页面
首先在页面添加一段脚本,使用jQuery去访问后台
var page = ""; var loc = decodeURIComponent(window.parent.location); var start = loc.indexOf("Log/") + 8; var end = loc.indexOf(".html"); page = loc.substr(start, end-start); if(page != null && page != '') { alert(page); $.ajax({ type : "get", url : "setPreviousPageAction.do?previousPage=" + page + ".html", success : function(msg){ } }); }
然后,后台有记录这个页面:
@RequestMapping(value="setPreviousPageAction.do") public void setPreviousPageAction(@RequestParam(value="previousPage") String previousPage, HttpSession session){ session.setAttribute(LogConstant.PREVIOUS_PAGE, previousPage); }
在登录完成后,返回这个页面即可。
5.保存用户名密码
登录页面提供一个保存下拉框:
<select class="save_login" id="savetime" name="savetime"> <option selected value="0">不保存</option> <option value="1">保存一天</option> <option value="2">保存一月</option> <option value="3">保存一年</option> </select>
后台在登录时会操作,将信息保存在cookie中:
if(savetime != null) { //保存用户在Cookie int savetime_value = savetime != null ? Integer.valueOf(savetime) : 0; int time = 0; if(savetime_value == 1) { //记住一天 time = 60 * 60 * 24; } else if(savetime_value == 2) { //记住一月 time = 60 * 60 * 24 * 30; } else if(savetime_value == 2) { //记住一年 time = 60 * 60 * 24 * 365; } Cookie cid = new Cookie(LogConstant.LOG_USERNAME, username); cid.setMaxAge(time); Cookie cpwd = new Cookie(LogConstant.LOG_PASSWORD, password); cpwd.setMaxAge(time); resp.addCookie(cid); resp.addCookie(cpwd); }
前台在发现用户未登录时,会取出cookie中的数据去登录:
if(session.getAttribute("currentUser")==null){ Cookie[] cookies = request.getCookies(); String username = null; String password = null; for(Cookie cookie : cookies) { if(cookie.getName().equals("log_username")) { username = cookie.getValue(); } else if(cookie.getName().equals("log_password")) { password = cookie.getValue(); } } if(username != null && password != null) { %> $.ajax({ type : "post", url : "loginByCookieAction.do", data:"username=" + "<%=username%>"+ "&password=" + "<%=password%>", success : function(msg){ if(msg.status == 'success') window.parent.location.reload(); else if(msg.status == 'failed') gotoLoginPage(); } }); <% } else { %> gotoLoginPage(); <% } ...
以上就列出了我在解决登录相关问题的方法,代码有点长,就没有全部列出。
- Springboot+SpringSecurity+JWT实现用户登录和权限认证示例
- Springboot+Shiro记录用户登录信息并获取当前登录用户信息的实现代码
- SpringMVC 实现用户登录实例代码
- springmvc+spring+mybatis实现用户登录功能(上)
- springmvc+spring+mybatis实现用户登录功能(下)
- 利用Spring IOC技术实现用户登录验证机制
- Spring mvc 实现用户登录的方法(拦截器)
- spring aop action中验证用户登录状态的实例代码
- Spring Cloud Gateway 使用JWT工具类做用户登录校验功能
- 使用Spring框架实现用户登录
相关文章
Springboot @Configuration @bean注解作用解析
这篇文章主要介绍了springboot @Configuration @bean注解作用解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2020-02-02Eclipse 开发java 出现Failed to create the Java Virtual Machine错误
这篇文章主要介绍了Eclipse 开发java 出现Failed to create the Java Virtual Machine错误解决办法的相关资料,需要的朋友可以参考下2017-04-04浅析Java ClassName.this中类名.this关键字的理解
Java ClassName.this中类名.this关键字 的理解大家都了解多少,有不太了解的朋友可以参考下本文一起学习学习2016-05-05springboot之端口设置和contextpath的配置方式
这篇文章主要介绍了springboot之端口设置和contextpath的配置方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-01-01IntelliJ IDEA下自动生成Hibernate映射文件以及实体类
这篇文章主要介绍了IntelliJ IDEA下自动生成Hibernate映射文件以及实体类,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-11-11
最新评论