Springboot 中使用 Servlet

1、自定义一个 Servlet 继承 HttpServlet

// 使用 @WebServlet 注解,并且给该 Servlet 起一个名字
@WebServlet("/myEmbedServlet")
public class MyEmbeddedServlet extends HttpServlet {
    @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.getWriter().write("xiao mao mao");
    }
}

2、启动类上标注 @ServletComponentScan 注解

@SpringBootApplication
// 标注要扫描哪个包下面的 Servlet
@ServletComponentScan(basePackages = {"com.xiaomaomao.springboot.controller"})
public class SpringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
}

3、浏览器发起访问 http://localhost:8080/myEmbedServlet

4、总结:
Springboot 中使用Servlet,是使用 Servlet3.x,不再使用 web.xml 配置文件来配置 Servlet ,而是通过注解实现 Servlet 开发。
Springboot 中不再使用 web.xml 配置文件映射 Servlet 信息

 

原文地址:https://www.cnblogs.com/xiaomaomao/p/14032616.html