Spring Framework Guru
Using the spring @requestmapping annotation.
@RequestMapping is one of the most common annotation used in Spring Web applications. This annotation maps HTTP requests to handler methods of MVC and REST controllers.
In this post, you’ll see how versatile the @RequestMapping annotation is when used to map Spring MVC controller methods.
Request Mapping Basics
In Spring MVC applications, the RequestDispatcher (Front Controller Below) servlet is responsible for routing incoming HTTP requests to handler methods of controllers.
When configuring Spring MVC, you need to specify the mappings between the requests and handler methods.
The @RequestMapping annotation can be applied to class-level and/or method-level in a controller.
The class-level annotation maps a specific request path or pattern onto a controller. You can then apply additional method-level annotations to make mappings more specific to handler methods.
Here is an example of the @RequestMapping annotation applied to both class and methods.
With the preceding code, requests to /home will be handled by get() while request to /home/index will be handled by index() .
@RequestMapping with Multiple URIs
You can have multiple request mappings for a method. For that add one @RequestMapping annotation with a list of values.
As you can see in this code, @RequestMapping supports wildcards and ant-style paths. For the preceding code, all these URLs will be handled by indexMultipleMapping() .
- localhost:8080/home
- localhost:8080/home/
- localhost:8080/home/page
- localhost:8080/home/pageabc
- localhost:8080/home/view/
- localhost:8080/home/view/view
@RequestMapping with @RequestParam
The @RequestParam annotation is used with @RequestMapping to bind a web request parameter to the parameter of the handler method.
The @RequestParam annotation can be used with or without a value. The value specifies the request param that needs to be mapped to the handler method parameter, as shown in this code snippet.
In Line 6 of this code, the request param id will be mapped to the personId parameter personId of the getIdByValue() handler method.
An example URL is this: localhost:8090/home/id?id=5
The value element of @RequestParam can be omitted if the request param and handler method parameter names are same, as shown in Line 11.
An example URL is this: localhost:8090/home/personId?personId=5
The required element of @RequestParam defines whether the parameter value is required or not.
In this code snippet, as the required element is specified as false , the getName() handler method will be called for both of these URLs:
- /home/name?person=xyz
The default value of the @RequestParam is used to provide a default value when the request param is not provided or is empty.
In this code, if the person request param is empty in a request, the getName() handler method will receive the default value John as its parameter.
Using @RequestMapping with HTTP Method
The Spring MVC @RequestMapping annotation is capable of handling HTTP request methods, such as GET, PUT, POST, DELETE, and PATCH.
By default all requests are assumed to be of HTTP GET type.
In order to define a request mapping with a specific HTTP method, you need to declare the HTTP method in @RequestMapping using the method element as follows.
In the code snippet above, the method element of the @RequestMapping annotations indicates the HTTP method type of the HTTP request.
All the handler methods will handle requests coming to the same URL ( /home ), but will depend on the HTTP method being used.
For example, a POST request to /home will be handled by the post() method. While a DELETE request to /home will be handled by the delete() method.
You can see how Spring MVC will map the other methods using this same logic.
Using @RequestMapping with Producible and Consumable
The request mapping types can be narrowed down using the produces and consumes elements of the @RequestMapping annotation.
In order to produce the object in the requested media type, you use the produces element of @RequestMapping in combination with the @ResponseBody annotation.
You can also consume the object with the requested media type using the consumes element of @RequestMapping in combination with the @RequestBody annotation.
The code to use producible and consumable with @RequestMapping is this.
In this code, the getProduces() handler method produces a JSON response. The getConsumes() handler method consumes JSON as well as XML present in requests.
@RequestMapping with Headers
The @RequestMapping annotation provides a header element to narrow down the request mapping based on headers present in the request.
You can specify the header element as myHeader = myValue .
In the above code snippet, the headers attribute of the @RequestMapping annotation narrows down the mapping to the post() method. With this, the post() method will handle requests to /home/head whose content-type header specifies plain text as the value.
You can also indicate multiple header values like this:
Here it implies that both text/plain as well as text/html are accepted by the post() handler method.
@RequestMapping with Request Parameters
The params element of the @RequestMapping annotation further helps to narrow down request mapping. Using the params element, you can have multiple handler methods handling requests to the same URL, but with different parameters.
You can define params as myParams = myValue . You can also use the negation operator to specify that a particular parameter value is not supported in the request.
In this code snippet, both the getParams() and getParamsDifferent() methods will handle requests coming to the same URL ( /home/fetch ) but will execute depending on the params element.
For example, when the URL is /home/fetch?id=10 the getParams() handler method will be executed with the id value 10 .. For the URL, localhost:8080/home/fetch?personId=20 , the getParamsDifferent() handler method gets executed with the id value 20 .
Using @RequestMapping with Dynamic URIs
The @RequestMapping annotation is used in combination with the @PathVaraible annotation to handle dynamic URIs. In this use case, the URI values can act as the parameter of the handler methods in the controller. You can also use regular expressions to only accept the dynamic URI values that match the regular expression.
In this code, the method getDynamicUriValue() will execute for a request to localhost:8080/home/fetch/10 . Also, the id parameter of the getDynamicUriValue() handler method will be populated with the value 10 dynamically.
The method getDynamicUriValueRegex() will execute for a request to localhost:8080/home/fetch/category/shirt . However, an exception will be thrown for a request to /home/fetch/10/shirt as it does not match the regular expression.
@PathVariable works differently from @RequestParam . You use @RequestParam to obtain the values of the query parameters from the URI. On the other hand, you use @PathVariable to obtain the parameter values from the URI template.
The @RequestMapping Default Handler Method
In the controller class you can have default handler method that gets executed when there is a request for a default URI.
Here is an example of a default handler method.
In this code, A request to /home will be handled by the default() method as the annotation does not specify any value.
@RequestMapping Shortcuts
Spring 4.3 introduced method-level variants, also known as composed annotations of @RequestMapping . The composed annotations better express the semantics of the annotated methods. They act as wrapper to @RequestMapping and have become the standard ways of defining the endpoints.
For example, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET) . The method level variants are:
- @GetMapping
- @PostMapping
- @PutMapping
- @DeleteMapping
- @PatchMapping
The following code shows using the composed annotations.
In this code, each of the handler methods are annotated with the composed variants of @RequestMapping . Although, each variant can be interchangeably used with @RequestMapping with the method attribute, it’s considered a best practice to use the composed variant. Primarily because the composed annotations reduce the configuration metadata on the application side and the code is more readable.
@RequestMapping Conclusion
As you can see in this post, the @RequestMapping annotation is very versatile. You can use this annotation to configure Spring MVC to handle a variety of use cases. It can be used to configure traditional web page requests, and well as RESTFul web services in Spring MVC.
You May Also Like
JWT Token Authentication in Spring Boot Microservices
Hikari Configuration for MySQL in Spring Boot 2
Database Migration with Flyway
Getting Ready for Spring Framework 6
Using Filters in Spring Web Applications
Bootstrapping Data in Spring Boot
Eureka Service Registry
Scheduling in Spring Boot
Spring for Apache Kafka
Spring retry.
Spring Boot CLI
Actuator in Spring Boot
Internationalization with Spring Boot
One-to-one relationship in jpa.
The @RequestBody Annotation
Spring BeanFactory vs ApplicationContext
MySQL Stored Procedures with Spring Boot
Bean Validation in Spring Boot
Spring state machine.
Exception Handling in Spring Boot REST API
Spring Boot Pagination
Spring rest docs, using mapstruct with project lombok, argumentcaptor in mockito.
Reading External Configuration Properties in Spring
Api gateway with spring cloud.
Testing Spring Boot RESTful Services
Caching in Spring RESTful Service: Part 2 – Cache Eviction
Spring boot messaging with rabbitmq.
Caching in Spring Boot RESTful Service: Part 1
Implementing HTTP Basic Authentication in a Spring Boot REST API
Immutable Property Binding
Java Bean Properties Binding
External configuration data in spring.
Spring Data JPA @Query
Configuring mysql with circleci.
Fabric8 Docker Maven Plugin
Feign REST Client for Spring Application
Docker Hub for Spring Boot
Consul miniseries: spring boot application and consul integration part 3, run spring boot on docker, consul miniseries: spring boot application and consul integration part 2.
Consul Miniseries: Spring Boot Application and Consul Integration Part 1
Why You Should be Using Spring Boot Docker Layers
Spring Bean Scopes
Debug your code in intellij idea, stay at home, learn from home with 6 free online courses.
What is the best UI to Use with Spring Boot?
Best Practices for Dependency Injection with Spring
Should I Use Spring REST Docs or OpenAPI?
Spring boot with lombok: part 1.
Using Project Lombok with Gradle
Spring bean lifecycle, spring profiles, spring bean definition inheritance, autowiring in spring.
What is New in Spring Boot 2.2?
Using Ehcache 3 in Spring Boot
How to configure multiple data sources in a spring boot application.
Using RestTemplate with Apaches HttpClient
Using RestTemplate in Spring
Working with resources in spring, using spring aware interfaces, service locator pattern in spring, using graphql in a spring boot application, spring jdbctemplate crud operations, contracts for microservices with openapi and spring cloud contract, using swagger request validator to validate spring cloud contracts, spring 5 webclient, defining spring cloud contracts in open api.
Hibernate Show SQL
Spring Component Scan
Using CircleCI to Build Spring Boot Microservices
Spring framework annotations.
Using JdbcTemplate with Spring Boot and Thymeleaf
Spring Data MongoDB with Reactive MongoDB
Spring Boot with Embedded MongoDB
Spring Web Reactive
What are Reactive Streams in Java?
What’s new in Spring Framework 5?
Spring Boot RESTful API Documentation with Swagger 2
Mockito Mock vs Spy in Spring Boot Tests
Spring Boot Mongo DB Example Application
Configuring Spring Boot for MariaDB
Spring boot web application, part 6 – spring security with dao authentication provider.
Configuring Spring Boot for MongoDB
Spring Boot Web Application, Part 5 – Spring Security
Chuck Norris for Spring Boot Actuator
Testing spring mvc with spring boot 1.4: part 1, running spring boot in a docker container.
Jackson Dependency Issue in Spring Boot with Maven Build
Using YAML in Spring Boot to Configure Logback
Using Logback with Spring Boot
Using Log4J 2 with Spring Boot
Fixing nouniquebeandefinitionexception exceptions, samy is my hero and hacking the magic of spring boot.
2015 Year in Review
Configuring Spring Boot for PostgreSQL
Embedded JPA Entities Under Spring Boot and Hibernate Naming
Spring Boot Developer Tools
Spring beanfactoryaware interface.
Spring BeanNameAware Interface
Displaying list of objects in table using thymeleaf.
Using H2 and Oracle with Spring Boot
Configuring Spring Boot for Oracle
Spring Boot Web Application – Part 4 – Spring MVC
Configuring Spring Boot for MySQL
Spring Boot Example of Spring Integration and ActiveMQ
How do i become a java web developer.
Spring Boot Web Application – Part 3 – Spring Data JPA
Spring Boot Web Application – Part 2 – Using ThymeLeaf
Spring Boot Web Application – Part 1 – Spring Initializr
Using the H2 Database Console in Spring Boot with Spring Security
Running code on spring boot startup, integration testing with spring and junit.
Polyglot Programming in Spring
Using Spring Integration Futures
Using the spring framework for enterprise application development.
Testing Spring Integration Gateways
Introduction to Spring Expression Language (SpEL)
Hello World Using Spring Integration
Creating Spring Beans
Dependency Injection Example Using Spring
Hello World With Spring 4
Getting started with spring boot.
What’s all the fuss about Java Lambdas?
17 comments on “ using the spring @requestmapping annotation ”.
is this correct? @PathVariable works differently from @RequestParam. You use @PathVariable to obtain the values of the query parameters from the URI. On the other hand, you use @RequestParam to obtain the parameter values from the URI template.
I thought query parameters are those params after the ‘?’ in the URI, (?queryParam=value&queryParam2=value2). So you use @RequestParam. And the URI template is of the form /fetch/{id}, so you use @PathVariable to obtain the param values. Did I misunderstood the statement above?
Ximanta Sarma
That’s correct. @RequestParm is used for query parameters (that follows ‘?’) in URL, whereas @PathVariable for {placeholder} values that can keep dynamically changing in URL.
Yunus Emre Incu
hi thanx for your share. But i have a quest. What about the “dispatcher-servlet.xml” and “web.xml”… can you show me your xml files. Thanx.
These are no longer required.
Hi, Thanks for the useful blog. I have a requirement to create multiple instance of RestController with different dao, service instance properties. I’m working on to convert Jersey rest code to spring boot rest. I have sample code of Jersey implementation in stackoverflow. Please let me know if you could comment on this.
https://stackoverflow.com/questions/46876938/how-to-create-multiple-instances-of-restcontroller-in-spring-boot-application
Thanks in advance.
Nice summary. The only thing missing to make it a little better would be to show that handling of Objects both as input (in a POST for example) and as a response. Of course this would probably end up Jackson or some other OJM/OXM discussion.
Why would one add @ResponseBody annotation in a class annotated with @RestController? @RestController itself contains @ResponseBody…
Is it possible to specify a list of request parameters in a request mapping?
I have the following mapping: @PostMapping(value = “/test/url”, params = { “id={10, 20}” })
Yet when I submit the following request: http://localhost:8080/test/url?id=10&id=20
I get the following error: ServletRequestParameterException: Parameter conditions “id={10, 20}” not met for actual request parameters: id={10, 20}
Correction: The “method” value of @RequestMapping defaults to an empty array — it does NOT default to the GET method. So, one should always be explicit, to avoid possibly nondeterministic behavior if multiple annotations can apply to the same request URL.
See https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html#method–
Lana Rohdes
Java is the brandd and most powerful programmic language ever. It’s features like cross platform supported is one of the most powerful fetures, AEM is also a java based technology, So have a look. aem architecture
You are using @Produces=”application/json” and returning a simple string. i just want to know how spring can process this without returning a json convertible object.
Leave a Reply Cancel Reply
Your email address will not be published. Required fields are marked *
Save my name, email, and website in this browser for the next time I comment.
This site uses Akismet to reduce spam. Learn how your comment data is processed .
- PyQt5 ebook
- Tkinter ebook
- SQLite Python
- wxPython ebook
- Windows API ebook
- Java Swing ebook
- Java games ebook
- MySQL Java ebook
Spring @RequestMapping
last modified October 18, 2023
In this article we show how to use @RequestMapping annotation in a classic Spring web application. The annotation is used for mapping web requests onto handler methods in request-handling classes.
Spring is a popular Java application framework for creating enterprise applications.
@RequestMapping
@RequestMapping is used for mapping web requests onto handler methods in request-handling classes. The process of mapping web requests to handler methods is also called routing.
@RequestMapping has the following specializations:
- @GetMapping
- @PostMapping
- @PutMapping
- @DeleteMapping
- @PatchMapping
The annotation can be used both at the class and at the method level. If used on both levels, the request paths are combined.
Spring @RequestMapping example
In the following example, we demonstrate the usage of the @RequestMapping annotation.
This is the project structure.
In the pom.xml we have the project dependencies.
This is the logback.xml configuration
This is a home page.
MyWebInitializer initializes the Spring web application. It contains one configuration class: WebConfig .
The WebConfig configures the Spring web application.
MyController various route definitions with @RequestMapping .
With value option, we map the / request path to the home handler method. If not expplicitly specified, the default request method is GET. The value is an alias to the path option.
With the method option, we can narrow the handler mapping to POST requests having the /about path.
This method can accept both GET and POST requests.
With the consumes option we can narrow down the mapping to the requests with defined content type.
With the params option we narrow down the mapping to the GET requests with /time path and info=time request parameter.
TestController has additional two mappings.
We can place @RequestMapping on class, too. The path is then combined with the method paths.
This handler is mapped to the /test/info path.
The path option is equivalent to the value . It can accept Ant-style URL mappings.
We run the Jetty server.
We generate a GET request to the home page with curl tool.
This is a POST request to the /about path.
The /fresh page accepts both GET and POST requests.
We send a request with a parameter to the /time page.
The class-level and method-level annotations are combined into the /test/info path.
Finally, the ant-style mapping.
In this article we have created created various routes with @RequestMapping annotation.
My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.
List all Spring tutorials .
Spring Annotations: @RequestMapping and its Variants
- Introduction
If you've read anything about Spring , developed a project, or was even remotely interested in how it works, you've been introduced to the @RequestMapping annotation.
It's one of the basic annotations in Spring which maps HTTP requests (URLs) with methods:
It allows us to run methods and pieces of code each time an endpoint is hit by the end-user with an HTTP request. In this case, it's a simple root mapping that returns the String "Hello World!" when the root endpoint is hit.
- The @RequestMapping Annotation
The @RequestMapping annotation itself offers more than shown in the previous example. Let's briefly cover some of the basic use cases of the annotation.
- @RequestMapping Scopes
The mapping can be assigned at a class level or a method level:
Here, the /admin mapping is assigned on the class level, whereas the /adminPanel and /statistics mappings are assigned to methods. The class-level mapping will be used as a prefix for all of these method-level mappings: /admin/adminPanel and /admin/statistics .
This way, we can segregate our application into logical parts. For an example, all administrator related logic will be behind the /admin wall, which only administrator users can enter. All non-administrator users will be redirected to the client side of the application.
- Multiple Mappings per Method
If need be, we can assign multiple mappings to a single method, such as:
Hitting any of these endpoints will result in the helloWorld() method handling our request.
- Request Methods
The most common attribute used is the method attribute which allows us to specify and narrow down the request method that our method handles ( GET , POST , DELETE , etc.) :
If we don't specify a request method, the default request method is GET .
- Request Headers
We can further specify the mapping by defining one or more headers. In this case, the helloWorld() method will handle the request if its content-type is text/plain or text/html :
- Path Variables
A lot of websites rely on path variables to showcase a specific product, page, profile, etc. to the end-user, such as example.com/viewProduct/324 , where 324 is the product ID:
Here, after the mapping, we encase the path variable with curly brackets ( {} ) and assign that value to our productId . The @PathVariable annotation takes care of this for us. Then, we can find the product via our ProductService and display it to the end-user.
Of course, the same approach can be used for other variables such as:
- Request Parameters
Very similar to path variables, many applications rely on request parameters to alter the state of the page. We can use the @RequestParam annotation to bind a request parameter to a variable:
- Producible and Consumable
Using the @RequestMapping annotation, we can also produce or consume media types. To produce a media type such as "JSON", you can use the produces attribute alongside the @ResponseBody annotation, whereas to consume a media type you can use the consumes attribute:
- Composed @RequestMapping Variants
A single mapping can correspond to different methods if we ensure there's no ambiguity as to which method should handle which version of the mapping.
We can have multiple methods with the same mapping if their request method is different:
This same method has 4 different variations:
- Default (GET)
With more variations, the readability of code gets reduced, and this quite honestly is already verbose for a simple mapping. Request mappings in bigger applications can get very complex and convoluted, and we'd want to keep it simpler and more readable.
For this purpose, we're introduced to several new annotations, the @RequestMapping variants:
- @GetMapping
- @PostMapping
- @DeleteMapping
- @PutMapping
- @PatchMapping
There are quite literally just shortcut versions for the mappings above where @PostMapping("/hello") is equal to @RequestMapping(value="/hello", RequestMethod.POST) .
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Taking a closer look at how these annotations are defined, we can get a clear idea of what they do:
That being said, we can rewrite the examples above:
As this is both a simpler, more readable and newer way of writing annotations, it's generally preferred to write them like this. If need be, you can still define any other attributes such as the value , params , path , etc.
@RequestMapping is a quintessential annotation in the Spring framework which allows us to map HTTP requests with methods we'd wish to run.
As of Spring 4.3, it's preferred and advised to use the shortcuts made for this annotation for a more readable and less verbose codebase.
You might also like...
- Prevent Cross-Site Scripting (XSS) in Spring Boot with Content-Security Policies (CSPs)
- Spring Boot with Redis: HashOperations CRUD Functionality
- Spring Cloud: Hystrix
- Guide to Unit Testing Spring Boot REST APIs
- @Controller and @RestController Annotations in Spring Boot
Improve your dev skills!
Get tutorials, guides, and dev jobs in your inbox.
No spam ever. Unsubscribe at any time. Read our Privacy Policy.
Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.
Great passion for accessible education and promotion of reason, science, humanism, and progress.
In this article
Make clarity from data - quickly learn data visualization with python.
Learn the landscape of Data Visualization tools in Python - work with Seaborn , Plotly , and Bokeh , and excel in Matplotlib !
From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.
© 2013- 2024 Stack Abuse. All rights reserved.
- Manage Email Subscriptions
- How to Post to DZone
- Article Submission Guidelines
- Manage My Drafts
Read about DevOps trends including supply chain management, platform engineering, deployment automation, and CI/CD pipeline observability.
Programming in Python. Dive into the Python ecosystem to learn about popular libraries, tools, modules, and more.
Getting Started With Large Language Models : A guide for both novices and seasoned practitioners to unlock the power of language models.
DZone Research Report : A look at our developer audience, their tech stacks, and topics and tools they're exploring.
- Custom Annotations To Validate Input Requests in Spring Boot - Part I
- Mastering Spring: Synchronizing @Transactional and @Async Annotations With Various Propagation Strategies
- Composing Custom Annotations in Spring
- Spring Boot: Cross-Origin AJAX HTTP Requests
- Foreign Function and Memory API: Modernizing Native Interfacing in Java 17
- Essential Relational Database Structures and SQL Tuning Techniques
- Code Complexity in Practice
- Advancements and Capabilities in Modern Mainframe Architecture
Using the Spring @RequestMapping Annotation
As often as springs @requestmapping annotation is, few recognize its versatility. here, we see that on display when used to map spring mvc controller methods..
Join the DZone community and get the full member experience.
@RequestMapping is one of the most common annotation used in Spring Web applications. This annotation maps HTTP requests to handler methods of MVC and REST controllers.
In this post, you’ll see how versatile the @RequestMapping annotation is when used to map Spring MVC controller methods.
Request Mapping Basics
In Spring MVC applications, the RequestDispatcher (Front Controller Below) servlet is responsible for routing incoming HTTP requests to handler methods of controllers.
When configuring Spring MVC, you need to specify the mappings between the requests and handler methods.
The @RequestMapping annotation can be applied to class-level and/or method-level in a controller.
The class-level annotation maps a specific request path or pattern onto a controller. You can then apply additional method-level annotations to make mappings more specific to handler methods.
Here is an example of the @RequestMapping annotation applied to both class and methods.
With the preceding code, requests to /home will be handled by get() while request to /home/index will be handled by index().
@RequestMapping With Multiple URIs
You can have multiple request mappings for a method. For that add one @RequestMapping annotation with a list of values.
As you can see in this code, @RequestMapping supports wildcards and ant-style paths. For the preceding code, all these URLs will be handled by indexMultipleMapping().
- localhost:8080/home
- localhost:8080/home/
- localhost:8080/home/page
- localhost:8080/home/pageabc
- localhost:8080/home/view/
- localhost:8080/home/view/view
@RequestMapping With @RequestParam
The @RequestParam annotation is used with @RequestMapping to bind a web request parameter to the parameter of the handler method.
The @RequestParam annotation can be used with or without a value. The value specifies the request param that needs to be mapped to the handler method parameter, as shown in this code snippet.
In Line 6 of this code, the request param id will be mapped to the personId parameter personId of thegetIdByValue() handler method.
The value element of @RequestParam can be omitted if the request param and handler method parameter names are same, as shown in Line 11.
The required element of @RequestParam defines whether the parameter value is required or not.
In this code snippet, as the required element is specified as false, the getName() handler method will be called for both of these URLs:
- /home/name?person=xyz
The default value of the @RequestParam is used to provide a default value when the request param is not provided or is empty.
In this code, if the person request param is empty in a request, the getName() handler method will receive the default value John as its parameter.
Using @RequestMapping With HTTP Methods
The Spring MVC @RequestMapping annotation is capable of handling HTTP request methods, such as GET, PUT, POST, DELETE, and PATCH.
By default, all requests are assumed to be of HTTP GET type.
In order to define a request mapping with a specific HTTP method, you need to declare the HTTP method in@RequestMapping using the method element as follows.
In the code snippet above, the method element of the @RequestMapping annotations indicates the HTTP method type of the HTTP request.
All the handler methods will handle requests coming to the same URL ( /home), but will depend on the HTTP method being used.
For example, a POST request to /home will be handled by the post() method. While a DELETE request to/home will be handled by the delete() method.
You can see how Spring MVC will map the other methods using this same logic.
Using @RequestMapping With Producible and Consumable
The request mapping types can be narrowed down using the produces and consumes elements of the@RequestMapping annotation.
In order to produce the object in the requested media type, you use the produces element of @RequestMapping in combination with the @ResponseBody annotation.
You can also consume the object with the requested media type using the consumes element of@RequestMapping in combination with the @RequestBody annotation.
The code to use producible and consumable with @RequestMapping is this.
In this code, the getProduces() handler method produces a JSON response. The getConsumes() handler method consumes JSON as well as XML present in requests.
@RequestMapping With Headers
The @RequestMapping annotation provides a header element to narrow down the request mapping based on headers present in the request.
You can specify the header element as myHeader = myValue.
In the above code snippet, the headers attribute of the @RequestMapping annotation narrows down the mapping to the post() method. With this, the post() method will handle requests to /home/head whose content-typeheader specifies plain text as the value.
You can also indicate multiple header values like this:
Here it implies that both text/plain as well as text/html are accepted by the post() handler method.
@RequestMapping With Request Parameters
The params element of the @RequestMapping annotation further helps to narrow down request mapping. Using the params element, you can have multiple handler methods handling requests to the same URL, but with different parameters.
You can define params as myParams = myValue. You can also use the negation operator to specify that a particular parameter value is not supported in the request.
In this code snippet, both the getParams() and getParamsDifferent() methods will handle requests coming to the same URL (/home/fetch) but will execute depending on the params element.
For example, when the URL is /home/fetch?id=10, the getParams() handler method will be executed with the id value 10.. For the URL, localhost:8080/home/fetch?personId=20, the getParamsDifferent() handler method gets executed with the id value 20.
Using @RequestMapping With Dynamic URIs
The @RequestMapping annotation is used in combination with the @PathVaraible annotation to handle dynamic URIs. In this use case, the URI values can act as the parameter of the handler methods in the controller. You can also use regular expressions to only accept the dynamic URI values that match the regular expression.
In this code, the method getDynamicUriValue() will execute for a request to localhost:8080/home/fetch/10. Also, the id parameter of the getDynamicUriValue() handler method will be populated with the value 10 dynamically.
The method getDynamicUriValueRegex() will execute for a request to localhost:8080/home/fetch/category/shirt. However, an exception will be thrown for a request to /home/fetch/10/shirt as it does not match the regular expression.
@PathVariable works differently from @RequestParam. You use @PathVariable to obtain the values of the query parameters from the URI. On the other hand, you use @RequestParam to obtain the parameter values from the URI template.
The @RequestMapping Default Handler Method
In the controller class, you can have default handler method that gets executed when there is a request for a default URI.
Here is an example of a default handler method.
In this code, a request to /home will be handled by the default() method as the annotation does not specify any value.
@RequestMapping Shortcuts
Spring 4.3 introduced method-level variants, also known as composed annotations of @RequestMapping. The composed annotations better express the semantics of the annotated methods. They act as wrapper to@RequestMapping and have become the standard ways of defining the endpoints.
For example, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method =RequestMethod.GET). The method level variants are:
- @GetMapping
- @PostMapping
- @PutMapping
- @DeleteMapping
- @PatchMapping
The following code shows using the composed annotations.
In this code, each of the handler methods are annotated with the composed variants of @RequestMapping. Although each variant can be interchangeably used with @RequestMapping with the method attribute, it’s considered a best practice to use the composed variant —primarily because the composed annotations reduce the configuration metadata on the application side and the code is more readable.
@RequestMapping Conclusion
As you can see in this post, the @RequestMapping annotation is very versatile. You can use this annotation to configure Spring MVC to handle a variety of use cases. It can be used to configure traditional web page requests as well as RESTFul web services in Spring MVC.
Published at DZone with permission of John Thompson , DZone MVB . See the original article here.
Opinions expressed by DZone contributors are their own.
Partner Resources
- About DZone
- Send feedback
- Advertise with DZone
CONTRIBUTE ON DZONE
- Become a Contributor
- Core Program
- Visit the Writers' Zone
- Terms of Service
- Privacy Policy
- 3343 Perimeter Hill Drive
- Nashville, TN 37211
- [email protected]
Let's be friends:
- Java Tutorial
- Java Spring
- Spring Interview Questions
- Java SpringBoot
- Spring Boot Interview Questions
- Spring MVC Interview Questions
- Java Hibernate
- Hibernate Interview Questions
- Advance Java Projects
- Java Interview Questions
- Solve Coding Problems
- Spring Boot - Flyway Database
- Spring Boot - @ConfigurationProperties
- Creating Spring Boot Project Using STS
- Spring Boot - Versioning a REST API
- Spring Boot - Cloud Configuration Server
- Integrating Apache HttpClient in Spring Boot
- Spring Boot – REST API Documentation using Swagger
- YAML to List of Objects in Spring Boot
- JSTL fn:replace() Function
- Request Body and Parameter Validation with Spring Boot
- Spring Boot - Customize Whitelabel Error Page
- Spring Boot - Admin Server
- SpringBoot Configuration
- Testing in Spring Boot
- Spring Boot - Sending SMS with Twilio
- Spring Boot API Call using OkHttp
- Spring Boot Ecosystem
- Spring Boot - How to set a Request Timeout for a REST API
- private vs private-final injection of dependency
Spring Boot – @Requestmapping
Spring Boot is the most popular framework of Java for building enterprise-level web applications and back-ends. Spring Boot has a handful of features that support quicker and more efficient web app development. Some of them are Auto-configuration, Embedded Server, opinionated defaults, and Annotation Support. In this article, we’ll be exploring the core annotation of Spring Boot – @RequestMapping which is part of the set of annotations that Spring Boot employs for defining URL endpoints and REST APIs.
@RequestMapping
This annotation is a versatile and flexible annotation that can be used with a controller (class) as well as the methods to map specific web requests with the handler methods and controllers. This annotation is part of a larger set of annotations provided by Spring Framework to define URL endpoints and simplify the development of Spring Boot applications.
It has the following features:
- Define several different endpoints to access a specific resource.
- Build REST APIs to serve web requests.
- Simplify the web development process by simply defining an annotation that offers a set of functionalities for handling requests.
- Define multiple endpoints in a single @RequestMapping annotation.
Step-By-Step Implementation of @RequestMapping annotation
For this article, we’ll be using the following tools:
- Java 8 or higher
- Java IDE like Eclipse, IntelliJ, and VS code (We’ll be using IntelliJ)
- POSTMAN for testing Request Mappings
- Dependency: Spring Web Starter
Step-1: Create a starter file and extract it
Go to Spring Initializr and create a starter file having a single dependency – Spring Web. Download and extract it into your local folder and open it in your favorite IDE.
pom.xml File:
Step-2: define a controller.
- Create a new package for containing all the controllers that we will be adding in our application under the src/main/java/package_name/Controllers
- Add a new TestController inside Controllers Package for defining Request Mappings. Your final directory structure would look something like this :
Step-4: Define URL Templates inside the controller
Annotate the Controller with @Controller to signify that this class is a controller that has some URL templates defined inside it and @RequestMapping on the controller as well as the methods to specify which URL path will give what output.
Below is the code Implementation of Controller:
Explanation of the above program:.
We’ve defined multiple end points using @RequestMapping which can be accessed at following URLs :
- http://localhost:8080/test/hello
- http://localhost:8080/test/sport
- http://localhost:8080/test/today/tasks
Annotations used:
- @Controller : This annotation implicitly marks the class as a component making it eligible for component scanning while signifying that this class invokes business logic, handles incoming web requests and returns customized responses.
- @ResponseBody : This annotation is used on both class level as well as on method level to indicate that the return value generated by this class or method doesn’t need to be resolved to a view page like HTML or JSP, rather it should be directly serialized into HTTP response body. And this serialization from Java Object to JSON is done by a technology called – Jackson Project that performs Jackson Data Binding under the hood.
Our request method can return any type of data – POJOs (Plain Old Java Objects) and this data will be serialized into JSON by the Jackson Project.
Note: @ResponseBody can be ignored if you’re using @RestController instead of @Controller.
Outputs for every endpoint on POSTMAN:
Endpoint – 1: http://localhost:8080/test/hello, endpoint – 2: http://localhost:8080/test/sport.
Endpoint – 3: http://localhost:8080/test/today/tasks
Notice that we’re selecting the type of request as GET in our POSTMAN this is because all of our methods are only returning some data, not making any changes in a database (as we’re not connected to any database).
And to be more specific, the actual use of @RequestMapping is to define the start of URL and the request handler method will perform some operation and depending on the type of operation a method performs, we will annotate it with GET, PUT, POST or DELETE. Let’s look at some of the most commonly used type of annotation we can use with a specific web request in brief:
- @GetMapping: This annotation is associated with the requests that are requesting a resource without making any changes in the database.
- @PostMapping: This annotation is associated with the requests that are trying to add new data in the database. Ex: Adding a new student record that contains all the information regarding a student like student_id, name, enrollment_number, branch etc.
- @PutMapping: This annotation is associated with the update requests that wants to update or change some already existing data in our database.
- @DeleteMapping: This annotation is associated with deleting persistent objects (already existing data) from our database.
In conclusion, @RequestMapping is a core annotation for defining a controller and mapping web requests to their appropriate methods. It is a core MVC Annotations defined for defining the controller and URL path, it is very crucial to understand the working and different variations of this annotation as a Java Developer you’ll be using it very frequently.
- It maps certain web requests to their specific controller and methods.
- We will have multiple controllers in our application, then each controller’s URL pattern will be different to identify and map web requests to an appropriate controller. For Example, we can have a controller for performing database operation, another controller for Throwing Exceptions, another for logging, monitoring etc. Each of the controller’s request mapping will have a unique URL Pattern
- @RequestMapping can also be used to take query parameters from the URL. For example, we need a student with a specific ID. So, we can define a mapping like this – https://localhost:8080/student/{id}. The {id} is a dynamic parameter whose input can vary depending on the requests. Curly braces around it indicates that the input in this part of URL will vary.
- Although @RequestMapping can be annotated on top of Methods as well, it’s more efficient and readable to use a specific type of mapping annotation like @GET, @PUT, @POST etc.
Please Login to comment...
- Geeks Premier League 2023
- Java-Spring-Boot
- Advance Java
- Geeks Premier League
- What is Bland Turbo and How to Use This Conversational AI?
- What is Perchance AI and How to Use This Text-to-Image AI Tool?
- Fintech startup CredAble scores $10 Mn in new round
- Google Gemini Advanced vs ChatGPT Plus: Which AI assistant is best for you?
- Dev Scripter 2024 - Biggest Technical Writing Event By GeeksforGeeks
IMAGES
VIDEO
COMMENTS
It should be possible to use placeholders in @RequestMapping, like for example @RequestMapping("${foo.bar}").Take a look at the documentation for more details:. Patterns in @RequestMapping annotations support ${… } placeholders against local properties and/or system properties and environment variables.This may be useful in cases where the path a controller is mapped to may need to be ...
The @RequestMapping annotation can be applied to class-level and/or method-level in a controller. The class-level annotation maps a specific request path or pattern onto a controller. You can then apply additional method-level annotations to make mappings more specific to handler methods. Here is an example of the @RequestMapping annotation ...
I am getting below error: The annotation @ApiResponses is disallowed for this location We are using swagger2.2.0 @RestController @RequestMapping(value = "/example") @ApiResponses(value = { @ApiRe...
In this tutorial, we'll focus on one of the main annotations in Spring MVC: @RequestMapping. Simply put, the annotation is used to map web requests to Spring Controller methods. Further reading: Serve Static Resources with Spring . How to map and handle static resources with Spring MVC - use the simple configuration, then the 3.1 more ...
@RequestMapping cannot be used in conjunction with other @RequestMapping annotations that are declared on the same element (class, interface, or method). If multiple @RequestMapping annotations are detected on the same element, a warning will be logged, and only the first mapping will be used. This also applies to composed @RequestMapping annotations such as @GetMapping, @PostMapping, etc.
org.springframework.web.bind.annotation.RequestMapping annotation is used to map web requests onto specific handler classes and/or handler methods. @RequestMapping can be applied to the controller class as well as methods. Today we will look into various usage of this annotation with example and other annotations @PathVariable and @RequestParam.
This also applies to composed @RequestMapping annotations such as @GetMapping, @PostMapping, etc. NOTE: When using controller interfaces (e.g. for AOP proxying), make sure to consistently put all your mapping annotations — such as @RequestMapping and @SessionAttributes — on the controller interface rather than on the implementation class.
Spring @RequestMapping. In this article we show how to use @RequestMapping annotation in a classic Spring web application. The annotation is used for mapping web requests onto handler methods in request-handling classes. Spring is a popular Java application framework for creating enterprise applications.
Conclusion. @RequestMapping is a quintessential annotation in the Spring framework which allows us to map HTTP requests with methods we'd wish to run. As of Spring 4.3, it's preferred and advised to use the shortcuts made for this annotation for a more readable and less verbose codebase. # java # spring.
All of the above annotations are already internally annotated with @RequestMapping and the respective value in the method element.. For example, if we'll look at the source code of @GetMapping annotation, we can see that it's already annotated with RequestMethod.GET in the following way: @Target({ java.lang.annotation.ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented ...
The @RequestMapping annotation can be applied to class-level and/or method-level in a controller. The class-level annotation maps a specific request path or pattern onto a controller. You can then apply additional method-level annotations to make mappings more specific to handler methods. So let's understand @RequestMapping Annotation at ...
The @RequestMapping annotation is used to map requests to controllers methods. It has various attributes to match by URL, HTTP method, request parameters, headers, and media types. You can use it at the class level to express shared mappings or at the method level to narrow down to a specific endpoint mapping.
The headers of the mapped request, narrowing the primary mapping. Same format for any environment: a sequence of "My-Header=myValue" style expressions, with a request only mapped if each such header is found to have the given value. Expressions can be negated by using the "!=" operator, as in "My-Header!=myValue".
The @RequestMapping annotation is a versatile tool. See it used to configure traditional web page requests as well as RESTFul web services in Spring MVC.
In spring mvc hello world application, we saw a very basic employee management application with end to end functionality (excluding any db access). In next step to learn spring mvc module, I am giving some examples of @RequestMapping annotation to show that how you can use @RequestMapping to map URLs to controller methods in different ways. I am again using the same code base as in spring mvc ...
Spring Boot - @Requestmapping. Spring Boot is the most popular framework of Java for building enterprise-level web applications and back-ends. Spring Boot has a handful of features that support quicker and more efficient web app development. Some of them are Auto-configuration, Embedded Server, opinionated defaults, and Annotation Support.
The annotation @Query is disallowed for this location. Then it means that you're using an annotation somewhere it's not meant for. If an annotation only allows you to put it on top of a method, you'll get this exception when you put it on top of your class, or on top of a property.
public @interface RequestMapping. Annotation for mapping web requests onto specific handler classes and/or handler methods. Provides a consistent style between Servlet and Portlet environments, with the semantics adapting to the concrete environment. NOTE: The set of features supported for Servlets is a superset of the set of features supported ...
I have controller method that has @Valid annotation to enforce JSR303 Bean validation. But when I just give @Valid is shows" This annotation @Valid is disallowed for this location I can get rid of this by giving full package path @javax.validation.Valid. It does not show the above message if I use this.