SpringMVC:如何在函数中获取@RequestMapping的值

时间:2015-01-14 01:13:55

标签: java spring jsp servlets model-view-controller

我有一个课程如下:

@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;
    }
}

我需要的是函数getRequestMappingValue(),它返回注释@RequestMapping的值(在这种情况下,它是" / path1 / path2")

2 个答案:

答案 0 :(得分:0)

MVC的重点是将/user/brian之类的请求映射到执行操作(如showUser(Model model))和返回视图的Controller方法。试图根据请求中的某个值猜测视图名称,这对我来说似乎是一种代码味道。

也许你可以解释一下你的用例?

我个人不会依赖于此(我认为这不是框架的广告功能),但您可以在当前处理程序映射中获取如下路径:

@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";
    }
}

请同时参考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.

答案 1 :(得分:0)

这个解决方案here几乎没有达到您所寻找的目标吗?

private final static String MAPPING = "/hello";

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