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

时间:2017-12-11 19:53:20

标签: java spring-mvc servlets

我添加了一个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);
        }
    }

获取方法

@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 filter方法转发到DataController中的loadAllData()方法。我没有使用web.xml并使用java配置进行过滤器配置。  我已经厌倦了下面的片段,但它再次重定向到dofilter方法。

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

1 个答案:

答案 0 :(得分:0)

我建议为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