有 Java 编程相关的问题?

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

如果客户端不接受cookie,java如何处理会话?理解反应。Servlet中的encodeURL()

我正在练习维护客户端和服务器之间的会话。为此,我使用了存储在cookie中的JSESSIONID的简单解决方案。所以我的小程序是这样工作的:

索引。html:

<html><body>
    
    <form action="testing">
        <input type="text" name="animal">
        <button>Go</button>
    </form>
    
</body></html>

我的服务。java(在XML中映射为/testing)

public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        String name = req.getParameter("animal");
        PrintWriter pw = resp.getWriter();

        pw.print("Welcome " + name + "<br>");

        HttpSession session = req.getSession();

        if (session.isNew()) {
            pw.print("New session: " + session.getId() + "<br>");
        } else {
            pw.print("Old session: " + session.getId() + "<br>");
        }

        pw.print("<a href=\'index.html\'> Home </a>");
    }
}

所以,若我从表单提交了两次以上的内容,服务器应该“找到”我的JSESSIONID存储在堆中。以下是提交表单时的外观图片(我在输入中键入了“parrot”):

enter image description here

但后来我在浏览器中禁用了cookies。之后,我的服务器再也找不到用户的JSESSIONID,因为用户从未将其存储在任何地方。请记住,以前,JSESSIONID存储在cookie中,但由于我禁用了它们,它不可能再将其存储在cookie中。所以现在,我被困住了

在这种情况下我能做什么?我发现response.encodeURL()使用URL并将其JSESSIONID附加到URL中。但我很难理解如何实现它以及它如何在内部工作。有人能告诉我如何使用encodeURL()解决这个问题,并实际解释代码在实现之后是如何工作的吗


共 (2) 个答案

  1. # 1 楼答案

    你可以做点什么。这用于将您的JSESSIONID附加到您将检索给用户的url,以便用户可以在其中导航并维护他们是谁的信息。了解它的内部工作原理很简单,正如您所见,它只是将id附加到您传递的url,用户信息如何存储,是您在服务器端的功能,您将在下一个请求中使用用户提供的id来检索信息

    /**
    * Almost minimal processing for a servlet.
    *
    * @param nextUrl The url the caller would like to go to next. If
    *                supplied, put an encoded url into the returned
    *                html page as a hyperlink.
    */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
       throws ServletException, IOException {
    
       resp.setContentType("text/plain");
       PrintWriter out = resp.getWriter();
       out.print("OK");
    
       String param = req.getParameter("nextUrl");
       if (param!=null) {
           // append an encoded url to carry the sessionids
           String targetUrl = resp.encodeURL(param);
           out.print(". You want to go <a href=\"");
           out.print(targetUrl);
           out.print("\">here next</a>.");
       }
    }
    

    编辑: 你把它放在代码的这一部分

    pw.print("<a href=\'" + resp.encodeURL("index.html") + "\'>Home</a>");
    
  2. # 2 楼答案

    根据the specification,服务器应该支持几种跟踪会话的方法:使用cookie、SSL会话或URL重写

    您询问的是URL重写,其工作原理如下:

    URL rewriting is the lowest common denominator of session tracking. When a client will not accept a cookie, URL rewriting may be used by the server as the basis for session tracking. URL rewriting involves adding data, a session ID, to the URL path that is interpreted by the container to associate the request with a session.

    The session ID must be encoded as a path parameter in the URL string. The name of the parameter must be jsessionid. Here is an example of a URL containing encoded path information:

    http://www.myserver.com/catalog/index.html;jsessionid=1234

    URL rewriting exposes session identifiers in logs, bookmarks, referer headers, cached HTML, and the URL bar. URL rewriting should not be used as a session tracking mechanism where cookies or SSL sessions are supported and suitable.

    请注意,它是一个路径参数,而不是查询参数。您的查询参数如下所示:

    http://www.myserver.com/catalog/index.html;jsessionid=1234?param1=value1&param2=value2&...
    

    服务器自动支持这种机制来跟踪会话,但很明显,您需要帮助服务器。要做到这一点,请确保所有链接都包含jsessionid,否则服务器将无法通过会话识别您的请求

    您可以在Java代码中使用^{}

    Encodes the specified URL by including the session ID, or, if encoding is not needed, returns the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. For example, if the browser supports cookies, or session tracking is turned off, URL encoding is unnecessary.

    For robust session tracking, all URLs emitted by a servlet should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies.

    您需要在JSP文件中执行同样的操作。这通常是通过^{}之类的方式完成的,而不是直接将URL写入文件:

    [...] You can use the url tag to rewrite URLs returned from a JSP page. The tag includes the session ID in the URL only if cookies are disabled; otherwise, it returns the URL unchanged. Note that this feature requires that the URL be relative. [...]