【问题标题】:Unable to exclude URL's in the servlet mapping in Spring MVC无法在 Spring MVC 的 servlet 映射中排除 URL
【发布时间】:2016-10-05 11:40:19
【问题描述】:

我在 Spring MVC 3.2 中有一个控制器,我想允许以下网址: http://localhost:8080/mypage http://localhost:8080/mypage/ http://localhost:8080/mypage/foo

我想排除任何其他内容,即http://localhost:8080/mypage/bar 应该会导致错误。目前 bar 被映射到 getStuff 方法。

我认为我必须能够在不使用过滤器的情况下完成此操作?

我的 servlet 映射如下所示:

<servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/mypage/*</url-pattern>
</servlet-mapping>

控制器请求映射:

@RequestMapping(method = RequestMethod.GET)
public String getView(HttpServletRequest request, @ModelAttribute("myform") final MyForm form)  {
        return "myview";
}
@ResponseBody
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@POST
@RequestMapping(value = "/save")
public String onSave(@RequestBody MyForm form, HttpServletRequest request, HttpServletResponse response)  {
        return "saved";
}

【问题讨论】:

    标签: spring spring-mvc


    【解决方案1】:

    您必须使用名为InterceptorsSpring MVC 过滤器。

    如果你自己写Interceptor,你有以下两种选择:

    1.选项:

    使用postHandle() 方法检查您的条件。如果您使用postHandle() 方法,您可以访问ModelAndView,并且如果您的网址与您的3 个网址之一不匹配,您可以抛出Exception 或更改ModelAndView

    2。选项:

    使用preHandle() 方法,检查网址,如果它们不匹配,则抛出ModelAndViewDefiningExceptionnew ModelAndView(),如下所示: ModelAndViewDefiningException(new ModelAndView("errorPage"))

    【讨论】:

      【解决方案2】:

      servlet 的&lt;url-pattern&gt; 标签不支持排除。这是 Servlet 规范的限制。
      您必须在 filter 中以编程方式创建此功能。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-18
        • 1970-01-01
        • 2016-01-02
        • 1970-01-01
        • 1970-01-01
        • 2021-06-15
        • 2012-11-04
        • 2012-08-25
        相关资源
        最近更新 更多