springboot-filter

本文展示了如何在SpringBoot应用中使用@WebFilter注解创建一个过滤器,拦截所有请求,并在请求处理前后打印信息。同时,定义了一个Servlet来响应特定路径的请求。通过@ServletComponentScan注解扫描并注册组件。
  • 首先应该定义一个类用于实现Filter接口,重写doFilter方法

  • 在类上加注解@WebFilter("/*")并设置拦截路径。

@WebFilter("/*")
public class oneFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        System.out.println("经过了Filter!");
        filterChain.doFilter(request,response);
    }
}
  • 在写一个servlet接口用于访问
@WebServlet("/ttt")
public class oneController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=utf-8");
        resp.getWriter().println("欢迎你!");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
  • 在主类中添加@ServletComponentScan(“com.ssp”)
@SpringBootApplication
@ServletComponentScan("com.ssp")
public class Application {

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

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值