Spring Boot中是否有Filter类(用于web应用程序)的注释?也许@Filter ?

我想在我的项目中添加一个自定义过滤器。

Spring Boot参考指南中提到过 FilterRegistrationBean,但我不确定如何使用它。


当前回答

Use:

@WebFilter(urlPatterns="/*")
public class XSSFilter implements Filter {

    private static final org.apache.log4j.Logger LOGGER = LogManager.getLogger(XSSFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.info("Initiating XSSFilter... ");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpRequestWrapper requestWrapper = new HttpRequestWrapper(req);
        chain.doFilter(requestWrapper, response);
    }

    @Override
    public void destroy() {
        LOGGER.info("Destroying XSSFilter... ");
    }

}

你需要实现Filter,并且它需要用@WebFilter(urlPatterns="/*")进行注释。

在Application或Configuration类中,您需要添加@ServletComponentScan。通过此操作,您的筛选器将被注册。

其他回答

这是一个建议而不是答案,但如果你在你的web应用程序中使用Spring MVC,最好使用Spring HandlerInterceptor而不是Filter。

它可以做同样的工作,但是

可以使用ModelAndView吗 它的方法可以在请求处理之前和之后调用,或者在请求完成之后调用。 它很容易测试

1. 实现HandlerInterceptor接口,并向类中添加@Component注释

@Component
public class SecurityInterceptor implements HandlerInterceptor {

    private static Logger log = LoggerFactory.getLogger(SecurityInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.getSession(true);
        if(isLoggedIn(request))
            return true;

        response.getWriter().write("{\"loggedIn\":false}");
        return false;
    }

    private boolean isLoggedIn(HttpServletRequest request) {
        try {
            UserSession userSession = (UserSession) request.getSession(true).getAttribute("userSession");
            return userSession != null && userSession.isLoggedIn();
        } catch(IllegalStateException ex) {
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}

2. 配置拦截器

@Configuration
public class WebConfig implements WebMvcConfigurer {

    private HandlerInterceptor securityInterceptor;

    @Autowired
    public void setSecurityInterceptor(HandlerInterceptor securityInterceptor) {
        this.securityInterceptor = securityInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(securityInterceptor).addPathPatterns("/**").excludePathPatterns("/login", "/logout");
    }

}

众所周知,Spring Boot是开发web应用程序或独立应用程序的一种极好的方式,具有最低的配置和独立的设置。

这就是我如何在Spring Boot应用程序中实现web过滤器开发的

我的SpringBootApp规格:

Spring Boot版本:2.0.4.RELEASE Java版本:8.0 Servlet规范:Servlet 3.0(强制性和重要)

我以以下方式声明了我的web过滤器,遵循Servlet规范3.0

这是定义过滤器作为基于web.xml定义的替代品的编程方式。

“@Webfilter”注释将在部署期间由容器处理。它所在的Filter类将根据配置创建,并应用于URL模式javax.servlet.Servlets和javax.servlet.DispatcherTypes。

要完全避免Web.xml,实现“可部署”的WebApp:

要将SpringBoot应用程序部署为“Traditional WAR”,应用程序类应该扩展SpringBootServletInitializer。

注意:

SpringBootServletInitializer是web.xml的“编程实现”,参考了Servlet 3.0+规范,它需要WebApplicationInitializer的实现。

因此,SpringBootApplication不需要“web.xml”作为它的应用程序类(在扩展SpringBootServletInitializer之后)。它扫描

@WebFilter, @WebListener鸭 @WebServlet。

注释@ServletComponentScan

这个注释允许扫描带有@WebFilter, @WebListener和@WebServlet注释的web组件的基本包。

由于嵌入式容器不支持@WebServlet、@WebFilter和@WebListener注解,Spring Boot在很大程度上依赖于嵌入式容器,引入了这个新的注解@ServletComponentScan来支持一些使用这三种注解的依赖JAR文件。

扫描只在使用嵌入式Servlet容器时执行。

下面是我的Spring Boot应用程序类定义:

自定义Servlet初始化器:

这里:我定义了一个自定义类:“ServletInitializer”,它扩展了class: SpringBootServletInitializer。

如前所述,SpringBootServletInitializer负责扫描注释:

@WebFilter, @WebListener鸭 @WebServlet。

因此Spring Boot应用程序类应该这样做

扩展类:SpringBootServletInitializer或 扩展扩展该类的自定义类:SpringBootServletInitializer

对于基于任何条件和spring引导中的任何列表的过滤,查询语言更加灵活,并允许我们向下过滤到我们需要的确切资源。 例如,如果我们有一个简单的实体,如User,并像这样定义它。

@Entity
public class User {
@Id
@GeneratedValue(strategy = 
GenerationType.AUTO)
private Long id;

private String firstName;
private String lastName;
private String email;

private int age;

//Setter and getter as usual

然后我们创建一个实现Specification接口的UserSpecification,我们将传递我们自己的约束来构造实际的查询。在本部分中,与标准和构建器相关的方法非常有用和灵活。

public class UserSpecification implements Specification<User> {

private SearchCriteria criteria;

@Override
public Predicate toPredicate
  (Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder) {

    if (criteria.getOperation().equalsIgnoreCase(">")) {
        return builder.greaterThanOrEqualTo(
          root.<String> get(criteria.getKey()), criteria.getValue().toString());
    } 
    else if (criteria.getOperation().equalsIgnoreCase("<")) {
        return builder.lessThanOrEqualTo(
          root.<String> get(criteria.getKey()), criteria.getValue().toString());
    } 
    else if (criteria.getOperation().equalsIgnoreCase(":")) {
        if (root.get(criteria.getKey()).getJavaType() == String.class) {
            return builder.like(
              root.<String>get(criteria.getKey()), "%" + criteria.getValue() + "%");
        } else {
            return builder.equal(root.get(criteria.getKey()), criteria.getValue());
        }
    }
    return null;
}
}

此外,我们还创建了一个基于以下SearchCriteria类中表示的一些简单约束的规范,任何条件都可以像这样创建:

public class SearchCriteria {
private String key;
private String operation;
private Object value;
 }

最后定义UserRepository和扩展JpaSpecificationExecutor,

public interface UserRepository 
extends JpaRepository<User, Long>, 
JpaSpecificationExecutor<User> {}

用一个Spring原型(如@Component)注释你的过滤器。在Spring @Configuration中注册一个Filter类型的@Bean。在Spring @Configuration中用FilterRegistrationBean类型注册一个@Bean。

下面是我的自定义Filter类的一个例子:

package com.dawson.controller.filter;

import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
public class DawsonApiFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        if (req.getHeader("x-dawson-nonce") == null || req.getHeader("x-dawson-signature") == null) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setContentType("application/json");
            httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Required headers not specified in the request");
            return;
        }
        chain.doFilter(request, response);
    }
}

我将它添加到Spring Boot配置中,如下所示:

package com.dawson.configuration;

import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import com.dawson.controller.filter.DawsonApiFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

@SpringBootApplication
public class ApplicationConfiguration {
    @Bean
    public FilterRegistrationBean dawsonApiFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new DawsonApiFilter());

        // In case you want the filter to apply to specific URL patterns only
        registration.addUrlPatterns("/dawson/*");
        return registration;
    }
}