Chip Zhang
Chip Zhang

Reputation: 651

SpringMVC: how to get the value of @RequestMapping in the function

I have a class as follows:

@Controller
@RequestMapping("/path1")
public class MyController
{
    @RequestMapping(value = "/path2", method = RequestMethod.GET)
    public ModelAndView func(ModelAndView mav)
    {
        String path = getRequestMappingValue(); // Here I expect a function which returns "/path1/path2"
        mav.setViewName(path  + ".jsp");
        return mav;
    }
}

What I require is the function getRequestMappingValue(), which returns the value of annotation @RequestMapping (in this case, it is "/path1/path2")

Upvotes: 3

Views: 3712

Answers (2)

John Deverall
John Deverall

Reputation: 6280

Doesn't this solution here achieve pretty much what you're looking for?

private final static String MAPPING = "/hello";

@RequestMapping(value = MAPPING)
@ResponseBody
public void helloMethod(AtmosphereResource atmosphereResource) {
   // MAPPING accessible as it's stored in instance variable
}

Upvotes: 0

Brian Clozel
Brian Clozel

Reputation: 59086

The whole point of MVC is mapping requests like /user/brian to Controller methods that perform actions (like showUser(Model model)) and return views. Trying to guess the view name based on some value in the request seems like a code smell to me.

Maybe you could explain a bit more your use case?

I wouldn't personally rely on this (I think this is not an advertised feature of the framework), but you can get the path within the current handler mapping like this:

@Controller
@RequestMapping("/path1")
public class MyController {

    @RequestMapping(value = "/path2")
    public String myAction(Model model, HttpServletRequest request) {

        String path = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        // do something
        return "viewName";
    }
}

Please also refer to the javadoc:

 Note: This attribute is not required to be supported by all HandlerMapping implementations. 
 URL-based HandlerMappings will typically support it, but handlers should not necessarily expect 
 this request attribute to be present in all scenarios.

Upvotes: 0

Related Questions