Multiple Request Mappings in Spring Boot

How can we define multiple request mappings for a single method?

In this tutorial, we are taking a look at a student’s question from my Spring Boot Introduction Course. The question was related to building out Spring Controllers and how to define multiple request mappings for a single method.

Request Mappings

“How can I create multiple request mappings for a single method?”

Multiple Request Mappings

If you want to follow along with this tutorial you can create a simple Spring Boot project that includes the Web dependency. We know that we can use the @RequestMapping annotation to map web requests onto specific handler classes and/or handler methods. If we wanted to map our home method to the root “/” we can do so using the following code. 

If you fire up this application and visit http://localhost:8080/ you will see the string “Hello, World!” returned to the browser. What happens if you wanted to define 2 or more web requests to be handled by the same method? It turns out you can only use one annotation per method, so something like this will not work. 

If we look at the Request Mapping class value will take an array of strings and defaults to an empty array.

So we can pass in an array of strings that represent web requests. 

Now if visit http://localhost:8080/ or http://localhost:8080/home  we should see the string “Hello, World!” printed to the browser window. 

Multiple Request Mappings Screencast

Conclusion

There are some things that might not be apparent but as we saw in this tutorial we can quickly drill into the code and find a solution. This is one of the many reasons open source is so great.

Question: Do you face any problems setting up request mappings? 

Hi, I’m Dan Vega. I am a Software Engineer living just outside of one of my favorite places in the world, Cleveland, Ohio. I am a self-taught programmer who firmly believes that you can accomplish anything in this life if you put your mind to it, roll up your sleeves and are willing to put in the work.

I have been writing software for over 18+ years now and I use my knowledge, passion, and influence to help other developers achieve their goals. I teach online and currently, have over 30,000 students.

When I am not writing software, I have a number of things that really keep me busy. I love to read books, listen to podcasts and watch online courses. I have a real thirst for knowledge and it consumes me every single day of the week. I also love to run & lift heavy weights which keep me balanced throughout the week.

Please note: I reserve the right to delete comments that are offensive or off-topic.