繁体   English   中英

Servlet过滤器将请求转发到无限循环

[英]Servlet filter forward the request to infinite loop

我添加了一个servlet过滤器来跳过某些GET方法的登录页面。如果请求以/ DataService开头,则应重定向到下面提到的Get方法。

过滤器实现:

 @Override
    public void doFilter(final ServletRequest arg0, final ServletResponse arg1, final FilterChain filterChain)
            throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) arg0;
        final HttpServletResponse response = (HttpServletResponse) arg1;
        final HttpSession session = request.getSession();

        final String id = (String) session.getAttribute("id");
 if ((request.getRequestURL().indexOf("/login")) < 0) {
        if (id == null) {
            error = "authentication required";
        }
    }
        if (null == error) {
            filterChain.doFilter(request, response); // happy flow
        } else if (request.getServletPath().startsWith("/DataService")) {
           // Need to redirect to one GET method

        } else { // unauthorized flow
            request.getRequestDispatcher("/login").forward(request, response);
        }
    }

GET方法

@RestController
@RequestMapping("/DataService")
public class DataController {

    @Autowired
    private DataLoaderService dataLoader;

    @RequestMapping(value = "/loadAllStaticData", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Boolean loadAllData() throws DataLoadException {
        DataLoader.loadAllData();
        return true;
    }.

帮助我如何将请求从do过滤器方法转发到DataController中的loadAllData()方法。我没有使用web.xml,而是将Java配置用于过滤器配置。 我已经在代码段下面累了,但是再次将其重定向到dofilter方法。

else if (request.getServletPath().startsWith("/DataService")) {
            request.getRequestDispatcher(request.getServletPath()).forward();

我建议为id做一个验证器。 为什么它需要是转发而不是重定向?

// get the id to validate
if (isValid(id)) {
    filterChain.doFilter(request, response);
} else {
    if (request.getServletPath().starts with("/DataService")) {
    response.sendRedirect("/DataService/loadAllData");
    } else {
        String error = "something";
        // do whatever you want with your error message
        response.send redirect("/login" );
    }
}

// make your boolean isValid method

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM