转发到 JSP 时如何检测 Java Servlet 中的 URL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1030798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 14:52:23  来源:igfitidea点击:

How do you detect the URL in a Java Servlet when forwarding to JSP?

javajspservlets

提问by Jeremy Logan

I have a servlet that looks something like this:

我有一个看起来像这样的 servlet:

public class ExampleServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().println(request.getPathInfo());
    }
}

with a web.xml mapping like:

使用 web.xml 映射,如:

<servlet>
    <servlet-name>example</servlet-name>
    <servlet-class>com.example.ExampleServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>example</servlet-name>
    <url-pattern>/example/*</url-pattern>
</servlet-mapping>

and it gives me exactly what I expect... If I go to http://localhost:8080/example/fooit prints "/foo". However, if I change the servlet to forward to a JSP file:

它给了我我所期望的......如果我去http://localhost:8080/example/foo它会打印“/foo”。但是,如果我将 servlet 更改为转发到 JSP 文件:

public class ExampleServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // do something here to check the value of request.getPathInfo()
        request.getRequestDispatcher("whatever.jsp").forward(request, response);
    }
}

then when I check the value of getPathInfo() it now reports "whatever.jsp" instead of "foo".

然后当我检查 getPathInfo() 的值时,它现在报告“whatever.jsp”而不是“foo”。

  1. Why has this changed before it's been forwarded to the JSP?
  2. How can I detect what URL the user's looking for?
  1. 为什么在它被转发到 JSP 之前就发生了变化?
  2. 如何检测用户正在寻找的 URL?

EDIT:Just in case it matters this is on Google App Engine. Don't think it should though.

编辑:以防万一这在 Google App Engine 上。不要认为它应该虽然。

回答by BalusC

The question is vague and ambiguous (is the servlet calling itself on every forward again?), but it much sounds like that you need request.getAttribute("javax.servlet.forward.request_uri").

这个问题含糊不清(servlet 是否再次在每次转发时调用自己?),但听起来很像您需要的request.getAttribute("javax.servlet.forward.request_uri").

回答by Tom

The URL the user (browser) requested can be accessed from the request by:

用户(浏览器)请求的 URL 可以通过以下方式从请求中访问:

request.getRequestURL()

Alternatively the request has a whole bunch of accessorsto get the various pieces of the URL as well as those on ServletRequest.

或者,请求有一大堆访问器来获取 URL 的各个部分以及ServletRequest 上的那些。

To redirect to a different URL change the response rather than the request:

要重定向到不同的 URL,请更改响应而不是请求:

response.sendRedirect(theURLToRedirectTo)