0

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

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

3 回答 3

2

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

    //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());
        }
    }
于 2016-03-16T09:07:41.030 回答
0

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

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

或者如果这是在 Spring 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);
}
于 2016-03-16T08:52:51.670 回答
0
@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";   
}  

也许你可以称之为它的价值。

于 2016-03-16T09:00:22.980 回答