zoukankan      html  css  js  c++  java
  • spring

    过滤器: serverlet自带,可以拦截html,css,js等

    拦截器:spring自带,只能拦截controller,用于controller运行前的预处理和运行后的后处理

    1. 配置环境

    springmvc.xml:

    <!-- 配置拦截器, class是自己写的拦截器路径 -->
        <mvc:interceptors>
            <mvc:interceptor>
                <mvc:mapping path="/**"/>
                <bean id="handlerInterceptorDemo1" class="interceptor.InterceptorTest"></bean>
            </mvc:interceptor>
        </mvc:interceptors>

    java:

    创建一个拦截器类,继承spring给的拦截器接口

    package interceptor;
    
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class InterceptorTest implements HandlerInterceptor { //继承spring拦截器接口HandlerInterceptor
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            System.out.println("preHandle拦截器拦截了");
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            System.out.println("postHandle方法执行了");
        }
    
        @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            System.out.println("afterCompletion方法执行了");
        }
    }

    在controller类中添加controller:

        //返回String
        @RequestMapping(path = "/stringTest")
        public String stringTest(Model model){
            //从数据库中查询到需要显示的值
            User user = new User();
            user.setName("张三");
            user.setAge(18);
            model.addAttribute("user", user);
            System.out.println("controller执行了");
    
            return "success";
        }

    jsp中添加一个超链接请求

    <a href = "/response/stringTest">stringTest</a>

    运行tomcat,然后点击链接查看后台输出。

     preHandle 在controller之前执行。 比如判断用户有没有登录,没登录直接跳到login

    postHandle 在跳转页面之前执行 一般用来预处理页面(modelAndView)。

    afterCompletion在整个请求结束后执行 可以测试性能,统计等。

  • 相关阅读:
    js 小数乘积位数太长
    微信浏览器跳转外部浏览器 app下载
    linux 查询制定目录的制定内容
    windows apache 跳转 tomcat 代理
    windows版 nginx配置反向代理实例教程 跳转tomcat和php网站
    概率论公式
    Python scipy 计算短时傅里叶变换(Short-time Fourier transforms)
    Centos 解决SSH 免密码登录 以及Crontab制作定时SSH自动登录和关闭的脚本
    python3 日志检索异常抛出异常 raise KeyError(key),KeyError: 'formatters'
    Pthon Matplotlib 画图
  • 原文地址:https://www.cnblogs.com/clamp7724/p/11732413.html
Copyright © 2011-2022 走看看