【问题标题】:HttpServletRequest not returning entire cookieHttpServletRequest 不返回整个 cookie
【发布时间】:2013-03-06 02:20:52
【问题描述】:

我的 HttpServletRequest.getCookies() 没有返回整个 cookie 值。 cookie 值是另一个键值对,因此可能会弄乱解析。我需要知道如何解决这个问题。

所以这是背景。我正在使用新的 apache2.4 mod_auth_form,它通过在 cookie 中设置用户名和密码来进行身份验证。 cookie 看起来像这样: "session=private-user=myUser&private-pw=myPass"

我在 Apache 上设置了代理,以便将某些 REST 调用传递到 tomcat 服务,在那里我有一个 Jersey REST 类在等待它们。

我可以在浏览器中看到 cookie。我还可以在 php.ini 中看到完整的 cookie。 但是,在我的 java 类中,HttpServletRequest 具有“会话”cookie,但值只是“私人用户”,而不是我期望的“私人用户=myUser&private-pw=myPass”。

我最好的猜测是带有 = 和 & 符号的键值对搞砸了解析。如何获得完整的原始 cookie 值?

如果重要的话,这是我的 java 代码:

private String getAuthenticatedUser(HttpServletRequest httpRequest) {
        String user = null;
        Cookie[] cookies = httpRequest.getCookies();
        for(Cookie cookie : cookies) {
            System.out.println(cookie.getValue());
        }
}

谢谢

【问题讨论】:

    标签: servlets cookies jersey


    【解决方案1】:

    使用 URLEncoder 对值进行编码,然后再将其设置到 cookie 中。

    String s = new String("private-user=myUser&private-pw=myPass");
    String encoded = URLEncoder.encode(s);
    

    并使用 URLDecoder 将其解码回原始值

    URLDecoder.decode(encoded);
    

    【讨论】:

    • 不幸的是,我无法控制这一点。正如我所提到的,apache mod_auth_form 模块设置了 cookie。
    【解决方案2】:

    我找到了使用 Jersey 的 @CookieParam 注释的方法。

    @GET
    @Path("/")
    public Response myRestCall(@CookieParam("session") String sessionValue) {
      System.out.println(sessionValue);
    }
    

    Jersey 似乎在解析这种类型的键值 cookie 方面做得更好,并按我的预期返回了“private-user=myUser&private-pw=myPass”。

    【讨论】:

    • 这并没有解释它是如何解决问题的。您刚刚使用 Annotation 代替了手动从 cookie 中获取值
    • 你是对的。它解决了我的问题,因为我能够解决它。而且这个解决方案对我来说实际上比使用 HttpServletRequest 更优雅。但如果你知道如何,我仍然想知道如何从 HttpServletRequest 中获取完整的 cookie。
    猜你喜欢
    • 1970-01-01
    • 2014-11-14
    • 2012-02-14
    • 2019-12-25
    • 2011-11-18
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 2016-01-12
    相关资源
    最近更新 更多