@PathVariable基本用法和Rest 风格的URL的请求 Spring MVC笔记(二)

当使用@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读取到。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,131评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,993评论 6 342
  • 翻译自Spring官方文档 4.1.2版本 相关文章: Spring参考手册 1 Spring Framework...
    liycode阅读 732评论 0 2
  • 1、Spring MVC请求流程 (1)初始化:(对DispatcherServlet和ContextLoderL...
    拾壹北阅读 1,980评论 0 12
  • Spring的模型-视图-控制器(MVC)框架是围绕一个DispatcherServlet来设计的,这个Servl...
    alexpdh阅读 2,685评论 0 3