• Spring MVC 拦截器 (十)


    完整的项目案例: springmvc.zip

    目录

    实例

    除了依赖spring-webmvc还需要依赖jackson-databind(用于转换json数据格式)

    <!--json-->
    <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.6</version>
    </dependency>


    项目结构:

    配置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">
    
        <!-- 请求总控器 -->
        <servlet>
            <servlet-name>dispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:dispatcher-servlet.xml</param-value>
            </init-param>
        </servlet>
        <servlet-mapping>
            <servlet-name>dispatcher</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
    </web-app>
    View Code

    配置dispatcher-servlet.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: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="edu.nf.ch10"/>
    
        <mvc:annotation-driven/>
    
        <mvc:default-servlet-handler/>
    
        <!-- 配置拦截器栈 -->
        <mvc:interceptors>
            <!-- 可以配置多个<mvc:interceptor>表示多个拦截器 -->
            <mvc:interceptor>
                <!-- 哪些请求映射到拦截器中 -->
                <mvc:mapping path="/**"/>
                <!-- 排除那些请求不经过拦截器-->
                <mvc:exclude-mapping path="/login.html"/>
                <mvc:exclude-mapping path="/userLogin"/>
                <mvc:exclude-mapping path="/js/**"/>
                <!-- 配置拦截器的bean-->
                <bean class="edu.nf.ch10.interceptors.LoginInterceptor"/>
            </mvc:interceptor>
        </mvc:interceptors>
    
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    
    </beans>

    请求控制器UserController:

    package edu.nf.ch10.controller;
    
    import edu.nf.ch10.controller.vo.ResponseVO;
    import edu.nf.ch10.entity.Users;
    import edu.nf.ch10.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import javax.servlet.http.HttpSession;
    
    /**
     * @author wangl
     * @date 2018/11/5
     */
    @Controller
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        @PostMapping("/userLogin")
        public @ResponseBody ResponseVO login(Users user, HttpSession session){
            user = userService.login(user);
            //只有当会话作用域存在用户信息才表示正常登陆
            session.setAttribute("user", user);
            ResponseVO vo = new ResponseVO();
            vo.setValue("index.html");
            return vo;
        }
    }

    异常处理类ControllerAdviceHandler:

    package edu.nf.ch10.controller.advice;
    
    import edu.nf.ch10.controller.vo.ResponseVO;
    import edu.nf.ch10.service.exception.UserException;
    import org.springframework.http.HttpStatus;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    /**
     * @author wangl
     * @date 2018/11/5
     * 定义一个全局的异常处理类(类似一个切面)
     * 这个类中定义的所有方法都是异常处理方法,
     * 也可以理解为是全局的异常通知
     * value属性指定对哪些控制器进行切入拦截
     */
    @ControllerAdvice("edu.nf.ch10.controller")
    public class ControllerAdviceHandler {
    
        @ExceptionHandler(UserException.class)
        public @ResponseBody ResponseVO loginExceptionHandle(UserException e){
            ResponseVO vo = new ResponseVO();
            vo.setCode(HttpStatus.UNAUTHORIZED.value());
            vo.setMessage(e.getMessage());
            return vo;
        }
    }
    View Code

    登录拦截器 LoginInterceptor

    package edu.nf.ch10.interceptors;
    
    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;
    
    /**
     * @author wangl
     * @date 2018/11/5
     * 登陆拦截器
     * 拦截器必须实现Spring提供的一个HandlerInterceptor接口
     */
    public class LoginInterceptor implements HandlerInterceptor {
    
        /**
         * 在调用Controller的请求方法之前执行
         * @param request
         * @param response
         * @param handler
         * @return
         * @throws Exception
         */
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            HttpSession session = request.getSession();
            //如果session获取的用户信息为null,表示没有登陆
            //那么将重定向到登陆页面
            if(session.getAttribute("user") == null){
                response.sendRedirect("login.html");
                return false;
            }
            return true;
        }
    
        /**
         * 在调用Controller方法之后执行(注意:只有在preHandle方法返回true的情况下才会执行)
         * @param request
         * @param response
         * @param handler
         * @param modelAndView
         * @throws Exception
         */
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            System.out.println("请求到达方法之后...");
        }
    
        /**
         * 在视图响应之后执行(注意:只有在preHandle方法返回true的情况下才会执行)
         * @param request
         * @param response
         * @param handler
         * @param ex
         * @throws Exception
         */
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            System.out.println("响应视图之后...");
        }
    }
    
    
  • 相关阅读:
    ThinkPHP6.0.5 验证码 遇到的坑 (验证失败)
    css已知宽高和未知宽高的居中定位
    有关CLR的初学小整理(可能理解不深刻,望大牛指出)
    关于CRC循环冗余校验的总结(C#)
    lesson 4 再谈继承多态,抽象类和接口
    Lesson 3
    Lesson 2
    lesson 1
    08_Spring实现action调用service,service调用dao的过程
    07_配置文件中决定接口的实现类
  • 原文地址:https://www.cnblogs.com/hhmm99/p/9925032.html
Copyright © 2020-2023  润新知