1.创建一个springboot项目
package com.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.util.concurrent.ListenableFutureCallbackRegistry;
import com.test.filter.SecondFilter;
import com.test.listener.SecondListener;
import com.test.servlet.Hello02Servlet;
@SpringBootApplication
public class App2 {
public static void main(String[] args) {
SpringApplication.run(App2.class, args);
}
@Bean
public ServletRegistrationBean getServlet(){
ServletRegistrationBean bean=new ServletRegistrationBean(new Hello02Servlet(),"/hello02");
return bean;
}
}
2.创建一个servlet类
package com.test.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* springboot整合servlet方式一
* <servlet>
* <servlet-name>hello</servlet-name>
* <servlet-class>com.test.servlet.HelloServlet</servlet-class>
* </servlet>
* <servlet-mapping>
* <servlet-name>hello</servlet-name>
* <url-pattern>/hello</url-pattern>
* </servlet-mapping>
* @author 26920
*
*/
public class Hello02Servlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("hello02======");
super.doGet(req, resp);
}
}
3.相比注解方式,在servlet类中不用做任何处理,可以在springboot配置类中加方法创建bean,只要有@Configuration注解的类都是配置类,@SpringBootApplication注解是一个组合注解包含@Configuration,所以我在类中写了个方法,方法名随便但方法的返回类型必须是ServletRegistrationBean。ServletRegistrationBean类中可以设置访问路几个。