【问题标题】:How to programmatically read the path of a rest service?如何以编程方式读取休息服务的路径?
【发布时间】:2016-03-16 08:46:07
【问题描述】:

假设我定义了以下简单的休息:

@RequestMapping("/user/data")
@ResponseBody
public String getUserDetails(@RequestParam int id) {
    ...
}

有没有办法通过代码的另一部分(即完全从不同的方法)读取路径字符串? 比如:

String restPath = SomeReflection.getPath("getuserdetails"); // received value: "/user/data"

WDYT? 谢谢!

解决了! 这是我需要的实现:

public String getUrlFromRestMethod(Class controllerClass, String methodName) {

        try {
            Method method = controllerClass.getMethod(methodName);
            if (method != null && method.isAnnotationPresent(RequestMapping.class)) {

                RequestMapping requestMappingAnnotation = method.getAnnotation(RequestMapping.class);
                return requestMappingAnnotation.toString();
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();//TODO
        }

        return null;
    }

【问题讨论】:

    标签: java rest path restful-url request-mapping


    【解决方案1】:

    如果您的意思是即使从另一个类也想以编程方式访问该值,那么也许您可以从这个示例开始制定您的解决方案:

        //get all methods defined in ClassA
        Method[] methods = ClassA.class.getMethods();
        for (Method m : methods) {
            //pick only the ones annotated with "@RequestMapping"
            if (m.isAnnotationPresent(RequestMapping.class)) {
                RequestMapping ta = m.getAnnotation(RequestMapping.class);
                System.out.println(ta.value()[0].toString());
            }
        }
    

    【讨论】:

      【解决方案2】:

      我建议你在你的方法中添加一个 HttpServletRequest 请求,然后从那里去 request.getServletPath()

      ei

      public String getUserDetails(HttpServletRequest request, @RequestParam int id) {
      

      或者如果这是在春季完成http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-requestmapping

      @RequestMapping(path = "/{day}", method = RequestMethod.GET)
      public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
          return appointmentBook.getAppointmentsForDay(day);
      }
      

      【讨论】:

      • 我应该指定 - 我正在寻找从外部类\方法到达路径
      【解决方案3】:
      @RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)  
      public String findOwner(@PathVariable String ownerId, Model model) {  
        Owner owner = ownerService.findOwner(ownerId);    
        model.addAttribute("owner", owner);    
        return "displayOwner";   
      }  
      

      也许你可以调用它的值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-26
        • 2011-06-24
        • 1970-01-01
        • 2016-08-26
        • 1970-01-01
        • 2013-10-25
        • 2016-09-14
        • 1970-01-01
        相关资源
        最近更新 更多