下面列出了javax.servlet.http.HttpUtils#javax.servlet.http.Cookie 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 得到Cookie的值,
*
* @param request
* @param cookieName
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null) {
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookieList.length; i++) {
if (cookieList[i].getName().equals(cookieName)) {
if (isDecoder) {
retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
} else {
retValue = cookieList[i].getValue();
}
break;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return retValue;
}
/**
* 获得指定Cookie的值
*
* @param request 请求对象
* @param response 响应对象
* @param name 名字
* @param isRemove 是否移除
* @return 值
*/
public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, boolean isRemove) {
String value = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
try {
value = URLDecoder.decode(cookie.getValue(), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (isRemove) {
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
}
}
return value;
}
/**
* 得到Cookie的值
* @author jitwxs
* @version 创建时间:2018年4月16日 下午7:08:13
* @param isDecoder 是否编码,编码格式为UTF-8
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null) {
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookieList.length; i++) {
if (cookieList[i].getName().equals(cookieName)) {
if (isDecoder) {
retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
} else {
retValue = cookieList[i].getValue();
}
break;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return retValue;
}
private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue, int cookieMaxage, String encodeString) {
try {
if (cookieValue == null) {
cookieValue = "";
} else {
cookieValue = URLEncoder.encode(cookieValue, encodeString);
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxage > 0)
cookie.setMaxAge(cookieMaxage);
if (null != request) {// 设置域名的cookie
String domainName = getDomainName(request);
// System.out.println(domainName);
if (!"localhost".equals(domainName)) {
cookie.setDomain(domainName);
}
}
cookie.setPath("/");
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("JSESSIONID")){
System.out.println("JSESSIONID="+cookie.getValue());
}
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
//invalidate the session if exists
HttpSession session = request.getSession(false);
System.out.println("User="+session.getAttribute("user"));
if(session != null){
session.invalidate();
}
//no encoding because we have invalidated the session
response.sendRedirect("login.html");
}
public void logout() {
Cookie[] cookies = getRequest().getCookies();
for (Cookie cookie : cookies) {
if ("zId".equals(cookie.getName())) {
cookie.setValue("");
cookie.setMaxAge(Constants.getSessionTimeout().intValue());
getResponse().addCookie(cookie);
}
if (Constants.ADMIN_TOKEN.equals(cookie.getName())) {
cookie.setValue("");
cookie.setMaxAge(Constants.getSessionTimeout().intValue());
cookie.setPath("/");
adminTokenService.setCookieDomain(getRequest(), cookie);
getResponse().addCookie(cookie);
}
}
redirect(LOGOUT_URI);
}
public void setAdminToken(User user, int sessionId, String protocol, HttpServletRequest request, HttpServletResponse response) {
AdminTokenVO adminTokenVO = new AdminTokenVO();
adminTokenVO.setUserId(user.getInt("userId"));
adminTokenVO.setSessionId(sessionId);
adminTokenVO.setProtocol(protocol);
long loginTime = System.currentTimeMillis();
adminTokenVO.setCreatedDate(loginTime);
AdminTokenThreadLocal.setAdminToken(adminTokenVO);
String encryptBeforeString = new Gson().toJson(adminTokenVO);
try {
byte[] base64Bytes = Base64.encodeBase64(encrypt(user.get("secretKey").toString(), encryptBeforeString.getBytes()));
String encryptAfterString = ByteUtils.bytesToHexString(base64Bytes);
String finalTokenString = adminTokenVO.getUserId() + TOKEN_SPLIT_CHAR + encryptAfterString;
Cookie cookie = new Cookie(Constants.ADMIN_TOKEN, finalTokenString);
cookie.setMaxAge((int) (Constants.getSessionTimeout() / 1000));
setCookieDomain(request, cookie);
cookie.setPath("/");
response.addCookie(cookie);
} catch (Exception e) {
LOGGER.error("", e);
}
}
/**
* Copy cookie from the proxy to the servlet client.
* Replaces cookie path to local path and renames cookie to avoid collisions.
*/
private void copyProxyCookie(HttpServletRequest servletRequest,
HttpServletResponse servletResponse, Header header) {
List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
String path = servletRequest.getContextPath(); // path starts with / or is empty string
path += servletRequest.getServletPath(); // servlet path starts with / or is empty string
for (int i = 0, l = cookies.size(); i < l; i++) {
HttpCookie cookie = cookies.get(i);
//set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
String proxyCookieName = getCookieNamePrefix() + cookie.getName();
Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
servletCookie.setComment(cookie.getComment());
servletCookie.setMaxAge((int) cookie.getMaxAge());
servletCookie.setPath(path); //set to the path of the proxy servlet
// don't set cookie domain
servletCookie.setSecure(cookie.getSecure());
servletCookie.setVersion(cookie.getVersion());
servletResponse.addCookie(servletCookie);
}
}
/**
* Update SCOPE_ID request attribute based on either cookie or URL query param
* information received in the request.
*
* @param event the event.
*/
public void beforeProcessControllerEvent(@Observes BeforeControllerEvent event) {
if (usingCookies()) {
final Cookie[] cookies = request.getCookies();
if (null != cookies) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(COOKIE_NAME)) {
request.setAttribute(SCOPE_ID, cookie.getValue());
return; // we're done
}
}
}
} else {
final String scopeId = event.getUriInfo().getQueryParameters().getFirst(SCOPE_ID);
if (scopeId != null) {
request.setAttribute(SCOPE_ID, scopeId);
}
}
}
/**
* <p>
* 清除指定Cookie 等同于 clearCookieByName(...)
* </p>
* <p>
* <p>
* 该方法不判断Cookie是否存在,因此不对外暴露防止Cookie不存在异常.
* </p>
*
* @param response
* @param cookieName cookie name
* @param domain Cookie所在的域
* @param path Cookie 路径
* @return boolean
*/
private static boolean clearCookie(HttpServletResponse response, String cookieName, String domain, String path) {
boolean result = false;
try {
Cookie cookie = new Cookie(cookieName, "");
cookie.setMaxAge(CLEAR_IMMEDIATELY_REMOVE);
if (StringUtils.isNotEmpty(domain)) {
cookie.setDomain(domain);
}
cookie.setPath(path);
response.addCookie(cookie);
log.debug("clear cookie " + cookieName);
result = true;
} catch (Exception e) {
log.error("clear cookie " + cookieName + " is exception!\n" + e.toString());
}
return result;
}
@Before
public void setUp() throws Exception {
sessionBean = spy(new SessionBean());
doReturn(MARKETPLACE_ID).when(sessionBean).getMarketplaceId();
// Mock the faces context of the SessionBean
fcContextMock = mock(FacesContext.class);
doReturn(fcContextMock).when(sessionBean).getFacesContext();
// Mock the external context of the faces context
ExternalContext extContextMock = mock(ExternalContext.class);
doReturn(extContextMock).when(fcContextMock).getExternalContext();
doReturn(WHITE_LABEL_PATH).when(extContextMock).getRequestContextPath();
req = mock(HttpServletRequest.class);
doReturn(req).when(extContextMock).getRequest();
doReturn(req).when(sessionBean).getRequest();
// Mock the marketplace service
marketplaceServiceMock = mock(MarketplaceService.class);
doReturn(marketplaceServiceMock).when(sessionBean)
.getMarketplaceService();
cookies = new Cookie[1];
doReturn(cookies).when(req).getCookies();
}
private boolean removeAuthenticationToken(HttpServletResponse response) {
boolean rc = true;
Cookie c = new Cookie(cookieName, null);
c.setMaxAge(0);
c.setPath("/");
try {
String domainName = Urls.getDomainName(request.getRequestURL().toString(), null);
if(domainName != null) {
c.setDomain(domainName);
}
} catch (MalformedURLException e) {
log.problemWithCookieDomainUsingDefault();
// we are probably not going to be able to
// remove the cookie due to this error but it
// isn't necessarily not going to work.
rc = false;
}
response.addCookie(c);
return rc;
}
@Override
@Nullable
protected Object resolveName(String cookieName, MethodParameter parameter,
NativeWebRequest webRequest) throws Exception {
HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
Assert.state(servletRequest != null, "No HttpServletRequest");
Cookie cookieValue = WebUtils.getCookie(servletRequest, cookieName);
if (Cookie.class.isAssignableFrom(parameter.getNestedParameterType())) {
return cookieValue;
}
else if (cookieValue != null) {
return this.urlPathHelper.decodeRequestString(servletRequest, cookieValue.getValue());
}
else {
return null;
}
}
static Authentication getAuthentication(HttpServletRequest request) {
Cookie cookie = WebUtils.getCookie(request, COOKIE_BEARER);
String token = cookie != null ? cookie.getValue() : null;
if (token != null) {
Claims claims = Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token)
.getBody();
Collection<? extends GrantedAuthority> authorities =
Arrays.stream(claims.get("authorities").toString().split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
String userName = claims.getSubject();
return userName != null ? new UsernamePasswordAuthenticationToken(userName, null, authorities) : null;
}
return null;
}
@Override
protected void buildCookie(com.intuit.karate.http.Cookie c) {
Cookie cookie = new Cookie(c.getName(), c.getValue());
requestBuilder.cookie(cookie);
for (Map.Entry<String, String> entry : c.entrySet()) {
if (entry.getValue() != null) {
switch (entry.getKey()) {
case DOMAIN:
cookie.setDomain(entry.getValue());
break;
case PATH:
cookie.setPath(entry.getValue());
break;
}
}
}
if (cookie.getDomain() == null) {
cookie.setDomain(uri.getHost());
}
}
/**
* 根据键读取cookie的值
*
* @param request 请求对象
* @param key 读取cookie的键
* @return cookie的值
*/
public static String readCookie(HttpServletRequest request, String key) {
Cookie[] cookies = request.getCookies();
if (cookies != null&&key!=null) {
for (Cookie cookie : cookies) {
if (cookie != null && key.equalsIgnoreCase(cookie.getName())) {
try {
String value = URLDecoder.decode(cookie.getValue(), SystemConfig.CHARSET);
return value;
} catch (UnsupportedEncodingException e) {
}
}
}
}
return null;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String name = req.getParameter("cookieName");
String value = req.getParameter("cookieValue");
String secure = req.getParameter("secure");
String path = req.getParameter("cookiePath");
Cookie cookie = new Cookie(name, value);
if (secure.equals("yes")) {
cookie.setSecure(true);
}
if (path != null) {
cookie.setPath(path);
}
res.addCookie(cookie);
RequestDispatcher requestDispatcher = req
.getRequestDispatcher("/cookie.jsp");
requestDispatcher.forward(req, res);
}
public PullRequestActivitiesPage(PageParameters params) {
super(params);
WebRequest request = (WebRequest) RequestCycle.get().getRequest();
Cookie cookie = request.getCookie(COOKIE_SHOW_COMMENTS);
if (cookie != null)
showComments = Boolean.valueOf(cookie.getValue());
cookie = request.getCookie(COOKIE_SHOW_COMMITS);
if (cookie != null)
showCommits = Boolean.valueOf(cookie.getValue());
cookie = request.getCookie(COOKIE_SHOW_CHANGE_HISTORY);
if (cookie != null)
showChangeHistory = Boolean.valueOf(cookie.getValue());
}
@GetMapping(value = "/getCookies")
@ApiOperation(value = "通过这个方法可以获取到Cookies",httpMethod = "GET")
public String getCookies(HttpServletResponse response){
//HttpServerletRequest 装请求信息的类
//HttpServerletResponse 装响应信息的类
Cookie cookie = new Cookie("login","true");
response.addCookie(cookie);
return "恭喜zuozewei获得cookies信息成功";
}
@Override
public boolean addAll(Collection<? extends Cookie> collection) {
boolean result = false;
for(Cookie cookie : collection) {
result|= add(cookie);
}
return result;
}
@Test
public void resolveCookieArgument() throws Exception {
Cookie expected = new Cookie("name", "foo");
request.setCookies(expected);
Cookie result = (Cookie) resolver.resolveArgument(cookieParameter, null, webRequest, null);
assertEquals("Invalid result", expected, result);
}
/**
* Get Cookie by Name
*
* @param name
* @return
*/
public Cookie getCookie( String name )
{
Object cookie = this.cookies.get( name );
if ( cookie != null )
return (Cookie) cookie;
else
return null;
}
/**
* 设置 Cookie
*
* @param name 名称
* @param value 值
* @param maxAge 生存时间(单位秒)
* @param path 路径
*/
public static void setCookie(HttpServletResponse response, String name, String value, String path, int maxAge) {
Cookie cookie = new Cookie(name, null);
cookie.setPath(path);
cookie.setMaxAge(maxAge);
try {
cookie.setValue(URLEncoder.encode(value, "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.addCookie(cookie);
}
/**
* 获取cookie
* @param request
* @param name
* @return
*/
public static String getCookie(HttpServletRequest request, String name) {
String value = null;
Cookie[] cookies = request.getCookies();
if (null != cookies) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
value = cookie.getValue();
}
}
}
return value;
}
/**
* Adds a new cookie to the request
* @param cookie a cookie to add, will displace existing cookies with the same name
*/
public void addCookie(Cookie cookie) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie cannot be null");
}
for (Iterator<Cookie> iterator = cookies.iterator(); iterator.hasNext();) {
Cookie c = iterator.next();
if (cookie.getName().equals(c.getName())) {
iterator.remove();
}
}
cookies.add(cookie);
}
/**
* 根据名字获取cookie.
*
* @param request HttpServletRequest
* @param name cookie名字
* @return Cookie
*/
public static Cookie readCookieByName(HttpServletRequest request, String name) {
Map<String, Cookie> cookieMap = readCookieAll(request);
if (cookieMap.containsKey(name)) {
Cookie cookie = (Cookie) cookieMap.get(name);
return cookie;
} else {
return null;
}
}
@Test
public void containsAll() throws Exception {
List<Cookie> content = Arrays.asList(cookie, brownieCookie);
CookieCollection cookies = new CookieCollection(content);
Assert.assertTrue(cookies.containsAll(content));
Assert.assertTrue(cookies.containsAll(Collections.singletonList(cookie)));
Assert.assertFalse(cookies.containsAll(Arrays.asList(cookie, brownieCookie, cupsCookie)));
Assert.assertTrue(cookies.containsAll(Arrays.asList(COOKIE_NAME, BROWNIE_NAME)));
}
public static Cookie getCookie(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
return cookie;
}
}
}
return null;
}
/**
* 设置cookie
*
* @param response response
* @param name name
* @param value value
* @param maxAgeInSeconds maxAgeInSeconds
*/
public static void setCookie(HttpServletResponse response, String name, String value, int maxAgeInSeconds) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
cookie.setMaxAge(maxAgeInSeconds);
// 指定为httpOnly保证安全性
cookie.setHttpOnly(true);
response.addCookie(cookie);
}
@Test
public void buildResponseHeadersNullDomainDefaulted() throws Exception {
Cookie cookie = new Cookie("cookieA", "valueA");
this.response.addCookie(cookie);
WebResponse webResponse = this.responseBuilder.build();
List<NameValuePair> responseHeaders = webResponse.getResponseHeaders();
assertThat(responseHeaders.size(), equalTo(1));
NameValuePair header = responseHeaders.get(0);
assertThat(header.getName(), equalTo("Set-Cookie"));
assertThat(header.getValue(), equalTo("cookieA=valueA"));
}