Micro Personnel Day: springboot integrated web infrastructure components

Now we need to configure servlet, Filter, Listener in this series of web components in springboot

Configuration servlet component
if the access / myservlet get request and executes a method in doGet

package org.javaboy.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/myservlet")
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("MyServlet");
    }


}

2. The filter assembly disposed
herein interceptor to intercept all paths

package org.javaboy.servlet;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

//表示拦截所有的地址
@WebFilter(urlPatterns = "/*")
public class MyFilter implements Filter {

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

Configuration listener
with a method and initial destruction methods listener method

package org.javaboy.servlet;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class MyRequestListener implements ServletRequestListener {

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        System.out.println("requestDestroyed");
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        System.out.println("requestInitialized");
    }
}

4. Start the class configuration
After configuring servlet, listener and filter, or not start classes obtained by scanning the package now scanned in these three components

package org.javaboy.servlet;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan(basePackages = "org.javaboy.servlet")
public class ServletApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServletApplication.class, args);
    }

}

After starting the Print Console:

requestInitialized
MyFilter
MyServlet
requestDestroyed
Published 277 original articles · won praise 23 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_41998938/article/details/104020239