【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 大神的精彩文章

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM