Spring MVC Controller configuration - mixing annotations and XML @PathVariable
I am developing a web app using the Spring MVC framework (v3).
Currently I have several controller classes defined - I have created them by extending the MultiActionController and then in my web mvc XML config defined the beans and the URL mappings:
QuestionController.java:
public class QuestionController extends MultiActionController implements InitializingBean
{
webmvc-config.XML
<bean id="questionController" class="com.tmm.enterprise.microblog.controller.QuestionController"></bean>
...
<bean id="fullHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="alwaysUseFullPath开发者_如何学Go" value="true" />
<property name="mappings">
<props>
<prop key="/question/**">questionController</prop>
</props>
</property>
</bean>
This works fine, I define methods in my controller matching the URLs being called and everything works correctly (for example, I have a list(..)
method, that gets correctly executed when I browse to /question/list
).
However, for this particular controller I want to make use of the @PathVariable
option in Spring to allow for variable URLs (e.g. i want a details(..)
method, that when I call /question/detail/9999
- where 9999
is a question ID the method is executed). I have tried to use this as follows:
QuestionController.java:
@RequestMapping("/detail/{questionId}")
public ModelAndView detail(@PathVariable("questionId") long questionId, HttpServletRequest request, HttpServletResponse response) throws Exception{
However, I get an error when I run the above and get:
Could not find
@PathVariable
[questionId
] in@RequestMapping
Has anyone come across this before? Is it ok to mix RequestMapping
annotations with the existing XML configured URL mapping?
This is the comment from DefaultAnnotationHandlerMapping class, If i am reading the comment right, If you add @RequestMapping at the top of your QuestionController.java, It might resolve your problem
Annotated controllers are usually marked with the {@link Controller} stereotype at the type level. This is not strictly necessary when {@link RequestMapping} is applied at the type level (since such a handler usually implements the {@link org.springframework.web.servlet.mvc.Controller} interface). However, {@link Controller} is required for detecting {@link RequestMapping} annotations at the method level if {@link RequestMapping} is not present at the type level.
EDIT
You can do some thing like this, move the /question part of the uri to the top and leave the detail part at the method level
@RequestMapping("/question")
public class QuestionController
{
@RequestMapping("/detail/{questionId}")
public ModelAndView detail(@PathVariable("questionId") long questionId, HttpServletRequest request, HttpServletResponse response) throws Exception{
}
精彩评论