springboot 配置多个DispatcherServlet 实现前端接口和后台管理端路径规则的分离

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

复写 spring boot提供的ServletRegistrationBean

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

    @Bean
    public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
    	ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet);
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(DispatcherControllerConfig.class);
        dispatcherServlet.setApplicationContext(applicationContext);
    	registration.addUrlMappings("*.html","*.js","*.css","*.png","*.jpg","*.gif","*.woff");
        return registration;
    }

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);
 	    }  
}

定义自定义的servletServletRegistrationBean

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

		@Bean
	    public ServletRegistrationBean bar() {
	        DispatcherServlet dispatcherServlet = new DispatcherServlet();
	        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
	        applicationContext.register(RestControllerConfig.class);
	        applicationContext.scan("cn.rest.controller");
	        dispatcherServlet.setApplicationContext(applicationContext);
	        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(dispatcherServlet);
	        servletRegistrationBean.setName("restServlet");
	        servletRegistrationBean.addUrlMappings("*.json");
	        return servletRegistrationBean;
	    }

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

@Configuration
@EnableWebMvc
public class RestControllerConfig extends WebMvcConfigurerAdapter{
	    @Override
	    public void addResourceHandlers(ResourceHandlerRegistry registry) {
	        registry.addResourceHandler("/**");
	    }
}

end

只有以.json结尾的请求才能拿到响应数据
在这里插入图片描述
只有以.html结尾的请求才能响应页面
springboot 配置多个DispatcherServlet 实现前端接口和后台管理端路径规则的分离_第1张图片

你可能感兴趣的:(码农进阶)