使用 javax.servlet 2.5 设置 httponly cookie [英] Setting an httponly cookie with javax.servlet 2.5

查看:69
本文介绍了使用 javax.servlet 2.5 设置 httponly cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个设置cookie的函数:

here is a function that sets a cookie:

public void addCookie(String cookieName, String cookieValue, Integer maxAge, HttpServletResponse response) {
    Cookie cookie = new Cookie(cookieName, cookieValue);
    cookie.setPath("/mycampaigns");
    cookie.setSecure(isSecureCookie);
    cookie.setMaxAge(maxAge);
    response.addCookie(cookie);
}

我相信servlet 3.0,有一种方法可以直接做到这一点.不幸的是,我的组织使用 2.5 并且此时升级不是一个选项.

I believe in servlet 3.0, there is a way to do this directly. Unfortunately my organization uses 2.5 and UPGRADING at this juncture IS NOT AN OPTION.

有没有办法使用响应来设置cookie?这是我在网上找到的一个例子

is there way to use the response to set the cookie? Here's an example i found online

response.setHeader("SET-COOKIE", "[SOME STUFF]" +"; HttpOnly")

如果这是做我想做的唯一方法,我会用什么替换[SOME STUFF]",这样我就不会丢失我的函数当前存储在 cookie 中的任何数据?

If this is the only way to do what i want, what would i replace "[SOME STUFF]" with so that i don't lose any of the data that my function currently stores in the cookie?

推荐答案

你说得对,手动设置标题是实现目标的正确方法.

You are right, manually setting header is the right way to achive your goal.

您还可以使用 javax.ws.rs.core.NewCookie 或任何其他具有有用 toString 方法的类将 cookie 打印到标题中,以使事情变得更简单.

You can also use javax.ws.rs.core.NewCookie or any other class with useful toString method to print cookie to a header to make things more simple.

public static String getHttpOnlyCookieHeader(Cookie cookie) {

    NewCookie newCookie = new NewCookie(cookie.getName(), cookie.getValue(), 
            cookie.getPath(), cookie.getDomain(), cookie.getVersion(), 
            cookie.getComment(), cookie.getMaxAge(), cookie.getSecure());

    return newCookie + "; HttpOnly";
}

以及用法:

response.setHeader("SET-COOKIE", getHttpOnlyCookieHeader(myOriginalCookie));

这篇关于使用 javax.servlet 2.5 设置 httponly cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆