详解使用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();
    <%
  } 

  ...

以上就列出了我在解决登录相关问题的方法,代码有点长,就没有全部列出。

(0)

相关推荐

  • spring mvc实现登录账号单浏览器登录

    在很多web产品中都需要实现在同一时刻,只能允许一个账号同时只能在一个浏览器当中登录.通俗点讲就是当A账号在浏览器1当中登录了,此时在浏览器2中登录A账号.那么在浏览器1中的A账号将会被挤出去,当用户操作浏览器1的页面,页面会跳到登录页面,需要重新登录.那么我们怎么实现这样的功能呢?下面将给大家进行详细的介绍: 原理 用户A使用账号a在浏览器当中登录,然后用户B在另外一台电脑上的浏览器登录账号a,当用户B登录验证成功时,将会触发登录监听类,在监听类当中判断出账号a已经被用户A登录,就把用户A的账

  • Spring MVC+mybatis实现注册登录功能

    本文实例为大家分享了Spring MVC mybatis实现注册登录功能的具体代码,供大家参考,具体内容如下 前期准备: 如下图所示,准备好所需要的包 新建工程,导入所需要的包,在web.xml中配置好所需要的,如下 <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee&q

  • Spring MVC登录注册以及转换json数据

    项目结构; 代码如下: BookController package com.mstf.controller; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.codehaus.jackson.map.ObjectMapper; import com.mstf.

  • springmvc+spring+mybatis实现用户登录功能(上)

    由于本人愚钝,整合ssm框架真是费劲了全身的力气,所以打算写下这篇文章,一来是对整个过程进行一个回顾,二来是方便有像我一样的笨鸟看过这篇文章后对其有所帮助,如果本文中有不对的地方,也请大神们指教. 一.代码结构 整个项目的代码结构如图所示: controller为控制层,主要用于对业务模块的流程控制. dao为数据接入层,主要用于与数据库进行连接,访问数据库进行操作,这里定义了各种操作数据库的接口. mapper中存放mybatis的数据库映射配置.可以通过查看mybatis相关教程了解 mod

  • SpringMVC 实现用户登录实例代码

    SpringMVC的一个登陆小案例 准备工作 创建一个Dynamic Web Project(本人是Eclipse) 添加相关的jar包,构建路径 创建springMVC-servlet.xml,及完善web.xml 创建代码逻辑 目录结构如下 对于新手而言,有一个项目的完整的目录结构是多么幸福的一件事啊. 目录结构 个人建议:注意其中的springMVC-servlet.xml的位置.以及源代码包的名称. 代码实战 首先是大管家,web.xml: <?xml version="1.0&q

  • 详解springmvc控制登录用户session失效后跳转登录页面

    springmvc控制登录用户session失效后跳转登录页面,废话不多少了,具体如下: 第一步,配置 web.xml <session-config> <session-timeout>15</session-timeout> </session-config> 第二步,配置spring-mvc.xml <!-- Session失效拦截 --> <mvc:interceptors> <!-- 定义拦截器 --> <

  • springmvc下实现登录验证码功能示例

    总体思路,简单讲,就是后台生成图片同时将图片信息保存在session,前端显示图片,输入验证码信息后提交表单到后台,取出存放在session里的验证码信息,与表单提交的验证码信息核对. 点击验证码图片时,通过jquery重新请求后台生成验证码图片方法,更换图片. 首先在后端controller里,有这样一个方法: 路径为http://localhost:8888/RiXiang_blog/login/captcha.form,访问这个路径便可以通过response写入图片. @RequestMa

  • 利用Spring IOC技术实现用户登录验证机制

    利用 Spring IOC 技术实现用户登录的验证机制,对用户进行登录验证. 首先利用 Spring 的自动装配模式将 User 对象注入到控制器中,然后将用户输入的用户名和密码与系统中限定的合法用户的用户名和密码进行匹配. 当用户名与密码匹配成功时,跳转到登录成功页面:当用户名与密码不匹配时,跳转到登录失败的页面. 1.创建 User 对象,定义用户名和密码属性,代码如下: package com.importnew; public class User { private String us

  • Spring+MongoDB实现登录注册功能

    本文实例为大家分享了Spring,Spring MVC,MongoDB实现登录注册 的具体代码,供大家参考,具体内容如下 工程目录: Spring配置文件: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springfra

  • webix+springmvc session超时跳转登录页面

    引言 最近做项目,发现ajax请求不能在服务器中直接重定向到登录页面.查了些资料发现jquery的ajax请求有人给出了方法.但是webix的ajax请求和jquery的有些区别.这里模仿jquery的处理方式实现webix的ajax请求session超时跳转. 具体的做法: 1.查看webix.js源码发现webix.ajax只有请求前的监听函数 "onBeforeAjax", 要做到获取返回状态跳转登录页面必须要有个返回的监听函数,但是源码没有.所以我修改了下源码,加了个返回的监听

随机推荐