【问题标题】:@RequestMapping annotation in Spring MVCSpring MVC 中的 @RequestMapping 注解
【发布时间】:2012-01-25 05:48:57
【问题描述】:

我有一个请求映射为@RequestMapping("/**") 的控制器 什么意思?

如果我想从上述映射中排除某些 url 模式,我该怎么做?

有人能解释一下吗?

【问题讨论】:

  • 另外请告诉我 url 模式如何与 @RequestMapping 一起使用。谢谢。

标签: spring-mvc request-mapping


【解决方案1】:

通过使用正则表达式“负前瞻”构造,我能够实现“url 排除”或“不匹配 url”。

我希望我的处理程序处理静态资源以外的所有内容,即 CSS/Images/JS 和错误页面。

为了防止错误页面的处理,即resourceNotFound,您需要

  1. 编辑 web.xml /web-app/error-page 以在错误 URL 前加上 /error/
  2. 编辑 WEB-INF/spring/webmvc-config.xml /beans/mvc:view-controller/@path 处理您的新映射
  3. 编辑 WEB-INF/spring/webmvc-config.xml /beans/bean[@class=**SimpleMappingExceptionResolver] 以将所有异常映射到错误/...

在你的控制器中使用下面的

@Controller
@RequestMapping(value = { "/" })
public class CmsFrontendController {

  @RequestMapping(value = { "/" }, headers = "Accept=text/html")
  public String index(Model ui) {
      return addMenu(ui, "/");
  }

  @RequestMapping(value = { "{path:(?!resources|error).*$}", "{path:(?!resources|error).*$}/**" }, headers = "Accept=text/html")
  public String index(Model ui, @PathVariable(value = "path")String path) {
      try {
          path = (String) request.getAttribute(
                  HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
          return addMenu(ui, path);
      } catch (Exception e) {
          log.error("Failed to render the page. {}", StackTraceUtil.getStackTrace(e));
          return "error/general";
      }
  }
}

【讨论】:

  • 必须有比这更易于维护的解决方案...?男人。
  • 谢谢!这很好用!一直在寻找一种执行排除的方法
  • 我唯一的问题是使用 thymeleaf 时 404 不起作用。我收到 org.thymeleaf.exceptions.TemplateInputException: An error occurred during template parsing.
【解决方案2】:

您的网址将拦截所有匹配“/**”的请求。根据您定义的位置,我不确定您为什么要这样做。在类级别,这应该定义基本路径,而在方法级别,它应该细化为特定的功能。

如果您想排除一个模式,您可以定义另一个控制器,该控制器的优先级高于指定 '/**' 的控制器

这里有 2 个来自 spring 源的很好的参考:

  1. http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html

  2. http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html

【讨论】:

  • /** 和 /* 有什么区别。我认为 /* 也会涵盖 /** 我是否正确?
  • @ChaitanyaMSV /* 将只覆盖 url 的第一部分假设 localhost:8080/hello 只有在你提供 localhost:8080/hello/user 时才会覆盖,你会看到一个错误页面。另一方面 /** 涵盖了 url 的所有部分
猜你喜欢
  • 1970-01-01
  • 2014-07-11
  • 2017-05-15
  • 1970-01-01
  • 2018-11-02
  • 1970-01-01
  • 2014-11-20
  • 1970-01-01
  • 2021-10-24
相关资源
最近更新 更多