开发者

Spring MVC RequestMapping matches wrong URL

I'm building a rest api for one webapp and have encountered a problem with RequestMapping.

Basicaly there are users, which are grouped together into various domains. When they work with the system some information is stored in an object called 'session' and written to DB.

I have the following URLs:

1)http://server.com/api/v1/domain/domainName/sessions - shows information about all sessions for all users in a domain.

2)http://server.com/api/v1/domain/domainName/user/userName/sessions - show information about sessions of particular user.

I'm using spring 3.0.5 and have declared 2 handlers in my controller class:

@RequestMapping(value = "/{domainId}/sessions", method=RequestMethod.GET)
public void findSessions(@PathVariable final String domainId) {
   ...
}

@RequestMapping(value = "/{domainId}/user/{username}/sessions", meth开发者_StackOverflowod=RequestMethod.GET)
public void findUserSessions(
        @PathVariable final String domainId,
        @PathVariable final String username) {
   ...
}

I'm using mixed controller mappings: SimpleUrlHandlerMapping + Annotations

Base path for controller is specified using SimpleUrlHandlerMapping:

<property name="mappings">
    <value>
    /api/v1/domain/** = api.DomainsController
    </value>
</property>

The problem is that both urls are handled by the first method. For URL 2, the username is bound to domainId pathvariable, thus braking method logic.

But, if i specify full path in request mapping - it works fine.

@RequestMapping(value = "/api/v1/domain/{domainId}/sessions", method=RequestMethod.GET)
@RequestMapping(value = "/api/v1/domain/{domainId}/user/{username}/sessions", method=RequestMethod.GET)


I think it would be better not to mix the SimpleUriHandlerMapping and RequestMapping methodologies. I don't think they are meant to work together.

I think what you'd want is just a Class level RequestMapping for the /api/v1/domain and then method level mappings for the individual cases.

So, in other words, remove the SimpleUrlHandlerMapping entry and do this instead:

@Controller
@RequestMapping(value = "/api/v1/domain")
public class DomainsController {

@RequestMapping(value = "/{domainId}/sessions", method=RequestMethod.GET)
public void findSessions(@PathVariable final String domainId) {
   ...
}

@RequestMapping(value = "/{domainId}/user/{username}/sessions", method=RequestMethod.GET)
public void findUserSessions(
        @PathVariable final String domainId,
        @PathVariable final String username) {
   ...
}

}

This tells Spring this controller is responsible for all requests starting with /api/v1/domain and then the method level request mappings are relative to this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜