spring3 的restful API RequestMapping介绍

简介: 原文链接:http://www.javaarch.net/jiagoushi/694.htmspring3 的restful API RequestMapping介绍在spring mvc中 @RequestMapping是把web请求映射到controller的方法上。

原文链接:http://www.javaarch.net/jiagoushi/694.htm

spring3 的restful API RequestMapping介绍


在spring mvc中 @RequestMapping是把web请求映射到controller的方法上。


1.RequestMapping Basic Example
  将http请求映射到controller方法的最直接方式
1.1 @RequestMapping  by Path
 
@RequestMapping(value = "/foos")
@ResponseBody
public String getFoosBySimplePath() {
return "Get some Foos";
}

可以通过下面的方式测试: curl -i http://localhost:8080/springmvc/foos


1.2 @RequestMapping – the HTTP Method,我们可以加上http方法的限制


@RequestMapping(value = "/foos", method = RequestMethod.POST)
@ResponseBody
public String postFoos() {
return "Post some Foos";
}

可以通过curl i -X POST http://localhost:8080/springmvc/foos测试。


2.RequestMapping 和http header


2.1 @RequestMapping with the headers attribute
  当request的header包含某个key value值时

@RequestMapping(value = "/foos", headers = "key=val")
@ResponseBody
public String getFoosWithHeader() {
return "Get some Foos with Header";
}

  header多个字段满足条件时
  
@RequestMapping(value = "/foos", headers = { "key1=val1", "key2=val2" })
@ResponseBody
public String getFoosWithHeaders() {
return "Get some Foos with Header";
}

通过curl -i -H "key:val" http://localhost:8080/springmvc/foos 测试。


2.2 @RequestMapping 和Accept头


@RequestMapping(value = "/foos", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public String getFoosAsJsonFromBrowser() {
return "Get some Foos with Header Old";
}
支持accept头为json的请求,通过curl -H "Accept:application/json,text/html" http://localhost:8080/springmvc/foos测试


在spring3.1中@RequestMapping注解有produces和 consumes 两个属性来代替accept头


@RequestMapping(value = "/foos", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public String getFoosAsJsonFromREST() {
return "Get some Foos with Header New";
}
同样可以通过curl -H "Accept:application/json" http://localhost:8080/springmvc/foos测试


produces可以支持多个


@RequestMapping(value = "/foos", produces = { "application/json", "application/xml" })

当前不能有两个方法同时映射到同一个请求,要不然会出现下面这个异常


Caused by: java.lang.IllegalStateException: Ambiguous mapping found. 
Cannot map 'fooController' bean method
public java.lang.String org.baeldung.spring.web.controller.FooController.getFoosAsJsonFromREST()
to {[/foos],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}: 
There is already 'fooController' bean method
public java.lang.String org.baeldung.spring.web.controller.FooController.getFoosAsJsonFromBrowser() 
mapped.

3.RequestMapping with Path Variables
3.1我们可以把@PathVariable把url映射到controller方法
单个@PathVariable参数映射

@RequestMapping(value = "/foos/{id}")
@ResponseBody
public String getFoosBySimplePathWithPathVariable(@PathVariable("id") long id) {
  return "Get a specific Foo with id=" + id;
}


通过curl http://localhost:8080/springmvc/foos/1试试
如果参数名跟url参数名一样,可以省略为


@RequestMapping(value = "/foos/{id}")
@ResponseBody
public String getFoosBySimplePathWithPathVariable(@PathVariable String id) {
  return "Get a specific Foo with id=" + id;
}
3.2 多个@PathVariable
  
    @RequestMapping(value = "/foos/{fooid}/bar/{barid}")
@ResponseBody
public String getFoosBySimplePathWithPathVariables(@PathVariable long fooid, @PathVariable long barid) {
return "Get a specific Bar with id=" + barid + " from a Foo with id=" + fooid;
}

通过curl http://localhost:8080/springmvc/foos/1/bar/2测试。


3.3支持正则的@PathVariable 
  
    @RequestMapping(value = "/bars/{numericId:[\\d]+}")
@ResponseBody
public String getBarsBySimplePathWithPathVariable(@PathVariable final long numericId) {
return "Get a specific Bar with id=" + numericId;
}


这个url匹配:http://localhost:8080/springmvc/bars/1
不过这个不匹配:http://localhost:8080/springmvc/bars/abc


4.RequestMapping with Request Parameters


我们可以使用 @RequestParam注解把请求参数提取出来
比如url:http://localhost:8080/springmvc/bars?id=100


@RequestMapping(value = "/bars")
@ResponseBody
public String getBarBySimplePathWithRequestParam(@RequestParam("id") long id) {
return "Get a specific Bar with id=" + id;
}

我们可以通过RequestMapping定义参数列表


@RequestMapping(value = "/bars", params = "id")
@ResponseBody
public String getBarBySimplePathWithExplicitRequestParam(@RequestParam("id") long id) {
return "Get a specific Bar with id=" + id;
}

和


@RequestMapping(value = "/bars", params = { "id", "second" })
@ResponseBody
public String getBarBySimplePathWithExplicitRequestParams(@RequestParam("id") long id) {
return "Narrow Get a specific Bar with id=" + id;
}

比如http://localhost:8080/springmvc/bars?id=100&second=something会匹配到最佳匹配的方法上,这里会映射到下面这个。


5.RequestMapping Corner Cases


5.1 @RequestMapping多个路径映射到同一个controller的同一个方法


@RequestMapping(value = { "/advanced/bars", "/advanced/foos" })
@ResponseBody
public String getFoosOrBarsByPath() {
return "Advanced - Get some Foos or Bars";
}

下面这两个url会匹配到同一个方法


curl -i http://localhost:8080/springmvc/advanced/foos
curl -i http://localhost:8080/springmvc/advanced/bars

5.2@RequestMapping 多个http方法 映射到同一个controller的同一个方法


@RequestMapping(value = "/foos/multiple", method = { RequestMethod.PUT, RequestMethod.POST })
@ResponseBody
public String putAndPostFoos() {
return "Advanced - PUT and POST within single method";
}
下面这两个url都会匹配到上面这个方法


curl -i -X POST http://localhost:8080/springmvc/foos/multiple
curl -i -X PUT http://localhost:8080/springmvc/foos/multiple

5.3@RequestMapping 匹配所有方法


@RequestMapping(value = "*")
@ResponseBody
public String getFallback() {
return "Fallback for GET Requests";
}


匹配所有方法

@RequestMapping(value = "*", method = { RequestMethod.GET, RequestMethod.POST ... })
@ResponseBody
public String allFallback() {
return "Fallback for All Requests";
}

6.Spring Configuration


controller的annotation


@Controller
public class FooController { ... }

spring3.1


@Configuration
@EnableWebMvc
@ComponentScan({ "org.baeldung.spring.web.controller" })
public class MvcConfig {
//
}

可以从这里看到所有的示例https://github.com/eugenp/tutorials/tree/master/springmvc

目录
相关文章
|
XML JSON API
识别这些API接口定义(http,https,api,RPC,webservice,Restful api ,OpenAPI)
本内容介绍了API相关的术语分类,包括传输协议(HTTP/HTTPS)、接口风格(RESTful、WebService、RPC)及开放程度(API、OpenAPI),帮助理解各类API的特点与应用场景。
|
前端开发 Java API
利用 Spring WebFlux 技术打造高效非阻塞 API 的完整开发方案与实践技巧
本文介绍了如何使用Spring WebFlux构建高效、可扩展的非阻塞API,涵盖响应式编程核心概念、技术方案设计及具体实现示例,适用于高并发场景下的API开发。
829 0
|
缓存 安全 API
RESTful与GraphQL:电商API接口设计的技术细节与适用场景
本文对比了RESTful与GraphQL这两种主流电商API接口设计方案。RESTful通过资源与HTTP方法定义操作,简单直观但可能引发过度或欠获取数据问题;GraphQL允许客户端精确指定所需字段,提高灵活性和传输效率,但面临深度查询攻击等安全挑战。从性能、灵活性、安全性及适用场景多维度分析,RESTful适合资源导向场景,GraphQL则适用于复杂数据需求。实际开发中需根据业务特点选择合适方案,或结合两者优势,以优化用户体验与系统性能。
|
人工智能 Java 机器人
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
Spring AI Alibaba集成Ollama,基于Java构建本地大模型应用,支持流式对话、knife4j接口可视化,实现高隐私、免API密钥的离线AI服务。
7679 2
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
|
存储 人工智能 Java
Spring AI与DeepSeek实战四:系统API调用
在AI应用开发中,工具调用是增强大模型能力的核心技术,通过让模型与外部API或工具交互,可实现实时信息检索(如天气查询、新闻获取)、系统操作(如创建任务、发送邮件)等功能;本文结合Spring AI与大模型,演示如何通过Tool Calling实现系统API调用,同时处理多轮对话中的会话记忆。
3133 57
|
JSON 编解码 API
Go语言网络编程:使用 net/http 构建 RESTful API
本章介绍如何使用 Go 语言的 `net/http` 标准库构建 RESTful API。内容涵盖 RESTful API 的基本概念及规范,包括 GET、POST、PUT 和 DELETE 方法的实现。通过定义用户数据结构和模拟数据库,逐步实现获取用户列表、创建用户、更新用户、删除用户的 HTTP 路由处理函数。同时提供辅助函数用于路径参数解析,并展示如何设置路由器启动服务。最后通过 curl 或 Postman 测试接口功能。章节总结了路由分发、JSON 编解码、方法区分、并发安全管理和路径参数解析等关键点,为更复杂需求推荐第三方框架如 Gin、Echo 和 Chi。
|
Java API 网络架构
基于 Spring Boot 框架开发 REST API 接口实践指南
本文详解基于Spring Boot 3.x构建REST API的完整开发流程,涵盖环境搭建、领域建模、响应式编程、安全控制、容器化部署及性能优化等关键环节,助力开发者打造高效稳定的后端服务。
1612 1
|
缓存 Java API
Spring WebFlux 2025 实操指南详解高性能非阻塞 API 开发全流程核心技巧
本指南基于Spring WebFlux 2025最新技术栈,详解如何构建高性能非阻塞API。涵盖环境搭建、响应式数据访问、注解与函数式两种API开发模式、响应式客户端使用、测试方法及性能优化技巧,助你掌握Spring WebFlux全流程开发核心实践。
1763 0
|
缓存 边缘计算 前端开发
从业务需求到技术栈:电商API选型RESTful还是GraphQL?这5个维度帮你决策
在数字经济时代,电商平台的竞争已延伸至用户体验与系统效能。作为连接前后端及各类服务的核心,API接口的架构设计至关重要。本文对比RESTful与GraphQL两大主流方案,从电商场景出发,分析两者的技术特性、适用场景与选型逻辑,帮助开发者根据业务需求做出最优选择。
|
JSON Java API
Spring API 开发简单示例及技巧
目录.png 以用户登录为栗子,示例API请求时处理技巧,和API返回数据时如何处理。 一、API返回时:返回的json数据 使用spring mvc默认配置就可以返回json了,不过需要jackson的jar包APIResponse是一...
1393 0