溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

使用Spring3 如何實(shí)現(xiàn)一個(gè)用戶權(quán)限認(rèn)證功能

發(fā)布時(shí)間:2020-11-12 15:35:35 來源:億速云 閱讀:109 作者:Leah 欄目:編程語(yǔ)言

今天就跟大家聊聊有關(guān)使用Spring3 如何實(shí)現(xiàn)一個(gè)用戶權(quán)限認(rèn)證功能,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

使用Spring3 實(shí)現(xiàn)用戶登錄以及權(quán)限認(rèn)證

這里我就簡(jiǎn)單介紹一下,我在實(shí)現(xiàn)的時(shí)候處理的一些主要的實(shí)現(xiàn)。

1.用戶登錄

 <form action="loginAction.do" method="post"> 
  <div class="header"> 
  <h3 class="logo png"></h3> 
  </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">&copy; 2013 - 2014 |</div> 
</form> 

以上是前臺(tái)頁(yè)面,后臺(tái)的就是一個(gè)簡(jiǎn)單的邏輯實(shí)現(xiàn):

    @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.登錄信息

這里,在登錄頁(yè)面有一段JavaScript,來顯示密碼錯(cuò)誤等信息:

<script type="text/javascript"> 
var login_username_info = '<%=request.getSession().getAttribute("currentUser") == null &#63; "" : request.getSession().getAttribute("currentUser")%>'; 
var login_message_info = '<%=request.getSession().getAttribute("login_message") == null &#63; "" : request.getSession().getAttribute("login_message")%>'; 
if(login_message_info != null && login_message_info != ''){ 
  alert(login_message_info); 
} 
 
</script> 

3.攔截未登錄用戶的請(qǐng)求

這里,從頁(yè)面和后臺(tái)實(shí)現(xiàn)了雙重?cái)r截:

頁(yè)面代碼如下:

<% 
if(session.getAttribute("currentUser")==null){ 
%> 
window.parent.location='login.html'; 
<% 
} 
%> 

后臺(tái)是一個(gè)攔截器(servlet-config.xml):

<!-- 攔截器 -->  
  <mvc:interceptors>  
    <mvc:interceptor>  
      <mvc:mapping path="/*.do" />  
      <bean class="com..log.report.interceptor.AccessStatisticsIntceptor" />  
    </mvc:interceptor>  
  </mvc:interceptors>  

攔截器的實(shí)現(xiàn)是

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())) { 
      //校驗(yàn)失敗 
      return false; 
//     throw new CustomException(LogConstant.USER_NOT_LOGIN); 
    } 
      return true; 
 } 

具體如何校驗(yàn)的,會(huì)根據(jù)用戶的權(quán)限,就不介紹了

4.返回未登錄前訪問的頁(yè)面

首先在頁(yè)面添加一段腳本,使用jQuery去訪問后臺(tái)

    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&#63;previousPage=" + page + ".html", 
    success : function(msg){   
 
    } 
  }); 
} 

然后,后臺(tái)有記錄這個(gè)頁(yè)面:

@RequestMapping(value="setPreviousPageAction.do") 
public void setPreviousPageAction(@RequestParam(value="previousPage") String previousPage, HttpSession session){ 
  session.setAttribute(LogConstant.PREVIOUS_PAGE, previousPage); 
} 

在登錄完成后,返回這個(gè)頁(yè)面即可。

5.保存用戶名密碼

登錄頁(yè)面提供一個(gè)保存下拉框:

<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> 

后臺(tái)在登錄時(shí)會(huì)操作,將信息保存在cookie中:

if(savetime != null) { //保存用戶在Cookie 
  int savetime_value = savetime != null &#63; 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); 
}  

前臺(tái)在發(fā)現(xiàn)用戶未登錄時(shí),會(huì)取出cookie中的數(shù)據(jù)去登錄:

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(); 
    <% 
  } 
   
  ... 

看完上述內(nèi)容,你們對(duì)使用Spring3 如何實(shí)現(xiàn)一個(gè)用戶權(quán)限認(rèn)證功能有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI