springMVC+request.session实现用户登录和访问权限控制
用springmvc mybatis实现用户登录登出功能,使用session保持登录状态,并实现禁止未登录的用户访问。感谢谷歌资源,在这里做个学习记录加深自己的印象。
原文在我的https://my.oschina.net/finchxu/blog/3010138
接着上次的整合https://my.oschina.net/finchxu/blog/3007984
上传到了github方便查看https://github.com/finch-xu/springbook/tree/1.2.6
src
└── main── java
│ └── cn── book
│ ├── controller
│ │ ├── BooksController.java
│ │ ├── LoginInterceptor.java
│ │ └── UsersController.java
│ ├── mapper
│ │ ├── BooksMapper.java
│ │ ├── BooksMapper.xml
│ │ ├── UsersMapper.java
│ │ └── UsersMapper.xml
│ ├── pojo
│ │ ├── Bookadmin.java
│ │ └── Useradmin.java
│ └── service
│ ├── BooksServiceImpl.java
│ ├── BooksService.java
│ ├── UsersServiceImpl.java
├── resources └── UsersService.java
│ ├── applicationContext-dao.xml
│ ├── applicationContext-service.xml
│ ├── applicationContext-trans.xml
│ ├── jdbc.properties
│ ├── log4j.properties
│ ├── spring-mvc.xml
│ └── sqlMapConfig.xml
└── webapp
├── index.jsp
└── WEB-INF
├── jsp
│ ├── bookDetail.jsp
│ ├── fail.jsp
│ ├── home.jsp
│ ├── listBooks.jsp
│ ├── updatepage.jsp
│ └── userlogin.jsp
├── static
│ ├── img
│ └── js
│ └── jquery3.js
└── web.xml
先看controller吧,还是两步,进入/home/userlogin页面,然后输入用户名和密码开始登陆,验证用户名和密码,正确就建立session保持状态,错误就提示重新输入。
@Controller
@RequestMapping("/home")
public class UsersController {
@Autowired
private UsersService usersService;
//进入login页面
@RequestMapping("/userlogin")
public String userlogin(){
return "userlogin";
}
//执行login操作,匹配用户名和密码,建立session持久连接
@RequestMapping(value = "/login",method = RequestMethod.POST)
public String login(Useradmin useradmin, Model model, HttpServletRequest request){
useradmin = usersService.checkLogin(useradmin.getUser_name(),useradmin.getUser_password());
if (useradmin != null){
model.addAttribute(useradmin);
request.getSession(true).setAttribute("useradmin",useradmin);
return "redirect:/a/listBooks";
}else {
model.addAttribute("message","登录名或密码错误!");
return "userlogin";
}
}
//logout登出,其实就是删除之前登录时设置的session
@RequestMapping("/logout")
public String logout(HttpServletRequest request) {
request.getSession().removeAttribute("useradmin");
return "redirect:userlogin";
}
}
service部分实现验证用户密码正确与否
接口
@Service
public interface UsersService {
Useradmin checkLogin(String user_name,String user_password);
}
实现
@Service
@Transactional
public class UsersServiceImpl implements UsersService{
@Autowired
private UsersMapper usersMapper;
@Override
public Useradmin checkLogin(String user_name,String user_password){
Useradmin useradmin = usersMapper.findUserByName(user_name);
if (useradmin != null && useradmin.getUser_password().equals(user_password)){
return useradmin;
}
return null;
}
}
然后要设置访问控制,只有登录的用户才能访问所有页面,当然这个/home/userlogin页面肯定要排除不然怎么登录啊。下边写一个拦截器。
重写了HandlerInterceptor的接口,三个方法,这里只用preHandle()方法。preHandle()方法,boolean布尔类型,false表示请求结束,true代表继续执行(如果是最后一个拦截器那么就会调用当前controller的方法)
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//获取请求的地址(根域名以外的部分)
String uri = request.getRequestURI();
if (uri.indexOf("/home/userlogin") >= 0){
return true;
}
//获取session,有就是说明已经登录,没有就是拦截访问并跳转到登录页面
HttpSession session = request.getSession();
Useradmin useradmin = (Useradmin) session.getAttribute("useradmin");
if (useradmin != null){
return true;
}
request.setAttribute("msg","还没登陆!快去登陆啊!");
request.getRequestDispatcher("/WEB-INF/jsp/userlogin.jsp").forward(request,response);
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
写个userlogin.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>快登录!</title>
<style>
#center{
border-radius: 20px;
width: 300px;
height: 350px;
margin: auto;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
</style>
<link rel="stylesheet" type="text/css" href="static/lib/bootstrap43/css/bootstrap.min.css"/>
<script type="text/javascript" src="static/js/jquery3.js"></script>
<script src="static/lib/bootstrap43/js/bootstrap.min.js"></script>
</head>
<body bgcolor="#ffe4c4">
<div id="center">
<h2>欢迎登录图书管理系统</h2>
<div style="color: deeppink">
<p>${message }</p> <%--这里显示上边的controller里边用户或者密码错误的信息--%>
</div>
<form id="login" action="${pageContext.request.contextPath}/home/login" method="post">
<table class="table">
<tr>
<td>用户名:</td>
<td><input type="text" id="user_name" name="user_name" class="form-control"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" id="user_password" name="user_password" class="form-control"/></td>
</tr>
<tr>
<td><input type="submit" value="点击登录" id="login0"/></td>
</tr>
</table>
</form>
</div>
</body>
</html>
当然还有实体类和mapper
pojo:
public class Useradmin {
Integer user_id;
String user_name;
String user_password;
...get和set...省略
}
mapper.java:
public interface UsersMapper {Useradmin findUserByName(String user_name);}
mapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.book.mapper.UsersMapper">
<sql id="BASE_TABLE">
useradmin
</sql>
<sql id="BASE_COLUMN">
user_id,user_name,user_password
</sql>
<select id="findUserByName" parameterType="string" resultType="Useradmin">
select * from useradmin where user_name = #{user_name}
</select>
</mapper>
感谢谷歌提供的资源。