【问题标题】:How to execute a filter on specific request in spring mvc?如何在spring mvc中对特定请求执行过滤器?
【发布时间】:2018-04-07 19:46:09
【问题描述】:

下面是过滤器。

@Component
public class TestFilter extends GenericFilterBean {

@Override
public void doFilter(
  ServletRequest request, 
  ServletResponse response,
  FilterChain chain) throws IOException, ServletException {
    chain.doFilter(request, response);
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    System.out.println("token is: "+httpRequest.getHeader("token"));
}    
}

以下是资源 我只想对第二个请求执行上述过滤器。

如何实现,请帮忙....

@RestController
public class UserResourceImpl implements UserResource {

private final UserDao userDao;
private final AuthenticationService authenticationService;
@Autowired
public UserResourceImpl(final UserDao userDao,final AuthenticationService authenticationService) {
this.userDao = userDao; 
this.authenticationService = authenticationService;
}

@Override
@RequestMapping(method = RequestMethod.POST, value = "/api/user", produces = "application/json")
public ResponseEntity<?> create(final User user) {
    userDao.save(user);
    return new ResponseEntity<>("", HttpStatus.OK);
}

@Override
@RequestMapping(method = RequestMethod.GET, value = "/api/user", produces = "application/json")
public ResponseEntity<?> getUsers(final User user) {


enter code here
    // how to execute the above filter for this request only ?

    return new ResponseEntity<>("", HttpStatus.OK);
}

}

【问题讨论】:

    标签: java spring spring-mvc jakarta-ee spring-boot


    【解决方案1】:

    您可以尝试使用HandlerInterceptorAdapter。它通过 url 而不是特定的方法工作,所以它不是你想要的,但它应该可以工作:

    public class MyInterceptor extends HandlerInterceptorAdapter {
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //To work with a specific method on the url
            if(request.getMethod().equals("GET")){
                //Do stuff
            }
    
            return super.preHandle(request, response, handler);
        } 
    
        //There is also a postHandle and postCompletion method that can be override     
    }
    

    并在WebMvcConfigurerAdapter注册:

    public class SpringMvcContextConfig extends WebMvcConfigurerAdapter {
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new MyInterceptor()).addPathPatterns("/yourUrl");
        }
    }
    

    另一种解决方案是使用带有 spring-mvc 的 Aspect 并在方法上设置 PointCut。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-09-17
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 2011-06-15
      • 1970-01-01
      • 2015-01-10
      • 2020-11-14
      相关资源
      最近更新 更多