美文网首页技术干货程序员
@PathVariable基本用法和Rest 风格的URL的请求

@PathVariable基本用法和Rest 风格的URL的请求

作者: 强出头 | 来源:发表于2017-07-24 09:50 被阅读0次

当使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId}, 这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上。

Spring MVC使用@Pathvariable注解时候需要配置HiddenHttpMethodFilter,首先需要在web.xml中配置,具体代码如下


<!-- 配置HiddenHttpMethodFilter:可以把 POST 请求转为 DELETE 或 PUT 请求 -->
  <filter>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

然后是@Pathvariable的具体使用,在方法中的代码如下


/*
    * Rest 风格的URL
    * 需要配置HiddenHttpMethodFilter
    * */
    @RequestMapping(value = "/testPathVariable/{id}" ,method = RequestMethod.POST)
    public String testPathVariable(@PathVariable(value = "id") Integer id){
        System.out.println("testPathVariable id = " + id);
        return SUCCESS;
    }

在.jsp前端显示的代码如下


<form action="/hello/testPathVariable/5" method="post">
    <input type="submit" value="testPathVariable"/>
</form>

action="/hello/testPathVariable/5"这里的5会被作为参数会被@PathVariable读取到。

相关文章

网友评论

    本文标题:@PathVariable基本用法和Rest 风格的URL的请求

    本文链接:https://www.haomeiwen.com/subject/qbivkxtx.html