springboot实战之注册自定义Servlet

来源:互联网 发布:双系统扩大windows内存 编辑:程序博客网 时间:2024/05/18 02:19

应用场景

在以前的web项目,servlet常用与特殊处理,比如验证码的实现,对外暴露http接口等等,重要性不言而喻。

springboot也有自己的实现servlet的方式。

  • 代码注册servlet

    通过ServletRegistrationBean、FilterRegistrationBean、ServletListenerRegistrationBean、ServletContextInitializer

    案例采用通过ServletRegistrationBean注册实现

  • 注解注册servlet

    比较方便,首先再SpringBootApplication(springboot项目入口)上添加@ServletComponentScan注解,其次,是自定义Servlet上添加@WebServlet注解

一、代码注册实现

自定义servlet MyServlet.java

// 方法二:通过@WebServlet//@WebServlet(urlPatterns = "/myServlet.view",description = "这事我自定义的servlet")public class MyServlet extends HttpServlet {    private final Logger _logger = LoggerFactory.getLogger(this.getClass());    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        _logger.info("===========doGet()============");        doPost(req, resp);    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        _logger.info("===========doPost()============");        resp.setCharacterEncoding("utf-8");        resp.setContentType("text/html");        PrintWriter out = resp.getWriter();        out.println("<html>");        out.println("<head>");        out.println("<title>Hello World</title>");        out.println("</head>");        out.println("<body>");        out.println("<h1>这是我自定义的Servlet</h1>");        out.println("</body>");        out.println("</html>");    }}

自定义配置文件

@Configurationpublic class ServertConfig {    /**     * 方法一:通过ServletRegistrationBean注册     * @return     */    @Bean    public ServletRegistrationBean servletRegistrationBean(){        return new ServletRegistrationBean(new MyServlet(),"/myServlet/*") ;    }}

程序入口

@SpringBootApplication//@ServletComponentScan(basePackages = "com.hsy.springboot.servlet")public class SpringBootServletApplication {    public static void main(String[] args) {        SpringApplication.run(SpringBootServletApplication.class,args);    }}

项目结构图

这里写图片描述

二、注解实现

1.将程序入口的//@ServletComponentScan(basePackages = “com.hsy.springboot.servlet”) 解注释

2.将MyServlet 中的 //@WebServlet(urlPatterns = “/myServlet.view”,description = “这事我自定义的servlet”) 解注释。

源码

springboot-servlet

历史文章

SpringBoot实战之入门

springboot实战之文章汇总

springboot实战之读取配置文件

springboot实战之整合jsp模版引擎

springboot实战之整合freemarker模版引擎

原创粉丝点击