假设我有3个需要由Spring MVC处理的url模式,如下所示:
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之前拦截请求,然后查询数据库以将username转换为userid并将请求URI更改为Spring MVC可以识别的模式,如www.example / user /用户id = 45。 但我不确定这是否可行,因为ServletAPI没有setter方法 对于requestURI(它确实有requestURI的getter方法)
或者如果您有更好的解决方案,请与我分享。提前感谢:-)
答案 0 :(得分:2)
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
}