springboot中使用Servlet
在springboot中使用Servlet主要有两种方式:
方式一、使用注解的方式:
首先编写一个Servlet类继承HttpServlet,方式和正常写Servlet一样。
然后在这个类上面加上@WebServlet注解,如下:
@WebServlet(name = "MyServlet",urlPatterns = "/myServlet")//表示请求路径 public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().println("MyServlet"); resp.getWriter().flush(); resp.getWriter().close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } }
但是这个时候,Springboot并不知道你加了Servlet,所以需要在Main方法上加上@ServletComponentScan注解,表示Servlet组件扫描,可以加上参数basePackages来说明需要扫描的包是哪个。具体如下:
@SpringBootApplication//SpringBoot的全局的自动配置注解,所有的业务类都要放在子包下,才能自动配置 @ServletComponentScan(basePackages = {"com.kunkun.springboot.servlet"})//servlet扫描 public class Application { public static void main(String[] args) { //固定的代码,启动SpringBoot程序,初始化Spring容器 SpringApplication.run(Application.class, args); } }
这样就完成了Servlet的配置:结果如下:

方式二:配置类的方式
首先依然是写一个普通的Servlet,如下:
public class HeServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().println("HeServlet2222222,<br>坤坤"); resp.getWriter().flush(); resp.getWriter().close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } }
然后写一个配置类,如下:
@Configuration public class ServletConfig { /** * @Bean 注解等价于在Spring配置文件xml中配置一个Bean * <Bean id="xxx", class="xxx.xxx.xxx"> * * </Bean> * 方法名等于id,方法返回类型等于class * * @return */ @Bean public ServletRegistrationBean heServletRegistrationBean(){ //返回一个Servlet注册bean,在这里可以添加Servlet和请求路径 ServletRegistrationBean registration = new ServletRegistrationBean(new HeServlet(),"/servlet/heservlet"); return registration; } }
第二种方式,springboot提供的方式,结果如下:


浙公网安备 33010602011771号