springboot配置嵌入式servlet容器的方法
某刘姓男子i 人气:0配置嵌入式Servlet容器
springboot默认tomcat为嵌入式servlet容器,所以不用在配置tomcat。
1.如何定制修改servlet容器?
1.在applicatio.properties里修改和server有关的配置(推荐)
如:
server.tomcat server.tomcat.connection-timeout= 连接超时时间 server.tomcat.uri-encoding=UTF-8 修改编码
server.servlet.XXX 通用servlet容器设置
server.tomcatXXX 一般是Tomcat的设置
2.通过代码的方式修改配置
-编写一个配置类 @Configuration 注解即可
-在里面添加一个ConfigurableServletWebServerFactory定制器
@Bean public ConfigurableServletWebServerFactory configurableServletWebServerFactory(){ TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();//这里是一个工厂 factory.setPort(8088);//修改端口号 //factory.setContextPath("/lanqiao518"); return factory; }
-返回定制器,并注入到容器中 @Bean ,这个时候就配置好了
3.注册Servlet三大组件(servlet、Listener【监听器】,Filter【过滤器】)
首先要自己写一个类,分别实现三大组件自己的接口然后才能添加进容器中
这里以servlet为例:
Servlet:
public class MyServlet extends HttpServlet {//写好servlet下一步给他添加进容器中 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=utf-8"); resp.setCharacterEncoding("utf-8"); resp.getWriter().write("hello 你好"); } }
listener:
public class Mylistener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("项目启动了————————————————————————"); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("项目关闭了————————————————————————"); } }
Filter:
public class MyFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("MyFilter拦截了----------------------"); filterChain.doFilter(servletRequest,servletResponse);//然后放行 } @Override public void destroy() { } }
1.将自己写的servlet注入容器:
@Configuration public class MyServletConfig { //将自己写的servlet添加进容器 @Bean public ServletRegistrationBean myServlet(){ ServletRegistrationBean registrationBean=new ServletRegistrationBean(new MyServlet(),"/my");//将自己写的servlet添加进来,并给一个访问路径 return registrationBean; } }
2.将自己写的Linstener注入容器
@Bean public ServletListenerRegistrationBean myListener() { ServletListenerRegistrationBean listenerRegistrationBean = new ServletListenerRegistrationBean(new Mylistener());//传一个自己写的监听器即可 return listenerRegistrationBean; }
3.将自己写的Filter注入容器
@Bean public FilterRegistrationBean myFilter(){ FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean(new MyFilter(),myServlet());//传一个自己写的Filter 和你要拦截的servlet 可以是多个 return filterRegistrationBean; }
注意:注入时的名称和自己编写的类名一致
加载全部内容