天天看點

SpringBoot實戰之7 注冊自定義Servlet

應用場景

在以前的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>");
    }
}
           

自定義配置檔案

@Configuration
public 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);
    }
}
           

項目結構圖

SpringBoot實戰之7 注冊自定義Servlet

二、注解實作

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

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

源碼

springboot-servlet

曆史文章

SpringBoot實戰之入門

springboot實戰之文章彙總

springboot實戰之讀取配置檔案

springboot實戰之整合jsp模版引擎

springboot實戰之整合freemarker模版引擎

繼續閱讀