2

Suppose I have 3 url patterns that needs to be handled by Spring MVC as follows:

1) www.example.com/login (to login page)

2) www.example.com/home (to my home page)

3) www.example.com/john (to user's home page)

I would like to know what is the best practice way of handling the url pattern that has username as part of the url (real world example is facebook fanpage www.faceboo.com/{fanpage-name})

I have come up with my own solution but not sure if this is the clean way or possible to do it.

In my approach, I need to intercept the request before it being passed to Spring MVC's dispatchservlet, then query the database to convert username to userid and change the request URI to the pattern that Spring MVC can recognize like www.example/user/userId=45. But I am not sure if this is doable since the ServletAPI does not have the setter method for requestURI(it does have the getter method for requestURI)

Or if you have a better solution please share with me. Thank in advance :-)

4

1 に答える 1

2

Spring MVC は、PathVariables を使用してこれを問題なく処理できるはずです。

/login 用の 1 つのハンドラー、/home 用の 1 つのハンドラー、および /{userName} 用の 1 つのハンドラー。ユーザー名ハンドラー内で、ルックアップを実行してユーザーを取得できます。このようなもの:

@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
}
于 2013-03-06T16:24:46.627 に答える