1

Given a method like:

@RequestMapping(value = {"/foo"}, method = RequestMethod.GET)
public String getMappingValueInMethod() {
    log.debug("requested "+foo); //how can I make this refer to /foo programmatically?
    return "bar";
}

The use case is for refactoring some lengthly code. I have several GET methods doing roughly the same thing and only the request mapping value is different.

I've looked at using path variables, but this is not really what I want (unless there's some clever use of it that I don't see). I could also get a value from the HttpServletRequest like in this post, but not sure whether there's a better way.

Community
  • 1
  • 1
riddle_me_this
  • 8,575
  • 10
  • 55
  • 80
  • 1
    When you say 'I've looked at using path variables, but this is not really what I want' are you sure. What about ... `@RequestMapping(value = {"/{path}"}, method = RequestMethod.GET) public String getMappingValueInMethod(@PathVariable("path") String path) { log.debug("requested "+path); return "bar"; }` – George Lee Nov 13 '15 at 16:53
  • Please go into detail about your use case. – Sotirios Delimanolis Nov 13 '15 at 16:55

2 Answers2

1

Solution 1

With HttpServletRequest.

@RequestMapping(value = "/foo", method = RequestMethod.GET)
public String fooMethod(HttpServletRequest request) {
    String path = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();
    System.out.println("path foo: " + path);
    return "bar";
}

Solution 2

With reflection.

@RequestMapping(value = "/foo2", method = RequestMethod.GET)
public String fooMethod2() {
    try {
        Method m = YourClassController.class.getMethod("fooMethod2");
        String path = m.getAnnotation(RequestMapping.class).value()[0];
        System.out.println("foo2 path: " + path);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }

    return "bar";
}

If you want get path from class (instead method) you can use:

String path = YourClassController.class.getAnnotation(RequestMapping.class).value();

Solution 3

With @PathVariable.

 @RequestMapping(value = {"/{foo3}"}, method = RequestMethod.GET)
    public @ResponseBody String fooMethod3(@PathVariable("foo3") String path) {
        path = "/" + path; // if you need "/"
        System.out.println("foo3 path: " + path);
        return "bar";
    }
Community
  • 1
  • 1
mkczyk
  • 2,460
  • 2
  • 25
  • 40
0

The simplest way of doing this would be putting the array directly in the request mapping i am assuming this is what you want.

    @RequestMapping(value = {"/foo","/foo1","/foo2"}, method = RequestMethod.GET)
public String getMappingValueInMethod(HttpServletRequest request) {
    log.debug("requested "+request.getRequestURI()); 
    return request.getRequestURI();
}

Then name the jsp files similar to the uri or other wise you could store the mapping between the request uri and the name of the page in the db .

Robert Ellis
  • 714
  • 6
  • 19