赞
踩
springboot 默认配置了一个DispatcherServlet 实现数据和页面的请求分开处理,通过
定义ServletRegistrationBean的对象实现,这个bean是由spring boot提供专门来注册servlet的,可以象注册bean一样去配置servlet。
该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;
}
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);
}
}
该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;
}
RestControllerConfig:设置自定义的的ServletRegistrationBean的静态资源访问路径,禁止访问静态资源
@Configuration
@EnableWebMvc
public class RestControllerConfig extends WebMvcConfigurerAdapter{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**");
}
}
只有以.json结尾的请求才能拿到响应数据
只有以.html结尾的请求才能响应页面
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。