Springboot 2.x中如何把web.xml中的Servlet、Listener、Filter以及 context-param 定义添加到SpringBoot中

先说有两种方法将Servlet、Listener和Filter定义添加到SpringBoot中,然后再说context-param如何添加

1. 通过注解的方式: https://docs.spring.io/spring-boot/docs/2.1.8.RELEASE/reference/htmlsingle/#boot-features-embedded-container-servlets-filters-listeners-beans

2. 通过SpringBean的方式:https://docs.spring.io/spring-boot/docs/2.1.8.RELEASE/reference/htmlsingle/#boot-features-embedded-container-servlets-filters-listeners

举例说明:web.xml如下(拿activemq 5.19.9 中 demo 的web.xml)

<?xml version="1.0" encoding="UTF-8"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at
   
    http://www.apache.org/licenses/LICENSE-2.0
   
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0"> 

    <display-name>Apache ActiveMQ Web Demo</display-name>

    <!-- context config -->
    <context-param>
    	<description>Whether we should include an embedded broker or not</description>
        <param-name>org.apache.activemq.embeddedBroker</param-name>
        <param-value>true</param-value>       
    </context-param>

	<!-- filters -->
	<filter>
		<filter-name>session</filter-name>
		<filter-class>org.apache.activemq.web.SessionFilter</filter-class>
		<async-supported>true</async-supported>
	</filter>
	<filter-mapping>
		<filter-name>session</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- listener -->
	<listener>
		<listener-class>org.apache.activemq.web.SessionListener</listener-class>
	</listener>

	<!-- servlet mappings -->
    
    <!-- the subscription REST servlet -->
    <servlet>
        <servlet-name>AjaxServlet</servlet-name>
        <servlet-class>org.apache.activemq.web.AjaxServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>

    <servlet>
        <servlet-name>MessageServlet</servlet-name>
        <servlet-class>org.apache.activemq.web.MessageServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
        <!--
        Uncomment this parameter if you plan to use multiple consumers over REST
        <init-param>
                <param-name>destinationOptions</param-name>
                <param-value>consumer.prefetchSize=1</param-value>
        </init-param> 
        -->
    </servlet>

    <!-- the queue browse servlet -->
    <servlet>
        <servlet-name>QueueBrowseServlet</servlet-name>
        <servlet-class>org.apache.activemq.web.QueueBrowseServlet</servlet-class>
        <async-supported>true</async-supported>
    </servlet>

    <!-- servlets for the portfolio demo -->
    <servlet>
        <servlet-name>PortfolioPublishServlet</servlet-name>
        <servlet-class>org.apache.activemq.web.PortfolioPublishServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>

	<!-- servlet mappings -->
    <servlet-mapping>
        <servlet-name>AjaxServlet</servlet-name>
        <url-pattern>/amq/*</url-pattern>
    </servlet-mapping>
    
    <servlet-mapping>
        <servlet-name>MessageServlet</servlet-name>
        <url-pattern>/message/*</url-pattern>
    </servlet-mapping>
    
    <servlet-mapping>
        <servlet-name>QueueBrowseServlet</servlet-name>
        <url-pattern>/queueBrowse/*</url-pattern>
    </servlet-mapping>
    
    <servlet-mapping>
        <servlet-name>PortfolioPublishServlet</servlet-name>
        <url-pattern>/portfolioPublish</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
      <welcome-file>index.html</welcome-file>
      <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

1. 通过注解的方式:

When using an embedded container, automatic registration of classes annotated with @WebServlet@WebFilter, and @WebListener can be enabled by using @ServletComponentScan.

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebListener;
import javax.servlet.annotation.WebServlet;

import org.apache.activemq.web.MessageServlet;
import org.apache.activemq.web.SessionFilter;
import org.apache.activemq.web.SessionListener;
//import org.apache.activemq.web.WebClient;
//import org.messaginghub.pooled.jms.JmsPoolConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ServletConfig {

    @WebServlet(asyncSupported=true,loadOnStartup=1,urlPatterns="/message/*")
    public class MyServlet extends MessageServlet {
	    //...
    }
    /**
    <!-- filters -->
	<filter>
		<filter-name>session</filter-name>
		<filter-class>org.apache.activemq.web.SessionFilter</filter-class>
		<async-supported>true</async-supported>
	</filter>
	<filter-mapping>
		<filter-name>session</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
    */
    @WebFilter(asyncSupported=true,urlPatterns="/*")
    public class MyFilter extends SessionFilter {
	    //...
    }
    /**
    <!-- listener -->
	<listener>
		<listener-class>org.apache.activemq.web.SessionListener</listener-class>
	</listener>
    */
    @WebListener()
    public class MyListener extends SessionListener {
	    //...
    }
}

在启动的类中添加  @ServletComponentScan

@SpringBootApplication
@ServletComponentScan
@ComponentScan(basePackages = {"com.lv.myapp" })
public class MyApplication {

	public static void main(String[] args) {
		
		SpringApplication application = new SpringApplication(MyApplication.class);
		//application.setBanner(new MyBanner());
		application.run(args);
		
	}

}

2. 通过SpringBean 的方式

@Configuration
public class ServletConfig {
    
    //Servlet
    @Bean
    public ServletRegistrationBean getMessageServletRegistrationBean() {  //一定要返回    ServletRegistrationBean
	    ServletRegistrationBean bean = new ServletRegistrationBean(new MessageServlet());         //放入自己的Servlet对象实例
        bean.addUrlMappings("/message/*");  //访问路径值
        bean.setAsyncSupported(true);
        bean.setLoadOnStartup(1);
        return bean;
    }
	
    @Bean
    public ServletRegistrationBean getAjaxServletRegistrationBean() {  
	    ServletRegistrationBean bean = new ServletRegistrationBean(new AjaxServlet());     //放入自己的Servlet对象实例
        bean.addUrlMappings("/amq/*");  //访问路径值
        bean.setAsyncSupported(true);
        bean.setLoadOnStartup(1);
        return bean;
    }
    //Filter    
    @Bean
    public FilterRegistrationBean sessionFilter() {
        FilterRegistrationBean sessionFilter = new FilterRegistrationBean(new SessionFilter());
        sessionFilter.addUrlPatterns("/*");
        sessionFilter.setAsyncSupported(true);
        return sessionFilter;
    }
    //Listener
    @Bean
    public ServletListenerRegistrationBean<SessionListener> setStartupServletContextListener(){
        ServletListenerRegistrationBean<SessionListener> result = new ServletListenerRegistrationBean<>();
        result.setListener(new SessionListener());
        //result.setOrder(20);
        return result;
    }
    
}

替换context-param

将以下Bean添加到ServletConfig中便可

@Bean
public ServletContextInitializer initializer() {
    return new ServletContextInitializer() {
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            //servletContext.setInitParameter("org.apache.activemq.brokerURL", brokerUrl);
            servletContext.setInitParameter("org.apache.activemq.embeddedBroker", "true");
            //servletContext.setAttribute(WebClient.CONNECTION_FACTORY_ATTRIBUTE, ((JmsPoolConnectionFactory) applicationContext.getBean(JmsPoolConnectionFactory.class)).getConnectionFactory());
        }
    };
}

针对 springboot 1.x中的配置 ,目前网上配置挺多的, 和Springboot 2.x 差别的主要是 定义全局的 contextparam 上

springboot 1.x 中的配置参照:https://blog.youkuaiyun.com/cysunc/article/details/84877028

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值