spring - 处理将用户名作为 url 一部分的 url 模式

标签 spring spring-mvc url-rewriting

假设我有 3 个 url 模式需要由 Spring MVC 处理,如下所示:

1) www.example.com/login(登录页面)

2) www.example.com/home(到我的主页)

3) www.example.com/john(到用户主页)

我想知道处理将用户名作为 url 一部分的 url 模式的最佳实践方法是什么(真实世界的示例是 facebook fanpage www.faceboo.com/{fanpage-name})

我已经提出了自己的解决方案,但不确定这是否是干净的方法或可能做到这一点。

在我的方法中,我需要在将请求传递给 Spring MVC 的dispatchservlet 之前拦截请求,然后查询数据库以将用户名转换为 userid 并将请求 URI 更改为 Spring MVC 可以识别的模式,例如 www.example/user/用户ID=45。 但我不确定这是否可行,因为 ServletAPI 没有 setter 方法 对于requestURI(它确实有requestURI的getter方法)

或者如果您有更好的解决方案请与我分享。预先感谢:-)

最佳答案

Spring MVC 应该能够使用 PathVariables 很好地处理这个问题。

一个用于/login 的处理程序、一个用于/home 的处理程序和一个用于/{userName} 的处理程序。在用户名处理程序中,您可以进行查找以获取用户。像这样的事情:

@RequestMapping(value="/login", method=RequestMethod.GET)
public String getLoginPage() {
    // Assuming your view resolver will resolve this to your jsp or whatever view
    return "login";
}

@RequestMapping(value="/home", method=RequestMethod.GET)
public String getHomePage() {
    return "home";
}

@RequestMapping(value="/{userName}", method=RequestMethod.GET)
public ModelAndView getUserPage( @PathVariable() String userName ) {
    // do stuff here to look up the user and populate the model
    // return the Model and View with the view pointing to your user page
}

关于spring - 处理将用户名作为 url 一部分的 url 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15252588/

相关文章:

java - 将 JSF .xhtml 文件映射到无扩展名

Spring 本地化,无需在查询字符串中传递语言

java - 当发现 302 状态代码时,私有(private) IP 在 HTML 中公开

java - spring-boot-starter-amqp 依赖导致 StackOverflowError

java - Spring hibernate CRUD : ORA-00923: FROM keyword not found where expected

json - spring mvc restcontroller 返回 json 字符串

php - .htaccess Url Rewrite 删除查询字符串键

asp.net - 如何删除www. ASP.NET MVC 中的前缀

java - 无法 Autowiring 字段(Spring mvc - 注释)

spring - 自定义实现UserDetails的示例