Java Spring MVC 3 中的 Restful 路径参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2951012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:51:42  来源:igfitidea点击:

Restful Path Parameters in Spring MVC 3

javaspringrest

提问by MDK

Is it possible to: set a URI template in the mvc:view-controller element of the *-servlet.xml file or in a controller method and then use/get that path parameter in a jsp?

是否可以:在 *-servlet.xml 文件的 mvc:view-controller 元素或控制器方法中设置 URI 模板,然后在 jsp 中使用/获取该路径参数?

I understand that using @PathVariable in a controller method will give me access to the path parameter in that controller method. But how can I gain access to the path parameter in the jsp?

我知道在控制器方法中使用 @PathVariable 将使我能够访问该控制器方法中的路径参数。但是如何才能访问jsp 中的 path 参数?

For example, is it possible to do something like:

例如,是否可以执行以下操作:

*-servlet.xml file:

*-servlet.xml 文件:

<beans...>
<mvc:view-controller path="/home" view-name="home"/>
<mvc:view-controller path="/home/{error}" view-name="home"/>
</beans>

jsp file:

jsp文件:

<c:if test="${not empty param['error']}">
<span class="error">You have an error...</span>
</c:if>

回答by Affe

If you want access to it in the jsp, return it as an attribute from the controller:

如果要在 jsp 中访问它,请将其作为属性从控制器返回:

@RequestMapping("/home/{error}")
public void handleError(@PathVariable String error, ModelMap model) {
    //your regular stuff

    model.addAttribute("error", error);
}

-

——

<c:if test="${not empty error}">
<span class="error">You have an error...</span>
</c:if>

回答by axtavt

The Mapof resolved path variables is exposed as an attirubte with name specifed by HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE. So, the solution is

Map解决路径变量的暴露与名称的attirubte通过specifed HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE。所以,解决办法是

<c:if test="${not empty requestScope['org.springframework.web.servlet.HandlerMapping.uriTemplateVariables']['error']}">

But accessing it this way is probably not a best idea, Affe's solution is cleaner.

但是以这种方式访问​​它可能不是一个最好的主意,Affe 的解决方案更简洁。