HttpServletRequest - 获取文字路径

时间:2015-09-17 21:12:15

标签: spring-mvc servlets

我有一个标有Spring @RequestMapping的方法,其中包含HttpServletRequest方法参数。

如果我在路径是“request.getServletPath()”时打印出“/things/{thingId}”的调用结果,我会得到“/things/2489sdfjk43298f”,其中{{thingId} 1}} path参数已替换为实际值。

我想打印出文字请求路径“/things/{thingId}”;即使用花括号,未替换的路径参数“{thingId}。”

这有可能吗?

编辑:在看完Sotirios下面的第二条评论后,我意识到我可能会向后看问题。这就是我实际上要做的......

我正在尝试在“/**”下创建一个端点,该端点从HttpServletRequest获取路径,我用它来查找enum中的值。这个enum有几个字段,其中一个显然是前面提到的路径,另一个是目标JSP文件的路径。然后我将此路径放入ModelAndView对象并返回以显示页面。

在我用路径参数命中第一个端点之前,这很好,因为我显然无法将值“/things/2489sdfjk43298f”放入枚举中,因为那只会匹配那个特定的{{ 1}}有一个特定的ID。

所以也许实际的问题是:当路径的某些部分由于路径参数而改变时,我该如何查找?我可以使用某种含通配符的thing格式吗?

我想这会变成更多的String - 查找/ enum匹配问题。我的坏。

编辑2:我正在谈论的String事情的简短示例:

enum

我的终点的简短示例:

public enum JspEndpointType {
  HOME("/home", "jsp/home");

  private static final Map<String, String> pathMap;
  private String requestPath;
  private String jspPath;

  static {
    pathMap = new HashMap<>();
    for (JspEndpointType jspEndpointType : JspEndpointType.values()) {
      pathMap.put(jspEndpointType.getRequestPath(), jspEndpointType.getJspPath());
    }
  }

  private JspEndpointValue(String requestPath, String jspPath) {
    this.requestPath = requestPath;
    this.jspPath = jspPath;
  }

  public String getRequestPath() {
    return requestPath;
  }

  public String getJspPath() {
    return jspPath;
  }

  public static String getByRequestPath(String requestPath) {
    return pathMap.get(requestPath);
  }
}

所以事情基本上归结为尝试添加@RequestMapping(value = "/**", method = RequestMethod.GET) public ModelAndView showPage(HttpServletRequest request) { return new ModelAndView(JspEndpointType.getByRequestPath(request.getServletPath())); } 这样的值:

enum

..然后能够传递路径“THINGS("/things/{thingId}", "jsp/things/whatever") ”并返回“/things/2489sdfjk43298f。”

编辑3:我找到了this StackoverFlow question,它指示我使用Spring的UriComponentsBuilder,特别是“/jsp/things/whatever”方法。然而,这似乎与我正在尝试做的相反......

1 个答案:

答案 0 :(得分:0)

您可以使用反射自行查找@RequestMapping注释。

相关问题