今天就跟大家聊聊有关使用Spring3 如何实现一个用户权限认证功能,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
使用Spring3 实现用户登录以及权限认证
这里我就简单介绍一下,我在实现的时候处理的一些主要的实现。
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">© 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();
<%
}
...
看完上述内容,你们对使用Spring3 如何实现一个用户权限认证功能有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。