SpringMVC拦截器实现登陆时的验证拦截

SpringMVC拦截器实现登陆时的验证拦截

实现HandlerInterceptor接口自定义拦截器

HandlerInterceptor 接口中定义了三个方法,我们就是通过这三个方法来对用户的请求进行拦截处理的.

(1 )preHandle (HttpServletRequest request, HttpServletResponse response, Object handle) 方法,顾名思义,该方法将在请求处理之前进行调用。SpringMVC 中的Interceptor 是链式的调用的,在一个应用中或者说是在一个请求中可以同时存在多个Interceptor 。每个Interceptor 的调用会依据它的声明顺序依次执行,而且最先执行的都是Interceptor 中的preHandle 方法,所以可以在这个方法中进行一些前置初始化操作或者是对当前请求的一个预处理,也可以在这个方法中进行一些判断来决定请求是否要继续进行下去。该方法的返回值是布尔值Boolean类型的,当它返回为false 时,表示请求结束,后续的Interceptor 和Controller 都不会再执行;当返回值为true 时就会继续调用下一个Interceptor 的preHandle 方法,如果已经是最后一个Interceptor 的时候就会是调用当前请求的Controller 方法。

(2 )postHandle (HttpServletRequest request, HttpServletResponse response, Object handle, ModelAndView modelAndView) 方法,由preHandle 方法的解释我们知道这个方法包括后面要说到的afterCompletion 方法都只能是在当前所属的Interceptor 的preHandle 方法的返回值为true 时才能被调用。postHandle 方法,顾名思义就是在当前请求进行处理之后,也就是Controller 方法调用之后执行,但是它会在DispatcherServlet 进行视图返回渲染之前被调用,所以我们可以在这个方法中对Controller 处理之后的ModelAndView 对象进行操作。postHandle 方法被调用的方向跟preHandle 是相反的,也就是说先声明的Interceptor 的postHandle 方法反而会后执行,这和Struts2 里面的Interceptor 的执行过程有点类型。Struts2 里面的Interceptor 的执行过程也是链式的,只是在Struts2 里面需要手动调用ActionInvocation 的invoke 方法来触发对下一个Interceptor 或者是Action 的调用,然后每一个Interceptor 中在invoke 方法调用之前的内容都是按照声明顺序执行的,而invoke 方法之后的内容就是反向的。

(3 )afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handle, Exception ex) 方法,该方法也是需要当前对应的Interceptor 的preHandle 方法的返回值为true 时才会执行。顾名思义,该方法将在整个请求结束之后,也就是在DispatcherServlet 渲染了对应的视图之后执行。这个方法的主要作用是用于进行资源清理工作的。

参考:http://elim.iteye.com/blog/1750680

登录拦截器

工程结构如下:

SpringMVC拦截器实现登陆时的验证拦截_第1张图片

没有登录的时候,直接请求/userHome, 会被拦截重定向到loginPage.jsp页,登录成功后,session中保存了user: 张三 这条信息,便可知道用户已登录,请求就不会被拦截。

自定义的拦截器, 通过校验 session 中的user信息,实现登录校验。

package cn.com.susq.interceptor;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * Created by susq on 2017-5-15.
 */
public class LoginInterceptor implements HandlerInterceptor {

    private static Logger logger = Logger.getLogger(LoginInterceptor.class);

    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        Object user = httpServletRequest.getSession().getAttribute("user");
        logger.info("user in session: " + httpServletRequest.getSession().getAttribute("user"));
        if(null == user) {
            logger.info("请先登录!");
            httpServletResponse.sendRedirect("/loginPage");
            return false;
        }
        return true;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion");
    }
}

在spring配置文件中配置拦截器


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="cn.com.susq.controller">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
    context:component-scan>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />             
        <property name="suffix" value=".jsp" />               
    bean>
    
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/userHome"/>
            <bean class="cn.com.susq.interceptor.LoginInterceptor">bean>
        mvc:interceptor>
    mvc:interceptors>
beans>

Controller如下

package cn.com.susq.controller;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by susq on 2017-5-15.
 */
@Controller
public class LoginController {

    private static Logger logger = Logger.getLogger(LoginController.class);

    @Resource
    HttpServletRequest request;

    @RequestMapping("/loginPage")
    public String toLoginPage() {
        return "login";
    }

    @RequestMapping("/userHome")
    public ModelAndView toUserHome(HttpServletRequest request) {
        logger.info("username in forward userHome: " + request.getParameter("username"));
        return new ModelAndView("userHome", "username", request.getParameter("username"));
    }

    @RequestMapping("/logout")
    public String logout() {
        request.getSession().removeAttribute("user");
        return "redirect:/";
    }

    @RequestMapping("/doLogin")
    public String doLogin(HttpServletRequest request) {
        logger.info("username: " + request.getParameter("username"));
        logger.info("password: " + request.getParameter("password"));

        try {
            if(request.getParameter("username").equals("张三") && request.getParameter("password").equals("123")) {
                request.getSession().setAttribute("user", "张三");
                return "forward:/userHome";
            } else {
                logger.info("没登录上");
                return "/loginPage";
            }
        } catch (Exception e) {
            return "/loginPage";
        }
    }
}

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>


<html>
<body>
<form action="/doLogin" method="post">
    用户名:<input type="text" name="username" /><br>
    密码:<input type="text" name="password" /><br>
    <input type="submit" value="登录" />
form>
body>
html>

userHome.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


<html>
<head>
    <title>My JSP 'hello.jsp' starting pagetitle>
head>

<body>
当前用户:${username}
<c:if test="${username!=null}">
    <a href="/logout">退出a>
c:if>
${message}
body>
html>

web.xml



<web-app>
  <display-name>Archetype Created Web Applicationdisplay-name>

  <filter>
    <filter-name>CharacterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
      <param-name>encodingparam-name>
      <param-value>utf-8param-value>
    init-param>
  filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

  <servlet>
    <servlet-name>dispatcherservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:applicationContext.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>dispatcherservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>
web-app>

你可能感兴趣的:(springmvc,spring,mvc)