springmvc拦截器实现用户登录权限验证

实现用户登录权限验证

先看一下我的项目的目录,我是在intellij idea 上开发的

 

1、先创建一个User类

 1 package cn.lzc.po;
 2 
 3 public class User {
 4     private Integer id;//id
 5     private String username;//用户名
 6     private String password;//密码
 7 
 8     public Integer getId() {
 9         return id;
10     }
11 
12     public void setId(Integer id) {
13         this.id = id;
14     }
15 
16     public String getUsername() {
17         return username;
18     }
19 
20     public void setUsername(String username) {
21         this.username = username;
22     }
23 
24     public String getPassword() {
25         return password;
26     }
27 
28     public void setPassword(String password) {
29         this.password = password;
30     }
31 }

 

 2、创建一个UserController类

 1 package cn.lzc.controller;
 2 
 3 import cn.lzc.po.User;
 4 import org.springframework.stereotype.Controller;
 5 import org.springframework.ui.Model;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 import org.springframework.web.bind.annotation.RequestMethod;
 8 
 9 import javax.servlet.http.HttpSession;
10 
11 @Controller
12 public class UserController {
13     /**
14      * 向用户登录页面跳转
15      */
16     @RequestMapping(value = "/login",method = RequestMethod.GET)
17     public String toLogin(){
18         return  "login";
19     }
20 
21     /**
22      * 用户登录
23      * @param user
24      * @param model
25      * @param session
26      * @return
27      */
28     @RequestMapping(value = "/login",method = RequestMethod.POST)
29     public String login(User user, Model model, HttpSession session){
30         //获取用户名和密码
31         String username=user.getUsername();
32         String password=user.getPassword();
33         //些处横板从数据库中获取对用户名和密码后进行判断
34         if(username!=null&&username.equals("admin")&&password!=null&&password.equals("admin")){
35             //将用户对象添加到Session中
36             session.setAttribute("USER_SESSION",user);
37             //重定向到主页面的跳转方法
38             return "redirect:main";
39         }
40         model.addAttribute("msg","用户名或密码错误,请重新登录!");
41         return "login";
42     }
43 
44     @RequestMapping(value = "/main")
45     public String toMain(){
46         return "main";
47     }
48     
49     @RequestMapping(value = "/logout")
50     public String logout(HttpSession session){
51         //清除session
52         session.invalidate();
53         //重定向到登录页面的跳转方法
54         return "redirect:login";
55     }
56     
57 }

 

3、创建一个LoginInterceptor类

 1 package cn.lzc.interceptor;
 2 
 3 import cn.lzc.po.User;
 4 import org.springframework.web.servlet.HandlerInterceptor;
 5 import org.springframework.web.servlet.ModelAndView;
 6 
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 import javax.servlet.http.HttpSession;
10 
11 public class LoginInterceptor implements HandlerInterceptor {
12 
13     @Override
14     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
15         //获取请求的RUi:去除http:localhost:8080这部分剩下的
16         String uri = request.getRequestURI();
17         //UTL:除了login.jsp是可以公开访问的,其他的URL都进行拦截控制
18         if (uri.indexOf("/login") >= 0) {
19             return true;
20         }
21         //获取session
22         HttpSession session = request.getSession();
23         User user = (User) session.getAttribute("USER_SESSION");
24         //判断session中是否有用户数据,如果有,则返回true,继续向下执行
25         if (user != null) {
26             return true;
27         }
28         //不符合条件的给出提示信息,并转发到登录页面
29         request.setAttribute("msg", "您还没有登录,请先登录!");
30         request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
31         return false;
32     }
33 
34     @Override
35     public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
36 
37     }
38 
39     @Override
40     public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
41 
42     }
43 }

 

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  

 

posted @ 2018-04-07 13:53  Kmily_Lee  阅读(35497)  评论(2编辑  收藏  举报