【spring-boot神器】第一篇:拦截器,过滤器,监听器,控制器,消息转换器,AOP执行顺序

整理一下这几天学习的资料和代码

第一部分、上代码

1、spring各种器的实现,idea搭建spring-boot的教程在这里http://www.jianshu.com/p/9082a533fa3c(整理的很好)

 1 import org.springframework.boot.SpringApplication;
 2 import org.springframework.boot.autoconfigure.SpringBootApplication;
 3 import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
 4 import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
 5 import org.springframework.boot.web.servlet.ServletComponentScan;
 6 import org.springframework.context.annotation.ImportResource;
 7 
 8 @SpringBootApplication(exclude =
 9         {DataSourceAutoConfiguration.class,
10                 HibernateJpaAutoConfiguration.class} //排除初始化的数据库的包
11 ) //移除自动注入数据源
12 @ServletComponentScan   //扫描过滤器、拦截器、监听器、servlet
13 @ImportResource(locations = {"classpath:application-bean.xml"}) //加载配置的xml(路径是src/main/resourcse/application-bean.xml)
14 public class SloveApplication {
15 
16     public static void main(String[] args) {
17         SpringApplication.run(SloveApplication.class, args);
18     }
19 
20 }

 

2、监听器

 1 import javax.servlet.ServletContextEvent;
 2 import javax.servlet.ServletContextListener;
 3 import javax.servlet.annotation.WebListener;
 4 
 5 /**
 6  * 
 7  */
 8 @WebListener
 9 public class MyListener  implements ServletContextListener{
10     @Override
11     public void contextInitialized(ServletContextEvent servletContextEvent) {
12         System.out.println("监听器初始化");
13         System.out.println(servletContextEvent.getServletContext().getServerInfo());
14     }
15 
16     @Override
17     public void contextDestroyed(ServletContextEvent servletContextEvent) {
18         System.out.println("监听器销毁");
19     }
20 }

3、过滤器

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;


@WebFilter
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器操作");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("过滤器销毁");
    }
}

4、拦截器

 1 import org.springframework.web.servlet.HandlerInterceptor;
 2 import org.springframework.web.servlet.ModelAndView;
 3 
 4 import javax.servlet.http.HttpServletRequest;
 5 import javax.servlet.http.HttpServletResponse;
 6 
 7 /**
 8  *
 9  *  拦截器实现
10  */
11 public class MyInterceptor implements HandlerInterceptor {
12 
13     @Override
14     public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
15         System.out.println("--------------拦截器请求前调用-----------------------------");
16         return true;// 只有返回true才会继续向下执行,返回false取消当前请求
17     }
18 
19     @Override
20     public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
21         System.out.println("请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)");
22 
23     }
24 
25     @Override
26     public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
27         System.out.println("在整个请求结束之后被调用,也就是在DispatcherServlet渲染了对应的视图之后执行(主要是用于进行资源清理工作)");
28 
29     }
30 }

5、消息转换器

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;

/**
 * 
 */
public class MyConver extends FastJsonHttpMessageConverter {



    @Override
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        //fastJson的版本影响是否可以获取
        System.out.println("--------------请求进入到消息转化器-------------------");
        return super.readInternal(clazz, inputMessage);
    }

    @Override
    protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        System.out.println("--------------响应进入到消息转化器-------------------");
        super.writeInternal(obj, outputMessage);
    }
}

配套的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-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <!-- spring可以自动去扫描base-pack下面的包或者子包下面的java文件,
        如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean -->
    <context:component-scan base-package="com.eternal"/>
    <!-- 实际开发中使用<mvc:annotation-driven/>代替注解适配器和映射器,设置配置方案 -->
    <mvc:annotation-driven>
        <!-- 设置不使用默认的消息转换器 -->
        <mvc:message-converters register-defaults="false">
            <!-- 配置Spring的转换器 -->
            <!-- 配置fastjson中实现HttpMessageConverter接口的转换器 -->
            <bean id="fastJsonHttpMessageConverter"  class="com.eternal.slovej.component.MyConver">
                <!-- 加入支持的媒体类型:返回contentType -->
                <property name="supportedMediaTypes">
                    <list>
                        <!-- 这里顺序不能反,一定先写text/html,不然ie下会出现下载提示 -->
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            <!--<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>-->
            <!--<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/>-->
            <!--<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>-->
            <!--<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>-->
        </mvc:message-converters>
    </mvc:annotation-driven>
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.eternal.slovej.component.MyInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

6、aop

 1 import org.aspectj.lang.JoinPoint;
 2 import org.aspectj.lang.ProceedingJoinPoint;
 3 import org.aspectj.lang.annotation.*;
 4 import org.springframework.context.annotation.Configuration;
 5 
 6 /**
 7  * Created by Administrator on 2017/7/31.
 8  */
 9 @Aspect
10 @Configuration
11 public class MyAop {
12     /*
13     * 定义一个切入点
14     */
15     @Pointcut("execution(* com.eternal.slovej.component.MyController.*(..))")
16     public void excudeService() {
17         System.out.println("==========定义切点===========");
18     }
19 
20     /**
21      * 通过连接点切入
22      */
23     @Before("excudeService()")
24     public void twiceAsOld1(JoinPoint point) {
25         System.out.println("before切面执行了。。。。" + point.getKind());
26     }
27 
28     @Around("excudeService()")
29     public Object twiceAsOld(ProceedingJoinPoint thisJoinPoint) {
30         Object s =null ;
31         try {
32             s = thisJoinPoint.proceed();
33         } catch (Throwable throwable) {
34             throwable.printStackTrace();
35         }
36         System.out.println("Around切面执行了。。。。");
37         return s;
38     }
39 
40     @After("excudeService()")
41     public void twiceAsOld3(JoinPoint point) {
42         System.out.println("after切面执行了。。。。" + point.getKind());
43     }
44 
45     @AfterReturning("excudeService()")
46     public void doFindByIdCheck() {
47         System.out.println("=======AfterReturning后置通知==================");
48     }
49 
50 
51 }

 

 

7、控制器

 1 import com.eternal.slovej.Test;
 2 import org.springframework.http.HttpStatus;
 3 import org.springframework.web.bind.annotation.RequestBody;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 import org.springframework.web.bind.annotation.ResponseStatus;
 6 import org.springframework.web.bind.annotation.RestController;
 7 
 8 /**
 9  * 
10  */
11 @RestController
12 public class MyController {
13 
14     //添加了一个方法
15     @RequestMapping(value = "/hello")
16     @ResponseStatus(HttpStatus.OK)
17     public String hello(@RequestBody Test test) {
18         System.out.println("----进入方法----" + test.getName()+"---------------"+test.getAge());
19         return "no hello world";
20     }
21 }

8、servlet

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 
 */
@WebServlet(urlPatterns = "/b")
public class MyServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doPost()");
    }
}

第二部分、跑代码

通过main()方法启动项目(使用内置的tomcat启动)---spring boot内置了三种servlet容器:tomcat,jetty,undertow。

监听器初始化
Apache Tomcat/8.5.16
过滤器初始化

启动成功后调用controller

过滤器操作
--------------拦截器请求前调用-----------------------------
--------------请求进入到消息转化器-------------------
before切面执行了。。。。method-execution
----进入方法----123---------------123
Around切面执行了。。。。
after切面执行了。。。。method-execution
=======AfterReturning后置通知==================
--------------响应进入到消息转化器-------------------
请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
在整个请求结束之后被调用,也就是在DispatcherServlet渲染了对应的视图之后执行(主要是用于进行资源清理工作)

执行顺序

接下来将对各个神器进行总结讲解

感谢 http://www.jianshu.com/u/8dc5811b228f 大神的精彩文章

 

posted @ 2017-07-31 22:55  帅LOVE俊  阅读(8815)  评论(0编辑  收藏  举报