您现在的位置是:主页 > news > 浦东新区苏州网站建设/百度云手机app下载
浦东新区苏州网站建设/百度云手机app下载
admin2025/5/3 15:51:13【news】
简介浦东新区苏州网站建设,百度云手机app下载,食品行业做网站,手机网站建网文章目录1. 配置2. 定制三大组件1. 配置Servlet2. 配置Filter3. 配置listener4. DIspatcherServlet在Spring boot中默认使用tomcat作为嵌入式的Servlet容器,现在来介绍Servlet配置及其原理。1. 配置 经常在项目中会设置服务器各种配置,包括端口、地址 一…
文章目录
- 1. 配置
- 2. 定制三大组件
- 1. 配置Servlet
- 2. 配置Filter
- 3. 配置listener
- 4. DIspatcherServlet
在Spring boot中默认使用tomcat作为嵌入式的Servlet容器,现在来介绍Servlet配置及其原理。
1. 配置
经常在项目中会设置服务器各种配置,包括端口、地址
一般通过配置文件进行修改,当然,记住如此多的的配置设置肯定不太现实,只需要关心ServerProperties
文件,查看有什么配置需要修改即可。
//修改服务器
server.port=8081
server.context-path=/crud
//修改tomcat设置
server.tomcat.uri-encoding=UTF-8server.xxx //通用的Servlet容器设置
server.tomcat.xxx //Tomcat的设置
ServerProperties源码,
@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties {/*** Server HTTP port.*/
private Integer port;/*** Network address to which the server should bind.*/
private InetAddress address;
2. 定制三大组件
由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文件,没有办法像传统的Spring mvc配置对应的servlet、Listener、Filter,因此需要自定制相应的组件。
1. 配置Servlet
只需要自己提前写好对应的Servlet,将其注册到容器中。只需要产生对应的ServletRegistrationBean
对象即可。
@Configuration
public class MyServletConfig {//提前写好myServlet,通过@Bean方式注册到配置文件中@Beanpublic ServletRegistrationBean myServlet(){ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(), "/myServlet");return registrationBean;}
2. 配置Filter
同样是写好对应的Filter注册到容器中,new一个对应的FilterRegistrationBean
即可。
@Configuration
public class MyServletConfig {//注册filter@Beanpublic FilterRegistrationBean myFilter(){FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();filterRegistrationBean.setFilter(new myFilter());filterRegistrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));return filterRegistrationBean;}
3. 配置listener
提前定义好自己的Listener,通过ServletListenerRegistrationBean
方式注入进容器中
@Bean
public ServletListenerRegistrationBean myListener(){ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());return registrationBean;
}
4. DIspatcherServlet
SpringBoot帮我们自动SpringMVC的时候,自动的注册SpringMVC的前端控制器;DIspatcherServlet;
DispatcherServletAutoConfiguration中:
@Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)
@ConditionalOnBean(value = DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public ServletRegistrationBean dispatcherServletRegistration(DispatcherServlet dispatcherServlet) {ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet, this.serverProperties.getServletMapping());//默认拦截: / 所有请求;包静态资源,但是不拦截jsp请求; //会拦截jsp//可以通过server.servletPath来修改SpringMVC前端控制器默认拦截的请求路径registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);registration.setLoadOnStartup(this.webMvcProperties.getServlet().getLoadOnStartup());if (this.multipartConfig != null) {registration.setMultipartConfig(this.multipartConfig);}return registration;
}