首页 > 代码库 > 拦截器测试

拦截器测试

  1 package com.isoftstone.iics.bizsupport.epartner.fh.HandlerInteceptor;
  2 
  3 import javax.servlet.http.HttpServletRequest;
  4 import javax.servlet.http.HttpServletResponse;
  5 
  6 import org.springframework.core.NamedThreadLocal;
  7 import org.springframework.web.servlet.HandlerInterceptor;
  8 import org.springframework.web.servlet.ModelAndView;
  9 import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
 10 
 11 /**
 12  * preHandle:预处理回调方法,实现处理器的预处理(如登录检查),第三个参数为响应的处理器;
 13 返回值:true表示继续流程(如调用下一个拦截器或处理器);
 14              false表示流程中断(如登录检查失败),不会继续调用其他的拦截器或处理器,此时我们需要通过response来产生响应;
 15 postHandle:后处理回调方法,实现处理器的后处理(但在渲染视图之前),此时我们可以通过modelAndView(模型和视图对象)对模型数据进行处理或对视图进行处理,modelAndView也可能为null。
 16 afterCompletion:整个请求处理完毕回调方法,即在视图渲染完毕时回调,如性能监控中我们可以在此记录结束时间并输出消耗时间,还可以进行一些资源清理,类似于try-catch-finally中的finally,但仅调用处理器执行链中preHandle返回true的拦截器的afterCompletion。
 17 
 18  * <P>Description: --拦截器处理器测试拦截器</P>
 19  * @ClassName: HandlerInteceptorTest
 20  * @author 冯浩  2017年4月10日 上午11:12:01
 21  * @see TODO
 22  */
 23 //或继承HandlerInterceptorAdater
 24 public class HandlerInteceptorTest implements HandlerInterceptor {
 25     
 26     public NamedThreadLocal<Long> local=new NamedThreadLocal<Long>("stopWatch-startTime");//为每个线程绑定的本地线程
 27 
 28 
 29     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
 30             throws Exception {
 31         long end=System.currentTimeMillis();
 32         Long start = local.get();
 33         System.out.println("\n process is "+(end-start)+" mills");
 34     }
 35 
 36     /**
 37      * 后处理回调
 38      */
 39     
 40     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
 41             ModelAndView modelAndView) throws Exception {
 42         System.out.println("\n this is postHandle!!!");
 43         
 44     }
 45 
 46     /**
 47      * 预处理回调
 48      */
 49     
 50     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
 51         long start=System.currentTimeMillis();
 52         local.set(start);
 53         System.out.println("\nthis is preHandle");
 54         return true;
 55     }
 56     
 57     
 58 
 59 }
 60 
 61 
 62 
 63 /**
 64  * 
 65  * <P>Description: TODO只需要实现自己需要的即可</P>
 66  * @ClassName: HandlerInteceptor2
 67  * @author 冯浩  2017年4月14日 下午1:26:06
 68  * @see TODO
 69  */
 70 
 71  class HandlerInteceptor2 extends HandlerInterceptorAdapter {
 72     
 73     public NamedThreadLocal<Long> local=new NamedThreadLocal<Long>("stopWatch-startTime");//为每个线程绑定的本地线程
 74 
 75 
 76     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
 77             throws Exception {
 78         long end=System.currentTimeMillis();
 79         Long start = local.get();
 80         System.out.println("\n process is "+(end-start)+" mills");
 81     }
 82 
 83     /**
 84      * 后处理回调
 85      */
 86     
 87     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
 88             ModelAndView modelAndView) throws Exception {
 89         System.out.println("\n this is postHandle!!!");
 90         
 91     }
 92 
 93     /**
 94      * 预处理回调
 95      */
 96     
 97     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
 98         long start=System.currentTimeMillis();
 99         local.set(start);
100         System.out.println("\nthis is preHandle");
101         return true;
102     }
103     
104     
105 
106 }

配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
 4     xmlns:mvc="http://www.springframework.org/schema/mvc"
 5     xsi:schemaLocation="
 6             http://www.springframework.org/schema/beans 
 7             http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 8             http://www.springframework.org/schema/aop 
 9             http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
10             http://www.springframework.org/schema/context
11             http://www.springframework.org/schema/context/spring-context-3.0.xsd
12             http://www.springframework.org/schema/mvc  
13             http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
14 
15     <context:component-scan annotation-config="true" base-package="com.isoftstone.iics.bizsupport.epartner.fh.HandlerInteceptor">
16         <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
17     </context:component-scan>
18     
19     <!-- <bean id="test" class="com.isoftstone.iics.bizsupport.epartner.fh.HandlerInteceptor.HandlerInteceptorTest"></bean>
20     不管用
21     <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
22        <property name="interceptors">
23            <list>
24                <bean class="com.isoftstone.iics.bizsupport.epartner.fh.HandlerInteceptor.HandlerInteceptorTest"></bean>
25            </list>
26        </property>
27       
28     </bean> 
29     
30     <bean name="/test" class="com.isoftstone.iics.bizsupport.epartner.fh.HandlerInteceptor.TestController"></bean>
31      -->
32      <mvc:interceptors>
33        <mvc:interceptor>
34            <mvc:mapping path="/test"/>
35            <bean class="com.isoftstone.iics.bizsupport.epartner.fh.HandlerInteceptor.HandlerInteceptorTest"></bean>
36        </mvc:interceptor>
37     </mvc:interceptors>
38 
39 </beans>

Controller

 1 package com.isoftstone.iics.bizsupport.epartner.fh.HandlerInteceptor;
 2 
 3 import java.lang.annotation.Annotation;
 4 
 5 import javax.servlet.http.HttpServletRequest;
 6 import javax.servlet.http.HttpServletResponse;
 7 
 8 
 9 
10 
11 
12 
13 
14 import org.springframework.web.bind.annotation.RequestMapping;
15 import org.springframework.web.bind.annotation.RequestMethod;
16 import org.springframework.web.servlet.ModelAndView;
17 //@Controller
18 //public class TestController{
19 //    
20 //    @RequestMapping(value="http://www.mamicode.com/test",method=RequestMethod.POST)
21 //    @ResponseBody
22 //    public void test(@RequestParam(value="http://www.mamicode.com/message",defaultValue="http://www.mamicode.com/default")String message){
23 //        System.out.println(message);
24 //        System.out.println("\nthis is testController");
25 //    }
26 //
27 //}
28 import org.springframework.web.servlet.mvc.Controller;
29 public class TestController implements Controller{
30 
31     @RequestMapping(value="http://www.mamicode.com/test",method=RequestMethod.POST)
32     @Override
33     public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
34         System.out.println("this is testController-----");
35         return new ModelAndView("test");
36     }
37 
38 }

测试

 1 package com.isoftstone.iics.bizsupport.epartner.fh.HandlerInteceptor;
 2 
 3 
 4 import java.io.IOException;
 5 import java.io.InputStream;
 6 import java.io.UnsupportedEncodingException;
 7 import java.util.ArrayList;
 8 import java.util.List;
 9 
10 import org.apache.commons.io.IOUtils;
11 import org.apache.http.HttpEntity;
12 import org.apache.http.NameValuePair;
13 import org.apache.http.client.ClientProtocolException;
14 import org.apache.http.client.HttpClient;
15 import org.apache.http.client.entity.UrlEncodedFormEntity;
16 import org.apache.http.client.methods.CloseableHttpResponse;
17 import org.apache.http.client.methods.HttpPost;
18 import org.apache.http.impl.client.CloseableHttpClient;
19 import org.apache.http.impl.client.DefaultHttpClient;
20 import org.apache.http.impl.client.HttpClients;
21 import org.apache.http.message.BasicNameValuePair;
22 import org.junit.Test;
23 import org.springframework.context.support.ClassPathXmlApplicationContext;
24 
25 import org.apache.commons.io.*;
26 
27 
28 public class TestInteceptor {
29     
30 
31     
32     @Test
33     public void test() throws UnsupportedEncodingException{
34        CloseableHttpClient client = HttpClients.createDefault();
35        String url="http://localhost:8082/com.isoftstone.iics.bizsupport.epartner/test";
36        HttpPost post=new HttpPost(url);
37        List<NameValuePair> param=new ArrayList<NameValuePair>();
38        param.add(new BasicNameValuePair("message","fenghao"));
39        UrlEncodedFormEntity entity=new UrlEncodedFormEntity(param,"utf-8");
40        post.setEntity(entity);
41        try {
42         CloseableHttpResponse response = client.execute(post);
43         HttpEntity res = response.getEntity();
44         InputStream content = res.getContent();
45         System.out.println(IOUtils.toString(content));
46     } catch (ClientProtocolException e) {
47         e.printStackTrace();
48     } catch (IOException e) {
49         e.printStackTrace();
50     }
51     
52         
53     }
54 
55 }

 

拦截器测试