一般情况下,使用Spring、Spring MVC这些框架之后,基本上就告别Servlet、Filter以及Listener 了,但是有时在整合一些第三方框架时,可能还是不得不使用Servlet,比如在整合某报表插件时就需要使用Servlet。Spring Boot中对于整合这些基本的Web组件也提供了很好的支持。
启动类上添加@ServletComponentScan描述
@ServletComponentScan
public class RuoYiApplication {
public static void main(String[] args) {
...
}
}
import org.springframework.stereotype.Component;
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测试
* 接口url:/my
*/
//@Component
@WebServlet("/my")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//打印name参数
System.out.println("MyServlet>>" + req.getParameter("name"));
}
}
package com.ruoyi.web.servlet.config;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
/**
* 过滤器
* WebFilter指定过滤请求
*/
@WebFilter("/*")
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//每次有请求时执行
System.out.println("MyFilter>>doFilter");
//请求放行
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//项目启动时执行
System.out.println("MyFilter>>init");
}
@Override
public void destroy() {
System.out.println("MyFilter>>destroy");
}
}
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
/**
* 自定义监听器
*/
@WebListener
public class MyListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("监听器: MyListener >> requestDestroyed");
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
System.out.println("监听器: MyListener >> requestInitialized");
}
}