整理一下这几天学习的资料和代码
第一部分、上代码
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 大神的精彩文章