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

第一部分、上代码

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

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

2、监听器

 import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener; /**
*
*/
@WebListener
public class MyListener implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("监听器初始化");
System.out.println(servletContextEvent.getServletContext().getServerInfo());
} @Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("监听器销毁");
}
}

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、拦截器

 import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
*
* 拦截器实现
*/
public class MyInterceptor implements HandlerInterceptor { @Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.println("--------------拦截器请求前调用-----------------------------");
return true;// 只有返回true才会继续向下执行,返回false取消当前请求
} @Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)"); } @Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("在整个请求结束之后被调用,也就是在DispatcherServlet渲染了对应的视图之后执行(主要是用于进行资源清理工作)"); }
}

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

 import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.Configuration; /**
* Created by Administrator on 2017/7/31.
*/
@Aspect
@Configuration
public class MyAop {
/*
* 定义一个切入点
*/
@Pointcut("execution(* com.eternal.slovej.component.MyController.*(..))")
public void excudeService() {
System.out.println("==========定义切点===========");
} /**
* 通过连接点切入
*/
@Before("excudeService()")
public void twiceAsOld1(JoinPoint point) {
System.out.println("before切面执行了。。。。" + point.getKind());
} @Around("excudeService()")
public Object twiceAsOld(ProceedingJoinPoint thisJoinPoint) {
Object s =null ;
try {
s = thisJoinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
System.out.println("Around切面执行了。。。。");
return s;
} @After("excudeService()")
public void twiceAsOld3(JoinPoint point) {
System.out.println("after切面执行了。。。。" + point.getKind());
} @AfterReturning("excudeService()")
public void doFindByIdCheck() {
System.out.println("=======AfterReturning后置通知==================");
} }

7、控制器

 import com.eternal.slovej.Test;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController; /**
*
*/
@RestController
public class MyController { //添加了一个方法
@RequestMapping(value = "/hello")
@ResponseStatus(HttpStatus.OK)
public String hello(@RequestBody Test test) {
System.out.println("----进入方法----" + test.getName()+"---------------"+test.getAge());
return "no hello world";
}
}

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

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

  1. spring boot实战(第一篇)第一个案例

    版权声明:本文为博主原创文章,未经博主允许不得转载.   目录(?)[+]   spring boot实战(第一篇)第一个案例 前言 写在前面的话 一直想将spring boot相关内容写成一个系列的 ...

  2. Springboot 系列(六)Spring Boot web 开发之拦截器和三大组件

    1. 拦截器 Springboot 中的 Interceptor 拦截器也就是 mvc 中的拦截器,只是省去了 xml 配置部分.并没有本质的不同,都是通过实现 HandlerInterceptor ...

  3. Spring boot 配置自己的拦截器

    框架使用的是spring boot 2.0 首先,自定义拦截器实现HandlerInterceptor接口,preHandler是在执行controller方法前执行的  此外还有两个方法,具体作用最 ...

  4. spring boot 学习(十二)拦截器实现IP黑名单

    拦截器实现IP黑名单 前言 最近一直在搞 Hexo+GithubPage 搭建个人博客,所以没怎么进行 SpringBoot 的学习.所以今天就将上次的”?秒防刷新”进行了一番修改.上次是采用注解加拦 ...

  5. Spring Boot 优雅的配置拦截器方式

    https://my.oschina.net/bianxin/blog/2876640 https://cs.xieyonghui.com/java/55.html 其实spring boot拦截器的 ...

  6. Spring Boot实践——三种拦截器的创建

    引用:https://blog.csdn.net/hongxingxiaonan/article/details/48090075 Spring中的拦截器 在web开发中,拦截器是经常用到的功能.它可 ...

  7. 【spring boot】在自定义拦截器中从request中获取json字符串

    又这样的需求,需要在自定义的拦截器中获取request中的数据,想获取到的是JSON字符串 那需要在拦截器中写这样一个方法 public static String getOpenApiRequest ...

  8. ava中拦截器 过滤器 监听器都有什么区别

    过滤器,是在java web中,你传入的request,response提前过滤掉一些信息,或者提前设置一些参数,然后再传入servlet或者struts2的action进行业务逻辑,比如过滤掉非法u ...

  9. java中拦截器 过滤器 监听器都有什么区别

    过滤器,是在java web中,你传入的request,response提前过滤掉一些信息,或者提前设置一些参数,然后再传入servlet或者struts2的action进行业务逻辑,比如过滤掉非法u ...

随机推荐

  1. 菜鸟入门【ASP.NET Core】7:WebHost的配置、 IHostEnvironment和 IApplicationLifetime介绍、dotnet watch run 和attach到进程调试

    WebHost的配置 我们用vs2017新建一个空网站HelloCore 可以使用ConfigureAppConfiguration对配置进行更改,比如说添加jsonfile和commandline配 ...

  2. 【Quartz】1、Quartz使用说明

    简介 Quartz 是个开源的作业调度框架,为在 Java 应用程序中进行作业调度提供了简单却强大的机制.Quartz 允许开发人员根据时间间隔(或天)来调度作业.它实现了作业和触发器的多对多关系,还 ...

  3. Matlab 根号的输入

    二次根号: sqrt(a)或a^0.5 三次根号: x^(1/3)或者x.^(1/3) 根据x的数据结构类型 矩阵.数组需要.^

  4. docker swarm 搭建及跨主机网络互连案例分析

    准备工作 安装docker,不建议直接使用Docker官方的yum install docker wget http://yum.dockerproject.org/repo/main/centos/ ...

  5. HDU5293(SummerTrainingDay13-B Tree DP + 树状数组 + dfs序)

    Tree chain problem Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Other ...

  6. 洛谷P3722 [AH2017/HNOI2017]影魔(线段树)

    题意 题目链接 Sol 题解好神仙啊qwq. 一般看到这种考虑最大值的贡献的题目不难想到单调数据结构 对于本题而言,我们可以预处理出每个位置左边第一个比他大的位置\(l_i\)以及右边第一个比他大的位 ...

  7. const修饰指针的三种效果

    当用const进行修饰时,根据const位置的不同有三种不同效果. 判断的标准是:const修饰谁,谁的内容就是不可变的. 1 const int *p = &a; const修饰*p, *p ...

  8. JsonParseException:非法的unquoted字符((CTRL-CHAR,代码9)):必须被转义

     其它异常,Could not read document: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped  ...

  9. JavaScript大杂烩0 - WEB基础知识

    1. 协议小结:HTTP协议与TCP/IP协议 现代Web应用开发的基础是HTTP协议,那么HTTP协议与我们熟知的TCP/IP协议有什么关系呢? 这个要从网络通信模型说起,简单的说,计算机通信就像两 ...

  10. 遇到npm报错read ECONNRESET怎么办

    遇到npm 像弱智一样报错怎么办 read ECONNRESET This is most likely not a problem with npm itselft 'proxy' config i ...