Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/kubernetes/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java SpringMVC:如何在函数中获取@RequestMapping的值_Java_Spring_Jsp_Servlets_Model View Controller - Fatal编程技术网

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

Java SpringMVC:如何在函数中获取@RequestMapping的值,java,spring,jsp,servlets,model-view-controller,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

我的课程如下:

@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(),它返回annotation@RequestMapping的值(在本例中为“/path1/path2”)

MVC的整个要点是将请求(如
/user/brian
映射到执行操作(如
showUser(Model)
)和返回视图的控制器方法。在我看来,试图根据请求中的某个值猜测视图名称似乎是一种代码味道

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

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

@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";
    }
}
另请参阅:

这个解决方案不正是你想要的吗

private final static String MAPPING = "/hello";

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

一种方法是reflection@JigarJoshi你能详细解释一下吗?我是Java和SpringMVC的新手,没有理由这么做。如果在
something/path1/
中有一个名为
path2.JSP
的JSP,只需在
setViewName
中编写它即可。不要让它依赖于其他元数据。我同意Sotirios的观点,但如果你真的想这样做,一个更简单的方法是提取一个字符串常量,并让@RequestMapping路径和视图名称都使用该常量。@JigarJoshi这个问题是另一个问题的重复,但这个问题并没有任何答案能够明确回答这个问题。OP,如果您更清楚地解释您的用例,这将是有帮助的;您所说想要的(
/path1/path2
)不是注释值。
private final static String MAPPING = "/hello";

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