简体   繁体   English

Spring MVC - 使用路径变量编辑响应URL

[英]Spring MVC - Edit the response URL with path variables

I'm going to use the StackOverflow's user profile's page as an example. 我将使用StackOverflow的用户配置文件页面作为示例。 Let's say we have this URL: 假设我们有这个网址:

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

If we change (edit in the browser's url bar) the last path variable like this: 如果我们更改(在浏览器的url栏中编辑)最后一个路径变量,如下所示:

https://stackoverflow.com/users/2036414/aWordThatIsNotTheLoginOfThisUser 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). ...并按Enter键,返回的URL将是第一个,这意味着此变量被设置为正确的登录,基于另一个变量,可能是用户的id(2036414)。 In other words, the URL is corrected to: 换句话说,URL被更正为:

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

My question is: how to do that using Spring MVC? 我的问题是:如何使用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 . Stackoverflow可能正在做一些奇特的URL重写 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. 让您的处理程序方法获取用户ID并检查它是否与用户名字符串匹配。 If it doesn't , then send a redirect 如果没有 ,则发送重定向

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

This will send a 302 response to the browser. 这将向浏览器发送302响应。 The browser will send a new HTTP request to the constructed address. 浏览器将向构造的地址发送新的HTTP请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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