【问题标题】:Wildcard path mapping /A/* should return 404 when path info is absent like /A当路径信息不存在时,通配符路径映射 /A/* 应返回 404,如 /A
【发布时间】:2015-11-08 10:02:14
【问题描述】:

我是 Servlet 的新手。我正在尝试使用 通配符 (*) 映射 URL,但它没有按我预期的方式工作。

这是我的 servlet 类。

@WebServlet(urlPatterns = {"/A/*"})
public class TestServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().write("Working...");
    }
}

上述 servlet 适用于 example.com/A 和 example.com/A/car。 我只想为第二个选项example.com/A/whatEver 使用servlet。我该怎么做?

简单来说:如果 example.com/A 之后有任何内容,我只想使用 servlet。

任何帮助将不胜感激。

【问题讨论】:

  • 它应该可以工作,你得到什么错误。?
  • 没有错误,但它对两个网址都有效。如果 example.com/A 之后有任何内容,我只想使用 servlet。
  • 你的意思是说它应该适用于 example.com/a/* 是吗?
  • 路径始终与您的 Web 应用程序上下文相关,通常与您的项目名称相同:example.com/<contextPath>/A/*...
  • 那么你可以使用example.com/a*

标签: servlets wildcard url-pattern pathinfo


【解决方案1】:

当HttpServletRequest#getPathInfo() 为空或empty 或equals 到/ 时,只需使用SC_NOT_FOUND (404) 调用HttpServletResponse#sendError()。

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String pathInfo = request.getPathInfo();

    if (pathInfo == null || pathInfo.isEmpty() || pathInfo.equals("/")) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // ... (continue)
}

【讨论】:

    猜你喜欢
    • 2019-03-31
    • 1970-01-01
    • 2018-06-15
    • 2011-08-21
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多