You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Servlet url-pattern改为/client后路径匹配异常求助

Servlet路径匹配异常解决方案

当你把url-pattern从/改为/client后,路径匹配失效的核心原因是请求路径的解析逻辑变了:

问题根源

  • 原配置/是全局匹配,访问/new时,request.getServletPath()会返回/new,刚好匹配switch里的case;
  • 现在配置/client是精确匹配,仅能匹配/client路径。当访问/client/new时,Servlet根本不会被触发(路径不满足精确匹配),就算调整匹配规则,getServletPath()返回的也是/client,而非你需要的/new。

两步解决

  1. 修改web.xml的映射规则
    将url-pattern改为/client/*,这样所有以/client/开头的请求都会被该Servlet处理:

    <servlet-mapping>
        <servlet-name>ClientServlet</servlet-name>
        <url-pattern>/client/*</url-pattern>
    </servlet-mapping>
    
  2. 调整Servlet里的action获取逻辑
    使用request.getPathInfo()获取路径后缀(也就是/new、/edit这类部分),替换原来的getServletPath():

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getPathInfo();
        // 处理默认情况(直接访问/client时action为null)
        if (action == null) {
            action = "";
        }
    
        try {
            switch (action) {
                case "/new":
                    showNewForm(request, response);
                    break;
                // 其他case保持不变
                default:
                    listClients(request, response);
                    break;
            }
        } catch (SQLException ex) {
            throw new ServletException(ex);
        }
    }
    

这样调整后,访问http://localhost:8081/Atelier1/client/new时,getPathInfo()会返回/new,就能正确匹配switch里的case,触发showNewForm方法了。

内容的提问来源于stack exchange,提问作者Ahmed Bentaj Hamyani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 04:05:54