Springmvc攔截器實現用戶登錄權限驗證

實現用戶登錄權限驗證
先看一下我的項目的目錄,我是在intellij idea 上開發的
在這裏插入圖片描述
1、先創建一個User類

package cn.lzc.po;

public class User {
    private Integer id;//id
    private String username;//用戶名
    private String password;//密碼

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

`
2、創建一個UserController類

 package cn.lzc.controller;

import cn.lzc.po.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    /**
     * 向用戶登錄頁面跳轉
     */
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String toLogin(){
        return  "login";
    }

    /**
     * 用戶登錄
     * @param user
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(User user, Model model, HttpSession session){
        //獲取用戶名和密碼
        String username=user.getUsername();
        String password=user.getPassword();
        //些處橫板從數據庫中獲取對用戶名和密碼後進行判斷
        if(username!=null&&username.equals("admin")&&password!=null&&password.equals("admin")){
            //將用戶對象添加到Session中
            session.setAttribute("USER_SESSION",user);
            //重定向到主頁面的跳轉方法
            return "redirect:main";
        }
        model.addAttribute("msg","用戶名或密碼錯誤,請重新登錄!");
        return "login";
    }

    @RequestMapping(value = "/main")
    public String toMain(){
        return "main";
    }
    
    @RequestMapping(value = "/logout")
    public String logout(HttpSession session){
        //清除session
        session.invalidate();
        //重定向到登錄頁面的跳轉方法
        return "redirect:login";
    }
    
}

3、創建一個LoginInterceptor類

package cn.lzc.interceptor;

import cn.lzc.po.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //獲取請求的RUi:去除http:localhost:8080這部分剩下的
        String uri = request.getRequestURI();
        //UTL:除了login.jsp是可以公開訪問的,其他的URL都進行攔截控制
        if (uri.indexOf("/login") >= 0) {
            return true;
        }
        //獲取session
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("USER_SESSION");
        //判斷session中是否有用戶數據,如果有,則返回true,繼續向下執行
        if (user != null) {
            return true;
        }
        //不符合條件的給出提示信息,並轉發到登錄頁面
        request.setAttribute("msg", "您還沒有登錄,請先登錄!");
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

4、看一下springmvc-config.xml中配置的攔截器

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    <!--定義組件掃描包-->
    <context:component-scan base-package="cn.lzc.controller"/>
    <!--配置器處理器映射器,配置處理器適配器-->
    <mvc:annotation-driven/>
    <!--定義視圖解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--配置攔截器-->
    <mvc:interceptors>
      <!--  <bean class="cn.lzc.interceptor.CustomInterceptor"></bean>--><!--攔截所有請求-->
       
        <!-- <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/" /><&lt;!&ndash;配置了mapping 這個 將不再起作用&ndash;&gt;
            <bean class="cn.lzc.interceptor.CustomInterceptor"></bean>
        </mvc:interceptor>-->
        
        <!--<mvc:interceptor>-->
           <!--<mvc:mapping path="/hello" />&lt;!&ndash;配置攔截hello結尾的&ndash;&gt;-->
            <!--<bean class="cn.lzc.interceptor.CustomInterceptor"/>-->
        <!--</mvc:interceptor>-->
        
        <!--登錄攔截器-->
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="cn.lzc.interceptor.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

5、看下web.xml的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--配置編碼過濾器-->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <!--攔截所有請求-->
    </filter-mapping>
    <!--配置前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

6、WEB-INF目錄下的main.jsp

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2018-04-07
  Time: 13:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>系統主頁</title>
</head>
<body>
    當前用戶:${USER_SESSION.username}
    <a href="${pageContext.request.contextPath}/logout">退出</a>
</body>
</html>

7、WEB-INF目錄下的login.jsp

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2018-04-07
  Time: 13:04
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用戶登錄</title>
</head>
<body>
    ${msg}
    <form action="${pageContext.request.contextPath}/login" method="post">
        用戶名:<input type="text" name="username"><br>&nbsp;&nbsp;&nbsp;:
        <input type="password" name="password"><br>
        <input type="submit" value="登錄">
    </form>
</body>
</html>

8、啓動tomcat,可以訪問了 http://localhost:8080/chater15/interceptor/login
在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章