过滤器是用于拦截应用程序的HTTP请求和响应的对象。通过使用过滤器,可以在两个实例上执行两个操作 -
- 在将请求发送到控制器之前
- 在向客户发送响应之前。
以下代码显示了带有@Component
注解的Servlet过滤器实现类的示例代码。
@Component public class SimpleFilter implements Filter { @Override public void destroy() {} @Override public void doFilter (ServletRequest request, ServletResponse response, FilterChain filterchain) throws IOException, ServletException {} @Override public void init(FilterConfig filterconfig) throws ServletException {} }//原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/spring-boot/spring_boot_servlet_filter.html
以下示例显示了在将请求发送到控制器之前从ServletRequest
对象读取远程主机和远程地址的代码。
在doFilter()
方法中,添加了System.out.println()
语句来打印远程主机和远程地址。
package com.yiibai.demo; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.springframework.stereotype.Component; @Component public class SimpleFilter implements Filter { @Override public void destroy() {} @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchain) throws IOException, ServletException { System.out.println("Remote Host:"+request.getRemoteHost()); System.out.println("Remote Address:"+request.getRemoteAddr()); filterchain.doFilter(request, response); } @Override public void init(FilterConfig filterconfig) throws ServletException {} }//原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/spring-boot/spring_boot_servlet_filter.html