org.fryske_akademy.jsf.util.CookieHelper Maven / Gradle / Ivy
The newest version!
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.fryske_akademy.jsf.util;
/*-
* #%L
* guiCrudApi
* %%
* Copyright (C) 2018 Fryske Akademy
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author eduard
*/
public class CookieHelper {
/**
* expires all existing cookies with this name and sets a fresh one, so there
* will be only one valid cookie with this name. {@link JsfUtil#contextPath() } will be
* used as path for he cookie.
* @param name
* @param value
* @param expiry
*/
public static void replaceCookie(String name, String value, int expiry, HttpServletRequest request, HttpServletResponse response) {
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie c : cookies) {
if (c.getName().equals(name)) {
c.setMaxAge(0);
c.setValue(null);
response.addCookie(c);
}
}
}
Cookie cookie = new Cookie(name, value);
cookie.setPath(JsfUtil.contextPath());
cookie.setSecure(true);
cookie.setMaxAge(expiry);
response.addCookie(cookie);
}
/**
* return the first cookie found with this name
* @param name
* @return
*/
public static Cookie getCookie(String name, HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
return cookie;
}
}
}
return null;
}
}