Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I override the @RequestMapping on a type for a method?

I have a spring controller/POJO like this:

@RequestMapping("/foo");
public class MyController {
    @RequestMapping("/bar") 
    public String MyAction() { return someSharedFunc(false); }

    @RequestMapping("/debug/ping");
    public String MyDebugPing() { return someSharedFunc(true); }

    private String someSharedFunc(boolean debug) {
      if(debug) return "FooBar"; else return "Debug!";
    }
}

In this scenario, the URL for MyDebugPing is /foo/debug/ping. However, I want it to be /debug/ping, effectively ignoring the RequestMapping on the class.

Is that possible?

like image 267
Michael Stum Avatar asked May 04 '12 01:05

Michael Stum


People also ask

Is @RequestMapping mandatory?

A @RequestMapping on the class level is not required. Without it, all paths are simply absolute, and not relative.

What will happen if handler methods @RequestMapping?

Using @RequestMapping With HTTP Methods 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.

What is the use of @RequestMapping annotation?

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.

What is the difference between the @RequestMapping annotation and @GetMapping annotation?

The @GetMapping annotation assigns specified handler methods to HTTP GET requests. @RequestMapping(method = RequestMethod. GET) is a constructed annotation that serves as a shorthand for @RequestMapping(method = RequestMethod.


1 Answers

Just remove the @RequestMapping annotation from the class and use full paths per individual methods. E.g.

public class MyController {
    @RequestMapping("/foo/bar") 
    public String MyAction() { return someSharedFunc(false); }

    @RequestMapping("/debug/ping");
    public String MyDebugPing() { return someSharedFunc(true); }

    private String someSharedFunc(boolean debug) {
      if(debug) return "FooBar"; else return "Debug!";
    }
}

If there is a lot of methods then you can simply move out the method to another controller.

like image 122
Eugene Retunsky Avatar answered Sep 20 '22 18:09

Eugene Retunsky