package edu.sjtu.infosec.ismp.manager.EM.util; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Convenience class for setting and retrieving cookies. */ public class RequestUtil { /** * ��日志 * */ private static transient Log log = LogFactory.getLog(RequestUtil.class); /** * Convenience method to set a cookie * * @param response response * @param name name * @param value value * @param path path */ public static void setCookie(HttpServletResponse response, String name, String value, String path) { if (log.isDebugEnabled()) { log.debug("Setting cookie '" + name + "' on path '" + path + "'"); } Cookie cookie = new Cookie(name, value); cookie.setSecure(false); cookie.setPath(path); cookie.setMaxAge(new Integer("3600").intValue() * new Integer("24").intValue() * new Integer("30").intValue()); // 30 days response.addCookie(cookie); } /** * Convenience method to get a cookie by name * * @param request the current request * @param name the name of the cookie to find * * @return the cookie (if found), null if not found */ public static Cookie getCookie(HttpServletRequest request, String name) { Cookie[] cookies = request.getCookies(); Cookie returnCookie = null; if (cookies == null) { return returnCookie; } for (int i = 0; i < cookies.length; i++) { Cookie thisCookie = cookies[i]; if (thisCookie.getName().equals(name)) { // cookies with no value do me no good! if (!thisCookie.getValue().equals("")) { returnCookie = thisCookie; break; } } } return returnCookie; } /** * Convenience method for deleting a cookie by name * * @param response the current web response * @param cookie the cookie to delete * @param path the path on which the cookie was set (i.e. /appfuse) */ public static void deleteCookie(HttpServletResponse response, Cookie cookie, String path) { if (cookie != null) { // Delete the cookie by setting its maximum age to zero cookie.setMaxAge(0); cookie.setPath(path); response.addCookie(cookie); } } /** * Convenience method to get the application's URL based on request * variables. * @param request request * @return AppURL */ public static String getAppURL(HttpServletRequest request) { StringBuffer url = new StringBuffer(); int port = request.getServerPort(); if (port < 0) { port = new Integer("80").intValue(); // Work around java.net.URL bug } String scheme = request.getScheme(); url.append(scheme); url.append("://"); url.append(request.getServerName()); if ((scheme.equals("http") && (port != new Integer("80").intValue())) || (scheme.equals("https") && (port != new Integer("443").intValue()))) { url.append(':'); url.append(port); } url.append(request.getContextPath()); return url.toString(); } }