Spring Boot集成servlet总共有两步
Step1:定义一个servlet类继承HttpServlet,并在该类上添加@WebServlet注解,给定访问地址,并重写该类的doGet()和doPost()方法,并且在doPost方法中调用doGet方法
@WebServlet(urlPatterns = "/servlet")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().println("hello servlet");
resp.getWriter().flush();
resp.getWriter().close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
Step2:在doGet方法中调用request类的方法实现需求
Step3:在Application入口类上添加@ServletComponent注解,给定扫描路径,扫描servlet类所在的路径;
@SpringBootApplication
@ServletComponentScan(basePackages = "com.study.springboot.servlet")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}