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;
    }

}

 

 

 

参考文章

【1】SpringBoot中使用Servlet的两种方式

 

posted @   先娶国王后取经  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2020-03-26 为什么使用脚本读取的数据行数和真实的数据行数不一致?
点击右上角即可分享
微信分享提示