冷知识,几乎用不到

在spring boot中使用Servlet有两种实现方法;

方法一:

正常创建servlet,然后只用注解@ServletComponentScan

package clc.user.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; /**
* ClassName: FirstServlet<br/>
* Description:spring boot 整合sevlet <br/>
* date: 2019/4/1 4:07 PM<br/>
* <p>
* 正常创建Servlet
* 可以使用@WebServlet注解实现
* 在spring boot启动类加注解@ServletComponentScan,会让spring启动时扫描@WebServlet注解并实例化
*
* @author chengluchao
* @since JDK 1.8
*/ @WebServlet(name = "FirstServlet", urlPatterns = "/FirstServlet")
public class FirstServlet extends HttpServlet { @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
System.out.println("FirstServlet");
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}

对应的启动类:

@SpringBootApplication
@ServletComponentScan
public class UserServiceApplication { public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}

----------

方法二:

正常创建Servlet,但不对其进行配置,放到启动类来操作

package clc.user.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; /**
* ClassName: SecondServlet<br/>
* Description:spring boot 整合sevlet <br/>
* date: 2019/4/1 4:07 PM<br/>
* <p>
*
* @author chengluchao
*
* 需要:
* @Bean public ServletRegistrationBean getServletRegistrationBean() {
* ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
* bean.addUrlMappings("SecondServlet");
* return bean;
* }
* @since JDK 1.8
*/ public class SecondServlet extends HttpServlet { @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
System.out.println("SecondServlet");
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
@SpringBootApplication
public class UserServiceApplication2 { @Bean
public ServletRegistrationBean getServletRegistrationBean() {
ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
bean.addUrlMappings("/SecondServlet");
return bean;
} public static void main(String[] args) {
SpringApplication.run(UserServiceApplication2.class, args);
}
}
05-11 19:43