基于原生的Servlet,通过了功能强大的前端控制器DispatcherServlet,对请求和相应进行统一处理
如今我们不再去web.xml中去主持servlet
 而是直接创建一个配置类ServletContainersInitConfig去基础AbstractDispatcherServletInitializer
createServletApplicationContext()方法是为了创建Servlet容器,加载SpringMVC对应的bean并放入WebApplicationContext对象范围中
createRootApplicationContext()方法是为了创建servlet容器时需要加载非SpringMVC对应的bean
getServletMappings()设定SpringMVC对应的请求映射路径,设置为/表示拦截所有请求
 //不管是springmvc.class 还是 spring.class 一般都需要加上注释@ComponentScan(“com/…”),包扫描
 主配置类ServletContainersInitConfig
 相关配置类SpringMvcConfig、SpringConfig
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer{
   protected WebApplicationContext createServletApplicationContext(){
   //配置springmvc的容器
      AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
      ctx.register(SpringMvcConfig.class);
      return ctx;
   }
   protected String[] getServletMappings(){
      return new String[]{"/"};
   }
    protected WebApplicationContext createRootApplicationContext(){
    //配置spring的容器
           AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
      ctx.register(SpringConfig.class);
      return ctx;
  //添加过滤器
  protected Filter[] getServletFilters(){
     CharacterEncodingFilter filter = new CharacterEncodingFilter();
     filter.setEncoding("utf-8");
     return new Filter[]{filter};
     //有多个的情况 return new Filter[]{filter,filter1,filter2};要么用它自带的过滤器,要么自己创建
  }
  
}
传参时
前端后端名字相对好即可,名称对应不上就用@RequstParam
 json 参数加上注解 @RequestBody(配件springmvc的配置类上加@EnableWebMvc)
拦截器
拦截器与过滤器的区别
归属不同: Filter属于Servlet技术,Interceptor属于SpringMvc技术
 拦截内容不同: Filter对所有访问进行增强,Interceptor仅针对SpringMvc的访问进行增强
编写拦截器(实现该三个方法)
@Componet
public class ProjectIntercaptor implements HandlerInterceptor{
  @Override
  public boolean preHandle(HttpServletRequest request,HttpServeletResponse response,Object handler) throws Exception{
      System.out.println("");
      return true;
  }
  @Override
  public boolean postHandle(HttpServletRequest request,HttpServeletResponse response,ModelAndView modelAndView) throws Exception{
      System.out.println("");
  }
  @Override
  public void afterCompletion(HttpServletRequest request,HttpServeletResponse response,Object handler,Exception ex) throws Exception{
      System.out.println("");
  }
}
注册拦截器
(也可以直接SpringMvcConfig类直接实现WebMvcConfiguer,然后直接在该类创建下面的方法,不用再去写个support类了)
public class SpringMvcSupport extends WebMvcConfigurationSupport{
  //继承WebMvcConfigurationSupport,就可以覆写很多添加方法,当然添加拦截器也是其中的一种
  @Autowired //把我们自己写的拦截器配置到注入到容器中
  private ProjectInterceptor projectInterceptor;
  @Override
  protected void addInterceptors(InterceptorRegistry registry){
     registry.addInterceptor(projectInterceptor).addPathPatterns("/books");
  }
}
拦截器参数
request 可以拿到请求的信息
 reponse 可以设置返回的信息
 handler 通过抢占可以拿到原始的方法
各个组件




















