1

I have the following problem. I want to use a controller, same for every page in my application. It is a common form included via include jsp in every page and it sends a mail to a predefined email account. The problem is, when I am posting the form, I get redirected to a blank page, with the url being my RequestMapping value despite the method called is actually void. So I need now to redirect me, after sending the mail to the page where I came from. How do I get access to the url link of the page that redirected me, into sending the email? Thanks

Bnrdo
  • 5,325
  • 3
  • 35
  • 63

1 Answers1

2

When returning void and one isn't handling writing the response yourself Spring MVC delegates detection of which view to render to a RequestToViewNameTranslator for which there is a single implementation the DefaultRequestToViewNameTranslator. Which basically takes the incoming URL, strips any suffixes (like .html etc.) and uses that as the viewname. The behavior you see now.

I guess you have 3 possible solutions

  1. Add a hidden form attribute which contains the current page
  2. Use the referer request header to determine where the request came from (not a 100% solution, See Alternative to "Referer" Header)
  3. Submit the form through ajax so that you stay on the current page

For option 2 add the HttpServletRequest as a parameter to your request handling method and retrieve the header.

public String foo(HttpServletRequest request) {
    String referer = request.getHeader("Referer");
    return "redirect:" + referer;
}

I would probably go for option 3 and maybe add option 1 as a fallback when no javascript is available.

Community
  • 1
  • 1
M. Deinum
  • 115,695
  • 22
  • 220
  • 224