当前位置:   article > 正文

springboot 配置多个DispatcherServlet 实现前端接口和后台管理端路径规则的分离_springboot2 配置多个dispatcherservlet 处理.do .htm请求,con

springboot2 配置多个dispatcherservlet 处理.do .htm请求,controller分离

springboot 默认配置了一个DispatcherServlet 实现数据和页面的请求分开处理,通过
定义ServletRegistrationBean的对象实现,这个bean是由spring boot提供专门来注册servlet的,可以象注册bean一样去配置servlet。

复写 spring boot提供的ServletRegistrationBean

该DispatcherServlet负责处理以.html结尾的请求,并开放静态资源。

    @Bean
    public ServletRegistrationBean<DispatcherServlet> dispatcherRegistration(DispatcherServlet dispatcherServlet) {
    	ServletRegistrationBean<DispatcherServlet> registration = new ServletRegistrationBean<DispatcherServlet>(dispatcherServlet);
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(DispatcherControllerConfig.class);
        dispatcherServlet.setApplicationContext(applicationContext);
    	registration.addUrlMappings("*.html","*.js","*.css","*.png","*.jpg","*.gif","*.woff");
        return registration;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

DispatcherControllerConfig:对默认的ServletRegistrationBean的静态资源访问路径进行映射

@Configuration
@EnableWebMvc
public class DispatcherControllerConfig implements WebMvcConfigurer{
	    @Override
	    public void addResourceHandlers(ResourceHandlerRegistry registry) {
	        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
	       WebMvcConfigurer.super.addResourceHandlers(registry);
 	    }  
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

定义自定义的servletServletRegistrationBean

该DispatcherServlet负责处理以.json结尾的请求,也就是数据。

		@Bean
	    public ServletRegistrationBean<HttpServlet> bar() {
	        DispatcherServlet dispatcherServlet = new DispatcherServlet();
	        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
	        applicationContext.register(RestControllerConfig.class);
	        applicationContext.scan("cn.rest.controller");
	        dispatcherServlet.setApplicationContext(applicationContext);
	        ServletRegistrationBean<HttpServlet> servletRegistrationBean = new ServletRegistrationBean<HttpServlet>(dispatcherServlet);
	        servletRegistrationBean.setName("restServlet");
	        servletRegistrationBean.addUrlMappings("*.json");
	        return servletRegistrationBean;
	    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

RestControllerConfig:设置自定义的的ServletRegistrationBean的静态资源访问路径,禁止访问静态资源

@Configuration
@EnableWebMvc
public class RestControllerConfig extends WebMvcConfigurerAdapter{
	    @Override
	    public void addResourceHandlers(ResourceHandlerRegistry registry) {
	        registry.addResourceHandler("/**");
	    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

end

只有以.json结尾的请求才能拿到响应数据
在这里插入图片描述
只有以.html结尾的请求才能响应页面
在这里插入图片描述

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号