简体   繁体   中英

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")

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM