gpt4 book ai didi

servlets - 如何在servlet中获取路径变量值

转载 作者:行者123 更新时间:2023-12-04 17:55:44 24 4
gpt4 key购买 nike

我想获取 servlet 中的路径变量。假设 url 是 www.demo.com/123/demo。我想从路径中获取 123 值而不进行任何字符串操作。

注意:以下 servlet 没有任何 web.xml 配置。我的代码是:

@WebServlet(urlPatterns = { "/demo" })
public class DemoServlet extends HttpServlet {

public DemoServlet()
{
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request,response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
sysout("demo");
}
}

最佳答案

您所指的 URL 部分是“上下文”。使用 request.getContextPath() 获取它。对于您的示例,这将返回 /123。如果您想要 exactly 123,则必须删除前导斜杠。

来自documentation :

Returns the portion of the request URI that indicates the context of the request. The context path always comes first in a request URI. The path starts with a "/" character but does not end with a "/" character. For servlets in the default (root) context, this method returns "". The container does not decode this string.

关于servlets - 如何在servlet中获取路径变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40658625/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com