Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get requested value(URL) when using @RequestMapping annotations

When I map multiple values to @RequestMapping(like Multiple Spring @RequestMapping annotations), can I get the requested value(URL)?

Like this:

@RequestMapping(value={"/center", "/left"}, method=RequestMethod.GET)
public String getCenter(Model model) throws Exception {     
    String requestedValue = getRequestedValue();  // I want this.

    // I want to do something like this with requested value.
    String result; 
    if (requestedValue.equals("center")
        result = "center";
    else if (requestedValue.equals("left")
        result = "left";
    return result;
}
like image 335
Sanghyun Lee Avatar asked Sep 29 '11 05:09

Sanghyun Lee


People also ask

Which of the following annotations will help us to read the value from the request URL?

We can use @RequestMapping with @RequestParam annotation to retrieve the URL parameter and map it to the method argument.

What is the @RequestMapping annotation used for?

One of the most important annotations in spring is the @RequestMapping Annotation which is used to map HTTP requests to handler methods of MVC and REST controllers. In Spring MVC applications, the DispatcherServlet (Front Controller) is responsible for routing incoming HTTP requests to handler methods of controllers.

Which annotation is used to handle GET request?

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.

Which of these can be the return type of a method annotated with @RequestMapping in spring?

A Callable can be returned when the application wants to produce the return value asynchronously in a thread managed by Spring MVC. A DeferredResult can be returned when the application wants to produce the return value from a thread of its own choosing.


1 Answers

You can have the Request (HttpServletRequest) itself as an parameter of the handler method. So you can then inspect the request url to get the "value".

@RequestMapping(value={"/center", "/left"}, method=RequestMethod.GET)
public String getCenter(Model model, HttpServletRequest request) throws Exception {             
   String whatYouCallValue = request.getServletPath(); 
   ....

Javadoc: https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html#getServletPath--

Btw: if I understand you right, you want to have different urls, not different values.

like image 90
Ralph Avatar answered Sep 25 '22 00:09

Ralph