简体   繁体   中英

Spring MVC - Edit the response URL with path variables

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM