Spring Boot basic study notes 13: path scanning integration Servlet three components

Zero, learning goals

  1. Master the use of path scanning method to integrate Servlet
  2. Master the use of path scanning method to integrate Filter
  3. Master the use of path scanning method to integrate Listener

In Spring Boot, when using path scanning to integrate the three components of Servlet, Filter, and Listener of the embedded Servlet container, you first need to add @WebServlet, @WebFilterand @WebListenerannotate to declare on the custom component separately , and configure the relevant attribute, and then Use @ServletComponentScanannotations on the startup class of the project main program to start component scanning.

1. Create a Spring Boot project-IntegrateThreeComponents02

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

2. Integrate the three major components of Servlet using path scanning

(1) Create the MyServlet class

Insert picture description here

package net.hw.lesson13.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;

/**
 * 功能:自定义Servlet
 * 作者:华卫
 * 日期:2021年02月28日
 */
@WebServlet("/hello")
public class MyServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
    
    
        System.out.println(req.getAttribute("hello"));
        System.out.println(req.getServletContext().getAttribute("message"));
        resp.setDateHeader("Expires", -1); // 浏览器不缓存
        resp.getWriter().println("Servlet向你问候:牛年大吉!");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
    
    
        doGet(req, resp);
    }
}
  • @WebServlet("/hello")Define urlPattern for MyServlet through annotations

(2) Create the CodeServlet class

Insert picture description here

package net.hw.lesson13.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;
import java.util.Random;

/**
 * 功能:生成6位字母数字验证码
 * 作者:华卫
 * 日期:2021年02月28日
 */
@WebServlet("/code")
public class CodeServlet extends HttpServlet {
    
    
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
    
    
        System.out.println(req.getAttribute("hello"));
        System.out.println(req.getServletContext().getAttribute("message"));
        resp.setDateHeader("Expires", -1);// 浏览器不缓存
        resp.getWriter().println(randomCode(6));
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
    
    
        doGet(req, resp);
    }

    /**
     * 产生指定位数随机码
     *
     * @param len
     * @return
     */
    public String randomCode(int len) {
    
    
        char[] codes = {
    
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
                'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4',
                '5', '6', '7', '8', '9'};
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < len; i++) {
    
    
            int index = new Random().nextInt(35);
            buffer.append(codes[index]);
        }
        return buffer.toString();
    }
}

(C) Create the MyFilter class

Insert picture description here

package net.hw.lesson13.filter;

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

/**
 * 功能:自定义过滤器
 * 作者:华卫
 * 日期:2021年02月28日
 */
@WebFilter(value = {
    
    "/hello", "/code"})
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 {
    
    
        //过滤器可以对request请求处理之前进行一些预处理
        servletRequest.setAttribute("hello", "过滤器向你问候:牛年大吉!");
        //也可以在request请求处理之后进行一些处理
        servletResponse.setCharacterEncoding("UTF-8");//解决中文乱码
        servletResponse.setContentType("text/html;charset=utf8");
        filterChain.doFilter(servletRequest, servletResponse); // 不要忘记了此句,否则程序正常请求流程就不走了
    }

    @Override
    public void destroy() {
    
    
    }
}
  • Annotate @WebFilter(value = {"/hello", "/code"})MyFilter to filter two specified requests.

(4) Create the MyListener class

Insert picture description here

package net.hw.lesson13.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * 功能:自定义监听器
 * 作者:华卫
 * 日期:2021年02月28日
 */
@WebListener("/")
public class MyListener implements ServletContextListener {
    
    
    @Override
    public void contextInitialized(ServletContextEvent sce) {
    
    
        System.out.println("ServletContext对象创建完成!");
        // 可以把相关数据写到context中
        ServletContext context = sce.getServletContext();
        context.setAttribute("message", "ServletContext初始化完成了!");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    
    
        System.out.println("ServletContext对象已经销毁!");
        // 在context环境消亡时,可以更新数据等
    }
}
  • @WebListener("/")Monitor all requests through annotations .

(5) Modify the entry class and add ServletComponentScan annotation

Insert picture description here

(6) Start the application and test the effect

  • View the console output after launching the application
    Insert picture description here
  • accesshttp://localhost:8080/hello
    Insert picture description here
  • accesshttp://localhost:8080/code
    Insert picture description here
  • As you can see, the results of the project are exactly the same as those of the previous project.

Three, path scanning integration Servlet three components summary

Using the annotation method, you can save configuration files (such as ServletConfig, FilterConfig, and ListenerConfig), greatly simplifying the operation. In actual applications, try to use this method to integrate the three major components of Servlet.

Guess you like

Origin blog.csdn.net/howard2005/article/details/114211021