有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是否在servlet中检索上一页路径?

我试图保持用户跟踪,如果他没有权限,然后将他返回到他请求的页面(上一页路径),并显示消息。在doGet()中,当我尝试使用request.getPathInfo()获取请求url时,它在jboss控制台中给出null

我的doGet源代码来自servlet:

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    if (!validateUserSession(request, response)) {
        return;
    }

    String pathTrace = request.getPathInfo();
    System.out.println("Request is comming from : " + pathTrace); // null

    loadNavigation(request, response);

    ServletContext context = getServletContext();
    RequestDispatcher rd = context
            .getRequestDispatcher("/jsp/admin_account/InviteUser.jsp");
    rd.forward(request, response);
}

共 (2) 个答案

  1. # 1 楼答案

    JavaDocs,getPathInfo可能返回NULL

    public java.lang.String getPathInfo()

    Returns any extra path information associated with the URL the client sent when it made this request. The extra path information follows the servlet path but precedes the query string. This method returns null if there was no extra path information.

    使用下面的API

    public java.lang.String getServletPath()

    Returns the part of this request's URL that calls the servlet. This includes either the servlet name or a path to the servlet, but does not include any extra path information or a query string. Same as the value of the CGI variable SCRIPT_NAME. Returns: a String containing the name or path of the servlet being called, as specified in the request URL, decoded.

    编辑:因为需要传递servlet URL

    在传递的servlet中添加referer_url作为另一个参数,并将该值传递给您试图获取路径的其他servlet

  2. # 2 楼答案

    从请求头中获取它

    String pathTrace = request.getHeader("referer");
    System.out.println("Request is comming from : " + pathTrace);