`
denyx123
  • 浏览: 43023 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Spring RequestMapping

 
阅读更多
1. Overview

In this article, we will discuss one of the main annotations in Spring MVC – the @RequestMapping – this is used to map web requests to Spring Controller methods.

Throughout the article, we will test each of the mappings showed via simple curl commands.

2. RequestMapping Basic Example

Let’s start with a simple example – mapping an HTTP request to a method using some straightforward criteria.

2.1. @RequestMapping – by Path

?
1
2
3
4
5
@RequestMapping(value = "/foos")
@ResponseBody
public String getFoosBySimplePath() {
    return "Get some Foos";
}
To test out this mapping with a simple curl command, run:

?
1
curl -i http://localhost:8080/spring-rest/foos
2.2. @RequestMapping – the HTTP Method

By default, the HTTP method mapped by a @RequestMapping is GET – this can of course be changed – for example to map to a POST request:

?
1
2
3
4
5
@RequestMapping(value = "/foos", method = RequestMethod.POST)
@ResponseBody
public String postFoos() {
    return "Post some Foos";
}
To test the POST via a curl comamnd:

?
1
curl i -X POST http://localhost:8080/spring-rest/foos
3. RequestMapping and HTTP Headers

3.1. @RequestMapping with the headers attribute

The mapping can be narrowed even further by specifying a header for the request:

?
1
2
3
4
5
@RequestMapping(value = "/foos", headers = "key=val")
@ResponseBody
public String getFoosWithHeader() {
    return "Get some Foos with Header";
}
And even multiple headers via the header attribute of @RequestMapping:

?
1
2
3
4
5
@RequestMapping(value = "/foos", headers = { "key1=val1", "key2=val2" })
@ResponseBody
public String getFoosWithHeaders() {
    return "Get some Foos with Header";
}
To test the operation, we’re going to use the curl header support:

?
1
curl -i -H "key:val" http://localhost:8080/spring-rest/foos
Note that for the curl syntax for separating the header key and the header value is a colon, same as in the HTTP spec, while in Spring the equals sign is used.

3.2. @RequestMapping Consumes and Produces

Mapping media types produced by a controller method is worth special attention – we can map a request based on its Accept header via the @RequestMapping headers attribute introduced above:

?
1
2
3
4
5
@RequestMapping(value = "/foos", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public String getFoosAsJsonFromBrowser() {
    return "Get some Foos with Header Old";
}
The matching for this way of defining the Accept header is flexible – it uses contains instead of equals, so a request such as the following would still map correctly:

?
1
curl -H "Accept:application/json,text/html" http://localhost:8080/spring-rest/foos
Starting with Spring 3.1, a the @RequestMapping annotation now has a produces and a consumes attributes, specifically for this purpose:

?
1
2
3
4
5
@RequestMapping(value = "/foos", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public String getFoosAsJsonFromREST() {
    return "Get some Foos with Header New";
}
Also, the old type of mapping with the headers attribute will automatically be converted to the new produces mechanism starting with Spring 3.1, so the results will be identical.

This is consumed via curl in the same way:

?
1
curl -H "Accept:application/json" http://localhost:8080/spring-rest/foos
Additionally, produces support multiple values as well:

?
1
@RequestMapping(value = "/foos", produces = { "application/json", "application/xml" })
Keep in mind that these are basically the same mapping, so Spring won’t accept them together – having both these methods active would result in:

?
1
2
3
4
5
6
7
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.
A final note on the new produces and consumes mechanism – these behave differently from most other annotations: when specified at type level, the method level annotations do not complement but override the type level information.

4. RequestMapping with Path Variables

Parts of the mapping URI can be bound to variables via the @PathVariable annotation.

4.1. Single @PathVariable

A simple example with a single path variable:

?
1
2
3
4
5
@RequestMapping(value = "/foos/{id}")
@ResponseBody
public String getFoosBySimplePathWithPathVariable(@PathVariable("id") long id) {
   return "Get a specific Foo with id=" + id;
}
This can be tested with curl:

?
1
curl http://localhost:8080/spring-rest/foos/1
If the name of the method argument matches the name of the path variable exactly, then this can be simplified by using @PathVariable with no value:

?
1
2
3
4
5
@RequestMapping(value = "/foos/{id}")
@ResponseBody
public String getFoosBySimplePathWithPathVariable(@PathVariable String id) {
   return "Get a specific Foo with id=" + id;
}
Note that @PathVariable benefits from automatic type conversion, so we could have also declared the id as:

?
1
@PathVariable long id
4.2. Multiple @PathVariable

More complex URI may need to map multiple parts of the URI to multiple values:

?
1
2
3
4
5
@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;
}
This is easily tested with curl in the same way:

?
1
curl http://localhost:8080/spring-rest/foos/1/bar/2
4.3. @PathVariable with RegEx

Regular expressions can also be used when mapping the @PathVariable; for example, we will restrict the mapping to only accept numerical values for the id:

?
1
2
3
4
5
@RequestMapping(value = "/bars/{numericId:[\\d]+}")
@ResponseBody
public String getBarsBySimplePathWithPathVariable(@PathVariable final long numericId) {
    return "Get a specific Bar with id=" + numericId;
}
This will mean that the following URIs will match:

?
1
http://localhost:8080/spring-rest/bars/1
But this will not:

?
1
http://localhost:8080/spring-rest/bars/abc
5. RequestMapping with Request Parameters

@RequestMapping allows easy mapping of URL parameters with the @RequestParam annotation.

We are now mapping a request to an URI such as:

?
1
http://localhost:8080/spring-rest/bars?id=100
?
1
2
3
4
5
@RequestMapping(value = "/bars")
@ResponseBody
public String getBarBySimplePathWithRequestParam(@RequestParam("id") long id) {
    return "Get a specific Bar with id=" + id;
}
We are then extracting the value of the id parameter using the @RequestParam(“id”) annotation in the controller method signature.

The send a request with the id parameter, we’ll use the parameter support in curl:

?
1
curl -i -X POST id=100 http://localhost:8080/spring-rest/bars
In this example, the parameter was bound directly without having been declared first.

For more advanced scenarios, @RequestMapping can explicitly define the parameters to be mapped as yet another way of narrowing the request mapping:

?
1
2
3
4
5
@RequestMapping(value = "/bars", params = "id")
@ResponseBody
public String getBarBySimplePathWithExplicitRequestParam(@RequestParam("id") long id) {
    return "Get a specific Bar with id=" + id;
}
Even more flexible mappings are allowed – multiple params values can be defined, and not all of them have to be used:

?
1
2
3
4
5
@RequestMapping(value = "/bars", params = { "id", "second" })
@ResponseBody
public String getBarBySimplePathWithExplicitRequestParams(@RequestParam("id") long id) {
    return "Narrow Get a specific Bar with id=" + id;
}
And of course, a request to an URI such as:

?
1
http://localhost:8080/spring-rest/bars?id=100&second=something
Will always be mapped to the best match – which is the narrower match, which defines both the id and the second parameter.

6. RequestMapping Corner Cases

6.1. @RequestMapping – multiple paths mapped to the same controller method

Although a single @RequestMapping path value is usually used for a single controller method, this is just good practice, not a hard and fast rule – there are some cases where mapping multiple requests to the same method may be necessary. For that case, the value attribute of @RequestMapping does accept multiple mappings, not just a single one:

?
1
2
3
4
5
@RequestMapping(value = { "/advanced/bars", "/advanced/foos" })
@ResponseBody
public String getFoosOrBarsByPath() {
    return "Advanced - Get some Foos or Bars";
}
Now, both of these curl commands should hit the same method:

?
1
2
curl -i http://localhost:8080/spring-rest/advanced/foos
curl -i http://localhost:8080/spring-rest/advanced/bars
6.2. @RequestMapping – multiple HTTP request methods to the same controller method

Multiple requests using different HTTP verbs can be mapped to the same controller method:

?
1
2
3
4
5
@RequestMapping(value = "/foos/multiple", method = { RequestMethod.PUT, RequestMethod.POST })
@ResponseBody
public String putAndPostFoos() {
    return "Advanced - PUT and POST within single method";
}
With curl, both of these will now hit the same method:

?
1
2
curl -i -X POST http://localhost:8080/spring-rest/foos/multiple
curl -i -X PUT http://localhost:8080/spring-rest/foos/multiple
6.3. @RequestMapping – a fallback for all requests

To implement a simple fallback for all requests using a specific HTTP method:

?
1
2
3
4
5
@RequestMapping(value = "*")
@ResponseBody
public String getFallback() {
    return "Fallback for GET Requests";
}
Or even for all request:

?
1
2
3
4
5
@RequestMapping(value = "*", method = { RequestMethod.GET, RequestMethod.POST ... })
@ResponseBody
public String allFallback() {
    return "Fallback for All Requests";
}
7. Spring Configuration

The Spring MVC Configuration is simple enough – considering that our FooController is defined in the following package:

?
1
2
3
4
package org.baeldung.spring.web.controller;

@Controller
public class FooController { ... }
Starting with Spring 3.1, we will only need a @Configuration class to enable the full MVC support and configure classpath scanning for the controller:

?
1
2
3
4
5
6
@Configuration
@EnableWebMvc
@ComponentScan({ "org.baeldung.spring.web.controller" })
public class MvcConfig {
    //
}
8. Conclusion

This article focus on the @RequestMapping annotation in Spring 3 - discussing a simple usecase, the mapping of HTTP headers, binding parts of the URI with @PathVariable and working with URI parameters and the @RequestParam annotation.

The implementation of this simple project can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is.
分享到:
评论

相关推荐

    Spring MVC--2.@RequestMapping 映射请求

    在Spring MVC框架中,`@RequestMapping`注解是核心组件之一,它用于处理HTTP请求映射,使得控制器类(Controller)中的方法能够与特定的URL路径关联起来。本篇文章将深入探讨`@RequestMapping`的使用、功能以及相关...

    Spring MVC之@RequestMapping详解

    《Spring MVC之@RequestMapping详解》 在Java Web开发中,Spring MVC框架因其强大的功能和灵活性而备受青睐。在处理HTTP请求时,@RequestMapping注解扮演着至关重要的角色,它负责将客户端的请求映射到控制器中的...

    Spring 实现远程访问详解——httpclient

    说得简单就是直接通过spring requestmapping即请求映射url访问远程服务。 1. 远程访问流程 1) 服务器在控制器定义远程访问请求映射路径 2) 客户端通过apache httpclient的 httppost方式访问远程服务 2. Httpclient...

    详解获取Spring MVC中所有RequestMapping以及对应方法和参数

    "详解获取Spring MVC中所有RequestMapping以及对应方法和参数" Spring MVC是一个基于模型-视图-控制器(MVC)模式的Web应用程序框架, RequestMapping是一个重要的注解,它可以将HTTP请求映射到控制器的方法上。在...

    Spring mvc中 RequestMapping 6个基本用法小结

    Spring MVC 中的 RequestMapping 6个基本用法小结 Spring MVC 是一个基于 Java 的 Web 应用程序框架,提供了强大的 RequestMapping 机制来处理 HTTP 请求。在 Spring MVC 中,RequestMapping 是一个核心组件,负责...

    spring-mvc-params:Spring RequestHandler方法参数注入

    春天的MVC参数Spring RequestMapping方法参数注入。描述该项目提供了两个注释:AutowiredParam和ResourceParam 这些可用于将Spring上下文Bean“注入”到方法参数中。 Spring已经为许多类型的方法参数提供了注入,...

    springmvc之@RequestMapping的demo

    通过这个简单的`springmvc_helloworld`示例,你可以了解`@RequestMapping`注解的基本用法,以及如何在Spring MVC框架下构建一个基本的Web应用。随着对Spring MVC的深入学习,你会发现更多高级特性,如拦截器、异常...

    SpringMVC@RequestMapping(重点)@RequestParam@PathVariable示例

    在Spring MVC框架中,`@RequestMapping`、`@RequestParam`和`@PathVariable`是三个非常重要的注解,它们用于处理HTTP请求并绑定请求参数到控制器方法的参数上。接下来,我们将详细探讨这三个注解的工作原理以及如何...

    SpringMybatis项目基于@RequestMapping和RequstAttribute实现登录注册

    在SpringMybatis项目中,利用`@RequestMapping`和`RequestAttribute`实现登录注册功能是Web开发中的常见实践。`@RequestMapping`是Spring MVC框架中用于处理HTTP请求映射的注解,而`RequestAttribute`则用于在请求...

    java8集合源码-tips:尖端

    RequestMapping 使用使用示例 编程闯关、完成挑战 设计模式 图片 图形化代码生成器 秒杀分析 排错工具 垃圾回收 log 权限框架比较 cron-utils time String 生产.java源代码 ,可以用来构建一些基础的代码,必须一些...

    java8集合源码-tips:小贴士

    RequestMapping 使用使用示例 编程闯关、完成挑战 设计模式 图片 图形化代码生成器 秒杀分析 排错工具 垃圾回收 log 权限框架比较 cron-utils time String 生产.java源代码 ,可以用来构建一些基础的代码,比如一些...

    简化版@requestmapping注解注册源码

    在Spring MVC框架中,`@RequestMapping`注解是核心组件之一,它用于处理HTTP请求映射,使得控制器类或方法能够与特定的URL路径关联。本文将深入解析`@RequestMapping`的工作原理,并介绍一个简化版的自定义实现,...

    springmvc关于@requestMapping和@requestParam的使用

    在Spring MVC框架中,`@RequestMapping` 和 `@RequestParam` 是两个非常重要的注解,它们在处理HTTP请求和参数绑定方面起着核心作用。本文将深入探讨这两个注解的使用和功能。 `@RequestMapping` 是Spring MVC用于...

    Spring MVC之@RequestMapping注解详解

    Spring MVC的@RequestMapping注解是核心的控制器层注解,它用于映射HTTP请求到特定的处理方法。在本文中,我们将深入探讨这个注解的各个方面,包括它的使用场景、属性以及如何结合其他注解实现更复杂的请求处理。 ...

    框架Spring的Controller注解和RequestMapping注解 在MVC应用注意事项

    SpringMVC不能只使用@Controller而不使用@RequestMapping

    spring-web-5.2.3.RELEASE和spring-webmvc-5.2.3.RELEASE

    比如,@RequestMapping注解可以用来映射URL到特定的方法,@GetMapping和@PostMapping等用于处理HTTP的GET和POST请求。@RequestParam用于获取请求参数,而模型数据可以通过@ModelAttribute注解传递给视图。视图通常由...

    spring4.0框架demo

    5. RESTful支持:Spring MVC 4.0加强了对RESTful风格的支持,通过@RequestMapping注解可以轻松创建REST服务。 四、实战Demo解析 在名为“springmvc4”的Demo项目中,我们可以通过以下步骤来理解Spring 4.0与Maven...

    Springmvc中 RequestMapping 属性用法归纳.docx

    在Spring MVC框架中,`@RequestMapping`注解是核心组件之一,它负责将HTTP请求映射到控制器类的处理方法。这个注解可以应用于类级别和方法级别,以定义请求的URL路径、HTTP方法以及其他的匹配条件。接下来,我们将...

    spring3.0mvc自学教程ppt+注解教程+注解实例+springmybatis教程+项目实例+中文api (老师的心血)从入门到项目实战

    2. **注解教程**:Spring 3.0引入了大量的注解,如`@Controller`、`@RequestMapping`、`@Service`、`@Autowired`等,大大减少了XML配置文件的需求。`@Controller`用于标记控制层类,`@RequestMapping`用于映射HTTP...

Global site tag (gtag.js) - Google Analytics