【问题标题】:SpringMVC: how to get the value of @RequestMapping in the functionSpringMVC:如何在函数中获取@RequestMapping的值
【发布时间】:2023-03-30 04:41:02
【问题描述】:

我有一堂课如下:

@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”)

【问题讨论】:

  • 一种方法是反射
  • @JigarJoshi 你能详细解释一下吗?我是 Java 和 SpringMVC 的新手。
  • 没有充分的理由这样做。如果您在something/path1/ 中有一个名为path2.jsp 的JSP,只需将其写入setViewName。不要让它依赖于其他一些元数据。
  • 我同意 Sotirios,但如果您真的想这样做,更简单的方法是提取一个字符串常量并让 @RequestMapping 路径和视图名称都使用该常量。
  • @JigarJoshi 该问题与另一个问题重复,但该问题没有任何似乎专门回答这个问题的答案。 OP,如果您更清楚地解释您的用例会很有帮助;你说你想要的(/path1/path2)不是注释值。

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


【解决方案1】:

MVC 的重点是将/user/brian 之类的请求映射到执行操作(例如showUser(Model 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";
    }
}

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

【讨论】:

    【解决方案2】:

    这个解决方案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
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-24
      • 2015-02-10
      • 2011-04-17
      • 1970-01-01
      • 2018-12-27
      • 1970-01-01
      • 2016-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多