1

I have added a servlet filter to skip the login the page for some GET method.If the request has start with /DataService , It should redirect to Get method mentioned below.

Filter Implementation:

 @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 Method

@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;
    }.

Help me how to forward the request from do filter method to loadAllData() method in DataController.I am not using web.xml and used java configuration for filter configuration. I have tired below snippet but its again redirecting to dofilter method.

else if (request.getServletPath().startsWith("/DataService")) {
            request.getRequestDispatcher(request.getServletPath()).forward();
Rithik_Star
  • 651
  • 5
  • 14
  • 39

1 Answers1

0

I would suggest making a validator for the id. Why does it need to be a forward and not a redirect?

// 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
geco17
  • 5,152
  • 3
  • 21
  • 38