基于SpringMVC的interceptor的用户登录权限限制

本次写的案例是,构建一个用户注册和登录界面,并用SpringMVC 的interceptor对用户直接登录主页权限进行限制
首先写一个domain对象,简单起见,就只写username和password属性

package lhc.domain;
public class User2 {
     private String username;
     private String password;
     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;
     }
     @Override
     public String toString() {
           return "User2 [username=" + username + ", password=" + password + "]";
     }

}

配置web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>testspring</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>


    <!-- 开启前端过滤器 -->
    <!-- The front controller of this Spring Web application, responsible for 
        handling all application requests -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <!-- 开启Spring的编码过滤器 -->

    <filter>  
        <filter-name>Encoding</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>  
        <init-param>  
            <param-name>forceEncoding</param-name>  
            <param-value>true</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>Encoding</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  


</web-app>

接下来是SpringMVC的配置文件的配置,开启注解,扫描包,开启视图解析器,配置自定义的拦截器

<?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:context="http://www.springframework.org/schema/context"
     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
     xmlns:mvc="http://www.springframework.org/schema/mvc"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
     <!-- 开启springm的注解 -->
     <mvc:annotation-driven></mvc:annotation-driven>
     <!-- 开启扫描指定位置的包 -->
     <context:component-scan base-package="lhc"></context:component-scan>
     <!-- 开启视图解析器 -->
     <bean
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
           <property name="prefix" value="/WEB-INF/jsp/"></property>
           <property name="suffix" value=".jsp"></property>
     </bean>         
     <!-- 配置自定义的拦截器 -->
     <mvc:interceptors>
           <mvc:interceptor>
                <mvc:mapping path="/**" />
                <bean class="lhc.controller.LoginInterceptor" />
           </mvc:interceptor>
     </mvc:interceptors>
</beans>

写一个登录界面的表单,并显示错误信息

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
     <h1>登录</h1>

     <!-- 显示错误信息 -->
     ${msg }

     <form action="${pageContext.request.contextPath }/user/login" method="post">
     用户名:<input type="text" name="username" /> <br/>
     密码:<input type="password" name="password"/><br/>
     <input type="submit" value="submit">
     </form>
</body>
</html>

写一个主页,并提供注销链接

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
     <h1>欢迎来到主页</h1>

     <h2></h2><a href="${pageContext.request.contextPath }/user/logout">注销</a></h2>
</body>
</html>

写Controller组件,由于SpringMVC架构建议不让用户直接访问jsp页面,并且直接访问的jsp页面不进行拦截.故在控制层转发到jsp页面,此时的jsp页面会被拦截

    // 登录login.jsp
     @RequestMapping(value = "/login", method = RequestMethod.GET)
     public String ToLogin() {
           return "login";
     }
     // 表单验证,注意方法与上面不同
     @RequestMapping(value = "/login", method = RequestMethod.POST)
     public String login(User2 user2, HttpSession session, HttpServletRequest request) {
           String username = user2.getUsername();
           String password = user2.getPassword();
           //由于重点在SpringMVC,此处模拟从数据库取出数据进行表单验证
           if (username != null && username.equals("tom") && password != null && password.equals("123")) {
                session.setAttribute("user", user2);
                //进入登录主页
                return "main";
           } else {
                request.setAttribute("msg", "用户名或密码错误");
                //返回到登录页面
                return "login";
           }
     }

     // 主页的注销处理
     @RequestMapping("/logout")
     public String logout(HttpSession session) {
           //清除session的数据
           session.invalidate();
           return "login";
     }
     // 直接登录main.jsp主页,需要写一个拦截器进行拦截
     @RequestMapping(value = "/main")
     public String ToMain() {
           return "main";
     }

为直接访问主页设置一个拦截器

package lhc.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import lhc.domain.User2;
public class LoginInterceptor implements HandlerInterceptor {
     @Override
     public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
                throws Exception {
     }
     @Override
     public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
                throws Exception {
     }
     @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
           //如果是登录login则放行
           if (request.getRequestURL().indexOf("/login")>0) {
                return true;
           }
           //如果已经登录过,则放行
           HttpSession session =request.getSession();
           User2 user = (User2)session.getAttribute("user");
           if(user!=null) {
                return true;
           }
           //没登录过又不登录login页面,转发到登录页面
           request.setAttribute("msg", "你还没登录");
          request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
           return false;
     }
}

猜你喜欢

转载自blog.csdn.net/lhc0512/article/details/79186157