1. 程式人生 > 其它 >Spring Boot之註冊servlet三大元件

Spring Boot之註冊servlet三大元件

技術標籤:servletservletfilterListener

由於Spring Boot預設是以jar包的形式啟動嵌入式的Servlet容器來啟動Spring Boot的web應用是,沒有web.xml配置檔案
註冊三大元件用以下方式

ServletRegistrationBean
FilterRegistrationBean
ServletListenerRegistrationBean



一、註冊一個ServletRegistrationBean

1.定義一個Servlet類

//向頁面輸出一句hello
public class HttpServlet extends javax.
servlet.http.HttpServlet
{ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("hello"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException { this.doPost(request,response); } }

2.編寫一個Servlet配置類

@Configuration
public class MyServerConfig {
    //註冊三大元件
    //注意加上@Bean註解,否者無法加入到容器中
    @Bean
    public ServletRegistrationBean myServlet(){
        ServletRegistrationBean servlet = new ServletRegistrationBean
(new HttpServlet(), "/myServlet"); return servlet; }

3.Spring Boot配置檔案

server.port=8081
server.servlet.context-path=/boot
server.tomcat.uri-encoding=UTF-8

4.啟動主配置檔案訪問http://localhost:8081/boot/myServlet
在這裡插入圖片描述

這樣就生效了



二、註冊一個FilterRegistrationBean

1.定義一個Filter類

public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("success");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

2.編寫一個filter配置類

@Configuration
public class MyServerConfig {
    //註冊三大元件

    @Bean
    public FilterRegistrationBean filterRegistrationBean(){
        FilterRegistrationBean re = new FilterRegistrationBean();
        re.setFilter(new MyFilter());
        re.setUrlPatterns(Arrays.asList("/hello","/filter"));
        return re;
    }

3.啟動訪問http://localhost:8081/boot/filter

在這裡插入圖片描述


ServletListenerRegistrationBean的使用類似於以上兩種元件

Spring Boot 幫我們自動註冊了SpringMVC的核心控制器DispatcherServlet,其註冊方式類似於以上兩種註冊