【问题标题】:Spring custom filter is not working with service layer methodSpring自定义过滤器不适用于服务层方法
【发布时间】:2017-12-30 06:11:06
【问题描述】:

我找到了解决方案,但我不明白为什么会这样,但另一个不行..

问题是,当我将 ServletRequest 转换为 HttpServletReuqest 并将请求传递给 Service 方法之一时,它就停在那里了。它试图抛出错误,我不确定。

当我在控制器中使用服务方法时它工作正常..(当我将相同的代码复制到过滤器类时问题已解决..但我不明白为什么它会中断,当我使用它时服务,但当我在我的 servlet 过滤器类中使用它时它可以工作)

这是我的代码:

public class AdminFilter extends GenericFilterBean { 

private final static Logger LOGGER = LogManager.getLogger("alog");
@Autowired
AccessService accessService;

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    if(request == null) {
        LOGGER.trace("request is null... why?"); //it was not null
    }
    if(httpRequest == null) {
        LOGGER.trace("httpRequest(after the cast) is null... why?");//it was not null
    }
    try {
        if (accessService.isAdmin(httpRequest)) {
            LOGGER.trace("User is Admin");
            filterChain.doFilter(request, response);
        }
    }
    catch (Exception E) {
        LOGGER.error("Request is empty : " + E.getStackTrace());//stack trace just gets null exception for not having a sepcific error handling 
    }

}

这是我的服务层方法:

    public boolean isAdmin(HttpServletRequest request) {
        LOGGER.trace("checking if the user is admin"); //this is never triggered.
        String user = request.getRemoteUser();

        //some logic here
        if (//some logic here) {
            //some logic here
            return true;
        }
        else {
            return false;   
        }
    }   

所以代码在遇到“isAdmin(request)”时会中断

但如果我不使用自动接线的服务方法,它就可以正常工作..

如果我只是将确切的代码复制并粘贴到我的 AdminFilter 类中并使用类似

的代码,它就可以工作
if (isAdmin(httpRequest)) 


//instead of   
if (accessService.isAdmin(httpRequest)) 

我知道我有解决方案..但我真的很想了解为什么...

【问题讨论】:

  • 让我猜猜,服务不是自动连接的,而是空的。

标签: spring spring-boot filter servlet-filters


【解决方案1】:

它是您的服务自动接线的正确实现吗?调试并查看服务是 null 还是其他 impl?

【讨论】:

  • 你好。我知道这是一个有点旧的帖子,但想分享我的发现。我确认@Autowired 的东西是空的......我只是有点困惑,因为它在我的本地工作,但是当我在遥控器上尝试它时它不是。研究表明,我不能将 autowire 与 servlet 过滤器一起使用,因为 servlet 过滤器是与 web.xml 连接的。
猜你喜欢
  • 1970-01-01
  • 2017-08-21
  • 2012-12-18
  • 1970-01-01
  • 2019-11-11
  • 2016-11-24
  • 1970-01-01
  • 2016-11-17
  • 1970-01-01
相关资源
最近更新 更多