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在整个请求结束后执行 可以测试性能,统计等。

  • 相关阅读:
    Mandriva Flash: 到处可用的口袋 Linux
    Pidgin 衔接 Google Talk 的设置配备铺排
    5 个使 Vim 更易用的脚本
    Bash 运用才干大补贴
    915Resolution打点宽屏表现标题问题
    Linux下误删root目次
    惠普推出 Linux 迷你条记本
    weblogic8.1for linux ES3.0拆卸与设置
    英俊的 Linux Mini PC
    Zonbu-售价 99 美元的袖珍电脑
  • 原文地址:https://www.cnblogs.com/clamp7724/p/11732413.html
Copyright © 2011-2022 走看看