Define request URL for a controller in Spring MVC

Request URL is a URL that the user will use to access our web application. In this tutorial, we will learn how to define a request URL for a controller in Spring MVC.

Define the request URL

A controller can handle one or more requests with different request URLs. Spring MVC gives us the @RequestMapping annotation to define a request URL.

In the example of the previous tutorial, you see that the HomeController has defined a request URL:

Controller with 1 request URL

If the @RequestMapping annotation with the request URL is defined only above the definition of a class, then this controller handles only one request.

For example:

In this case, if we add another method with the @RequestMapping annotation without the request URL:

then when we run, we get an error immediately:



Controller with multiple request URLs

If the @RequestMapping annotation with the request URL is defined in the methods, the controller can handle many different requests.

The following example of the HomeController class can handle two requests that come from the user including the home page and the login page:

You can also define a method that handles many requests by defining the request URL as follows:



Concatenate request URL

In case where both class and method are declared with the @RequestMapping annotation along with the request URL, then the request URL which used by the user to access a given page must be the request URL of the class plus the method’s request URL.

I have the following example:

In the above example, I have declared the @RequestMapping annotation both on the class (“test”) and method (“home”), the URL request that the user needs to access the home page must be “/test/home”. ”

Result:

Define request URL for a controller in Spring MVC

Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment