Spring MVC使用@PathVariable映射查询参数而不是URI模板值

时间:2012-07-10 15:40:02

标签: spring-mvc

@RequestMapping(value = "/account/{id}", method = RequestMethod.GET)
public ModelAndView getAccount(@PathVariable String id)
        throws ProfileNotFoundException {
   System.out.println(id);
   return null;
}

... / account / 12345结果为空

... / account / test?id = 12345'12345'的结果是12345

不知道如何解决此问题,但我希望第一个链接工作而不是第二个。这是我的webmvc-config.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd                 
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd                 
                        http://www.springframework.org/schema/mvc 
                        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

    <context:component-scan base-package="com.twheys.lexika.web.**"
        use-default-filters="false">
        <context:include-filter expression="org.springframework.stereotype.Controller"
            type="annotation" />
    </context:component-scan>

    <mvc:annotation-driven/>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

2 个答案:

答案 0 :(得分:0)

只需将其指定为@PathVariable("id") - 如果没有负责解析参数值的HandlerMethodArgumentResolver尝试通过参数名称找出参数值,则参数名称(id)在编译期间会丢失(除非调试编译期间符号打开,通常不是。

答案 1 :(得分:0)

@RequestMapping(value = "/authors/{authorId}")
public ModelAndView getAuthorById(@PathVariable String authorId) {
    Author author = bookService.getAuthorById(authorId);
    ModelAndView mav = 
        new ModelAndView("bookXmlView", BindingResult.MODEL_KEY_PREFIX + "author", author);
    return mav;
}

以上代码对我来说很好。请以类似的方式使用。