springMVC+request.session實現用戶登陸和訪問權限控制

用springmvc mybatis實現用戶登陸登出功能,使用session保持登陸狀態,並實現禁止未登陸的用戶訪問。感謝谷歌資源,在這裏作個學習記錄加深本身的印象。
原文在個人https://my.oschina.net/finchxu/blog/3010138
接着上次的整合https://my.oschina.net/finchxu/blog/3007984javascript

上傳到了github方便查看https://github.com/finch-xu/springbook/tree/1.2.6css

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保持狀態,錯誤就提示從新輸入。html

@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部分實現驗證用戶密碼正確與否java

接口
@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頁面確定要排除否則怎麼登陸啊。下邊寫一個攔截器。jquery

重寫了HandlerInterceptor的接口,三個方法,這裏只用preHandle()方法。preHandle()方法,boolean布爾類型,false表示請求結束,true表明繼續執行(若是是最後一個攔截器那麼就會調用當前controller的方法)git

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

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

固然還有實體類和mapperweb

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>

感謝谷歌提供的資源。spring

相關文章
相關標籤/搜索