4

I'm going to use the StackOverflow's user profile's page as an example. Let's say we have this URL:

https://stackoverflow.com/users/2036414/userlogin

If we change (edit in the browser's url bar) the last path variable like this:

https://stackoverflow.com/users/2036414/aWordThatIsNotTheLoginOfThisUser

...and push Enter, the URL returned will be the first, what means that this variable is being setted to the right login, based on the other variable, which is probably the id of the user (2036414). In other words, the URL is corrected to:

https://stackoverflow.com/users/2036414/userlogin

My question is: how to do that using Spring MVC? Here's my controller:

@RequestMapping(value="/{id}/{login}", method = RequestMethod.GET)
public String showPerfilUsuario(@PathVariable("id") long id, @PathVariable("login") String login, Map<String, Object> model){
    Usuario usuario = usuarioService.buscarUsuarioPorId(id);
    model.put("usuario", usuario);
    return "usuario"; //that's the tiles definition's name
}

Any help will be apreciated, thanks.

0

1 Answer 1

6

Stackoverflow might be doing some fancy URL rewriting. A simple way to do this is to send a redirect. Have your handler method get the the user id and check if it matches the user name string. If it doesn't, then send a redirect

return "redirect:/users/" + id + "/" + correctUserName;

This will send a 302 response to the browser. The browser will send a new HTTP request to the constructed address.

Sign up to request clarification or add additional context in comments.

3 Comments

don't forget that (in this case) you shouldn't redirect if the username is already correct; otherwise you might get into a redirection loop :)
It worked very well! I thought in this solution, but I was forgetting the verification, which is crucial in this case. Thank you!
@vitorgreati You are welcome. Take note of Michal's comment too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.