在JSP视图中,Spring 3.0.6 MVC @PathVariable和@RequestParam为空/空

ale*_*ler 12 spring spring-annotations spring-3

我一直试图设置一个非常简单的控制器/视图,但是无法使其工作.在我web.xml,我已经定义了一个<servlet>名为servlet-context.xml,运行正常.在servlet-context.xml,我设置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"

<...other stuff in here... />

<mvc:annotation-driven />
Run Code Online (Sandbox Code Playgroud)

除其他事项外.我的理解是这就是使用@注释所需要的一切.

在我的控制器中,我有:

@RequestMapping(value="/student/{username}/", method=RequestMethod.GET)
public String adminStudent(@PathVariable String username, @RequestParam String studentid) {
    return "student";
}
Run Code Online (Sandbox Code Playgroud)

在我student.jsp看来,我有:

<p>This is the page where you would edit the stuff for ${username}.</p>
<p>The URL parameter <code>studentid</code> is set to ${studentid}.</p>
Run Code Online (Sandbox Code Playgroud)

当我发出请求时http://localhost:8080/application/student/xyz123/?studentid=456,我得到了我期望的视图,但所有变量都是空白或为空:

<p>This is the page where you would edit the stuff for .</p>
<p>The URL parameter <code>studentid</code> is set to .</p>
Run Code Online (Sandbox Code Playgroud)

我怀疑这是用我的方式有问题web.xmlservlet-context.xml正在建立,但我不能在任何地方找到罪魁祸首.据我所见,在任何日志中都没有显示任何内容.


更新:我的代码基于spring-mvc-showcase的这一部分:

@RequestMapping(value="pathVariables/{foo}/{fruit}", method=RequestMethod.GET)
public String pathVars(@PathVariable String foo, @PathVariable String fruit) {
    // No need to add @PathVariables "foo" and "fruit" to the model
    // They will be merged in the model before rendering
    return "views/html";
}
Run Code Online (Sandbox Code Playgroud)

...对我来说很好.我无法理解为什么这个例子有效但我的不行.是不是因为他们正在做一些不同的servlet-context.xml

<annotation-driven conversion-service="conversionService">
    <argument-resolvers>
        <beans:bean class="org.springframework.samples.mvc.data.custom.CustomArgumentResolver"/>
    </argument-resolvers>
</annotation-driven>
Run Code Online (Sandbox Code Playgroud)

duf*_*ymo 17

创建模型映射并将参数名称/值对添加到其中:

@RequestMapping(value="/student/{username}/", method=RequestMethod.GET)
public String adminStudent(@PathVariable String username, @RequestParam String studentid, Model model) {
    model.put("username", username);
    model.put("studentid", studentid);

    return "student";
}
Run Code Online (Sandbox Code Playgroud)


ale*_*ler 7

啊哈!最后想出来了.

spring-mvc-showcase是使用Spring 3.1,这将自动地暴露@PathVariables到模型中,根据SPR-7543.

正如@duffymo和@JB Nizet指出的那样,添加到Model中的model.put()是为早于3.1的Spring版本做的事情.

Ted Young用Spring向我指出了正确的方向:将@PathVariables暴露给模型.