Facundo Ch.
Facundo Ch.

Reputation: 12214

How to manage URLs on errors on Spring MVC?

I have a webapp with Spring MVC 3.0.4.RELEASE.

I have the following scenario:

1) I enter a search web page by GET with the path: search.html
2) I click search and do a POST to the path: searchResults.hmtl
3) When I click a search result, I do a POST to searchResults/enterResult.html
4) Let assume that the controller raises an exception...
5) I need to return to searchResults.html page with the previous search.

I can't use forward, because it maintains the path searchResults/enterResults.html, so if I click o a search result it builds the following inexistent path: searchResults/searchResults/enterResults.html

do you know how to manage this problem?

Upvotes: 1

Views: 322

Answers (1)

limc
limc

Reputation: 40160

If the error occurs, why not do a redirect:searchResults.html instead of forwarding it? If you want to send the error message back to be displayed in that page, you can add them as parameters, like this: redirect:searchResults.html?error_message=yada.

By the way, if you avoid using relative URL when constructing your search result form action, you shouldn't get searchResults/searchResults/enterResults.html problem in the first place. It does seem like you are doing a POST on enterResults.html instead of /your-app/searchResults/enterResults.html If you fix this, you won't need to perform the redirect as I mentioned above.

What I'm trying to say here is:

... instead of doing this...

<form action="enterResults.html" method="POST">
    ...
</form>

... do this...

<form action="${pageContext.request.contextPath}/searchResults/enterResults.html" method="POST">
    ...
</form>

This way, it doesn't really matter if the forwarded URL retains the previous URL or not. You will always POST to the right action.

Upvotes: 2

Related Questions