java servlet
Spring MVC的核心控制器DispatcherServlet会处理所有的请求,项目中使用Controller基本能解决大部分的功能需求,但有时也需要使用Servlet,比如实现拦截和监听功能;
Servlet 是 Sun 公司所设计开发的可以用于接收和处理 HTTP 请求的 Java 类,Spring MVC 这样的框架就是对 Servlet 的二次封装
即servlet和controller一样能接收请求
使用servlet的两种方式
方式一
使用@WebServlet和@ServletComponentScan注解
@WebServlet(urlPatterns="/ServletDemo/*")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doGet");
resp.getWriter().print("Get Servlet ServletDemo");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doPost");
resp.getWriter().print("Post Servlet ServletDemo");
}
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doPut");
resp.getWriter().print("Put Servlet ServletDemo");
}
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doDelete");
resp.getWriter().print("Delete Servlet ServletDemo");
}
}
@SpringBootApplication
@ServletComponentScan
public class ServletApplication {
public static void main(String[] args) {
SpringApplication.run(ServletApplication.class, args);
}
}
方式二
使用配置类
@Configuration
public class ServletConfig {
@Bean
public ServletRegistrationBean myServletRegistrationBean() {
ServletRegistrationBean servletRegistrationBean=new ServletRegistrationBean(
new MyServlet(),"/ServletDemo"
);
return servletRegistrationBean;
}
}
参考文章