最好的选择是 URL 模式/xyz/*
.
The 服务程序接口 https://jakarta.ee/specifications/servlet/6.0/jakarta-servlet-spec-6.0不支持 URL 模式通配符*
在映射的中间,例如/xyz/*/test
也不是 URI 模板。它只是allows https://jakarta.ee/specifications/servlet/6.0/jakarta-servlet-spec-6.0#specification-of-mappings通配符*
在映射的最后像这样/prefix/*
或者像这样在映射的开头*.suffix
.
您可以使用提取路径信息HttpServletRequest#getPathInfo() https://jakarta.ee/specifications/servlet/6.0/apidocs/jakarta.servlet/jakarta/servlet/http/httpservletrequest#getPathInfo()。这是一个基本的启动示例,如何提取路径信息、空值和数组索引越界检查,为简洁起见省略了:
@WebServlet("/xyz/*")
public class XyzServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String pathInfo = request.getPathInfo(); // /{value}/test
String[] pathParts = pathInfo.split("/");
String value = pathParts[1]; // {value}
String action = pathParts[2]; // test
if ("test".equals(action)) {
// ...
}
}
}
如果您希望能够使用URI 模板 https://en.wikipedia.org/wiki/URI_Template尽管如此,这实际上是一个 REST 端点而不是 HTML 页面,然后看一下雅加达 REST (JAX-RS) https://eclipse-ee4j.github.io/jakartaee-tutorial/#extracting-path-parameters:
@Path("/xyz/{value}/test")
public class XyzResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getTest(@PathParam("value") String value) {
// ...
}
}
如果您想要更细粒度的控制,例如使用 Apache HTTPDmod_rewrite
,那么你可以看看Tuckey 的 URL 重写过滤器 https://tuckey.org/urlrewrite/ or 自行开发 URL 重写过滤器 https://stackoverflow.com/questions/2725102/how-to-use-a-servlet-filter-in-java-to-change-an-incoming-servlet-request-url.