Ad

How Do I Tell When A Request Is A Forward In PreHandle Using Spring MVC?

- 1 answer

I have the following...

@GetMapping("signup")
public String get(){
    return "forward:/";
}

@Override
public boolean preHandle(HttpServletRequest request,
                       HttpServletResponse response,
                       Object handler) throws IOException {
    ...
        if(!per.isPresent() && !request.getRequestURL().toString().contains("signup")){
            response.sendRedirect("/signup");
            return false;
        }
}

The problem here is when the forward comes it isn't signup so I redirect back. However, I also want to intercept requests that go directly to the root.

Is there any way to tell if a request is a forward and what the original url was?

Ad

Answer

Here is the solution I came up with that works. I don't like this answer and I would prefer not attaching a custom header when it seems like the info that it is a forward should be available. However, since I couldn't find that info in the docs I just added the header...

@GetMapping("")
public String get(HttpServletResponse response){
    response.setHeader("signup","true");
    return "forward:/";
}

Then I checked for it

private static boolean isSignupForward(HttpServletResponse response){
    return Boolean.valueOf(response.getHeader("signup"));
}
...
if(
  !isSignupForward(response) &&
  !per.isPresent() &&
  !isSignup(request) &&
  !isJsFile(request)
){
  response.sendRedirect("/signup");
  return false;
}

I will leave the bounty in case someone has a better answer.

Ad
source: stackoverflow.com
Ad