001: /*
002: * File : $Source: /usr/local/cvs/opencms/src/org/opencms/util/CmsRequestUtil.java,v $
003: * Date : $Date: 2008-03-01 14:40:26 $
004: * Version: $Revision: 1.27 $
005: *
006: * This library is part of OpenCms -
007: * the Open Source Content Management System
008: *
009: * Copyright (c) 2002 - 2008 Alkacon Software GmbH (http://www.alkacon.com)
010: *
011: * This library is free software; you can redistribute it and/or
012: * modify it under the terms of the GNU Lesser General Public
013: * License as published by the Free Software Foundation; either
014: * version 2.1 of the License, or (at your option) any later version.
015: *
016: * This library is distributed in the hope that it will be useful,
017: * but WITHOUT ANY WARRANTY; without even the implied warranty of
018: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
019: * Lesser General Public License for more details.
020: *
021: * For further information about Alkacon Software GmbH, please see the
022: * company website: http://www.alkacon.com
023: *
024: * For further information about OpenCms, please see the
025: * project website: http://www.opencms.org
026: *
027: * You should have received a copy of the GNU Lesser General Public
028: * License along with this library; if not, write to the Free Software
029: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
030: */
031:
032: package org.opencms.util;
033:
034: import org.opencms.flex.CmsFlexRequest;
035: import org.opencms.i18n.CmsEncoder;
036: import org.opencms.jsp.CmsJspActionElement;
037: import org.opencms.main.CmsLog;
038: import org.opencms.main.OpenCms;
039:
040: import java.io.IOException;
041: import java.io.UnsupportedEncodingException;
042: import java.util.ArrayList;
043: import java.util.HashMap;
044: import java.util.Iterator;
045: import java.util.List;
046: import java.util.Map;
047:
048: import javax.servlet.ServletException;
049: import javax.servlet.http.Cookie;
050: import javax.servlet.http.HttpServletRequest;
051: import javax.servlet.http.HttpServletResponse;
052: import javax.servlet.http.HttpSession;
053:
054: import org.apache.commons.fileupload.DiskFileUpload;
055: import org.apache.commons.fileupload.FileItem;
056: import org.apache.commons.fileupload.FileUploadBase;
057: import org.apache.commons.fileupload.FileUploadException;
058: import org.apache.commons.logging.Log;
059:
060: /**
061: * Provides utility functions for dealing with values a <code>{@link HttpServletRequest}</code>.<p>
062: *
063: * @author Alexander Kandzior
064: *
065: * @version $Revision: 1.27 $
066: *
067: * @since 6.0.0
068: */
069: public final class CmsRequestUtil {
070:
071: /** Request attribute that contains the original error code. */
072: public static final String ATTRIBUTE_ERRORCODE = "org.opencms.util.CmsErrorCode";
073:
074: /** HTTP Accept-Charset Header for internal requests used during static export. */
075: public static final String HEADER_ACCEPT_CHARSET = "Accept-Charset";
076:
077: /** HTTP Accept-Language Header for internal requests used during static export. */
078: public static final String HEADER_ACCEPT_LANGUAGE = "Accept-Language";
079:
080: /** HTTP Header "Cache-Control". */
081: public static final String HEADER_CACHE_CONTROL = "Cache-Control";
082:
083: /** HTTP Header "Connection". */
084: public static final String HEADER_CONNECTION = "Connection";
085:
086: /** The "Content-Disposition" http header. */
087: public static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition";
088:
089: /** The "Content-Type" http header. */
090: public static final String HEADER_CONTENT_TYPE = "Content-Type";
091:
092: /** HTTP Header "Expires". */
093: public static final String HEADER_EXPIRES = "Expires";
094:
095: /** HTTP Header "If-Modified-Since". */
096: public static final String HEADER_IF_MODIFIED_SINCE = "If-Modified-Since";
097:
098: /** The Header that stores the session id (used by OpenCms upload applet). */
099: public static final String HEADER_JSESSIONID = "JSESSIONID";
100:
101: /** HTTP Header "Last-Modified". */
102: public static final String HEADER_LAST_MODIFIED = "Last-Modified";
103:
104: /** HTTP Header "Location". */
105: public static final String HEADER_LOCATION = "Location";
106:
107: /** HTTP Header for internal requests used during static export. */
108: public static final String HEADER_OPENCMS_EXPORT = "OpenCms-Export";
109:
110: /** HTTP Header "Pragma". */
111: public static final String HEADER_PRAGMA = "Pragma";
112:
113: /** HTTP Header "Server". */
114: public static final String HEADER_SERVER = "Server";
115:
116: /** HTTP Header "user-agent". */
117: public static final String HEADER_USER_AGENT = "user-agent";
118:
119: /** HTTP Header value "max-age=" (for "Cache-Control"). */
120: public static final String HEADER_VALUE_MAX_AGE = "max-age=";
121:
122: /** HTTP Header value "must-revalidate" (for "Cache-Control"). */
123: public static final String HEADER_VALUE_MUST_REVALIDATE = "must-revalidate";
124:
125: /** HTTP Header value "no-cache" (for "Cache-Control"). */
126: public static final String HEADER_VALUE_NO_CACHE = "no-cache";
127:
128: /** HTTP Header "WWW-Authenticate". */
129: public static final String HEADER_WWW_AUTHENTICATE = "WWW-Authenticate";
130:
131: /** Identifier for x-forwarded-for (i.e. proxied) request headers. */
132: public static final String HEADER_X_FORWARDED_FOR = "x-forwarded-for";
133:
134: /** Assignment char between parameter name and values. */
135: public static final String PARAMETER_ASSIGNMENT = "=";
136:
137: /** Delimiter char between parameters. */
138: public static final String PARAMETER_DELIMITER = "&";
139:
140: /** Delimiter char between url and query. */
141: public static final String URL_DELIMITER = "?";
142:
143: /** The prefix for &. */
144: private static final String AMP = "amp;";
145:
146: /** The log object for this class. */
147: private static final Log LOG = CmsLog.getLog(CmsRequestUtil.class);
148:
149: /**
150: * Default constructor (empty), private because this class has only
151: * static methods.<p>
152: */
153: private CmsRequestUtil() {
154:
155: // empty
156: }
157:
158: /**
159: * Appends a request parameter to the given URL.<p>
160: *
161: * This method takes care about the adding the parameter as an additional
162: * parameter (appending <code>¶m=value</code>) or as the first parameter
163: * (appending <code>?param=value</code>).<p>
164: *
165: * @param url the URL where to append the parameter to
166: * @param paramName the paramter name to append
167: * @param paramValue the parameter value to append
168: *
169: * @return the URL with the given parameter appended
170: */
171: public static String appendParameter(String url, String paramName,
172: String paramValue) {
173:
174: if (CmsStringUtil.isEmpty(url)) {
175: return null;
176: }
177: int pos = url.indexOf(URL_DELIMITER);
178: StringBuffer result = new StringBuffer(256);
179: result.append(url);
180: if (pos >= 0) {
181: // url already has parameters
182: result.append(PARAMETER_DELIMITER);
183: } else {
184: // url does not have parameters
185: result.append(URL_DELIMITER);
186: }
187: result.append(paramName);
188: result.append(PARAMETER_ASSIGNMENT);
189: result.append(paramValue);
190: return result.toString();
191: }
192:
193: /**
194: * Appends a map of request parameters to the given URL.<p>
195: *
196: * The map can contains values of <code>String[]</code> or
197: * simple <code>String</code> values.<p>
198: *
199: * This method takes care about the adding the parameter as an additional
200: * parameter (appending <code>¶m=value</code>) or as the first parameter
201: * (appending <code>?param=value</code>).<p>
202: *
203: * @param url the URL where to append the parameter to
204: * @param params the parameters to append
205: * @param encode if <code>true</code>, the parameter values are encoded before they are appended
206: *
207: * @return the URL with the given parameter appended
208: */
209: public static String appendParameters(String url, Map params,
210: boolean encode) {
211:
212: if (CmsStringUtil.isEmpty(url)) {
213: return null;
214: }
215: if ((params == null) || params.isEmpty()) {
216: return url;
217: }
218: int pos = url.indexOf(URL_DELIMITER);
219: StringBuffer result = new StringBuffer(256);
220: result.append(url);
221: if (pos >= 0) {
222: // url already has parameters
223: result.append(PARAMETER_DELIMITER);
224: } else {
225: // url does not have parameters
226: result.append(URL_DELIMITER);
227: }
228: // ensure all values are of type String[]
229: Map newParams = createParameterMap(params);
230: Iterator i = newParams.entrySet().iterator();
231: while (i.hasNext()) {
232: Map.Entry entry = (Map.Entry) i.next();
233: String key = (String) entry.getKey();
234: Object value = entry.getValue();
235: String[] values = (String[]) value;
236: for (int j = 0; j < values.length; j++) {
237: String strValue = values[j];
238: if (encode) {
239: strValue = CmsEncoder.encode(strValue);
240: }
241: result.append(key);
242: result.append(PARAMETER_ASSIGNMENT);
243: result.append(strValue);
244: if ((j + 1) < values.length) {
245: result.append(PARAMETER_DELIMITER);
246: }
247: }
248: if (i.hasNext()) {
249: result.append(PARAMETER_DELIMITER);
250: }
251: }
252: return result.toString();
253: }
254:
255: /**
256: * Creates a valid request parameter map from the given map,
257: * most notably changing the values form <code>String</code>
258: * to <code>String[]</code> if required.<p>
259: *
260: * If the given parameter map is <code>null</code>, then <code>null</code> is returned.<p>
261: *
262: * @param params the map of parameters to create a parameter map from
263: * @return the created parameter map, all values will be instances of <code>String[]</code>
264: */
265: public static Map createParameterMap(Map params) {
266:
267: if (params == null) {
268: return null;
269: }
270: HashMap result = new HashMap();
271: Iterator i = params.entrySet().iterator();
272: while (i.hasNext()) {
273: Map.Entry entry = (Map.Entry) i.next();
274: String key = (String) entry.getKey();
275: Object values = entry.getValue();
276: if (values instanceof String[]) {
277: result.put(key, values);
278: } else {
279: if (values != null) {
280: result.put(key, new String[] { values.toString() });
281: }
282: }
283: }
284: return result;
285: }
286:
287: /**
288: * Parses the parameters of the given request query part and creates a parameter map out of them.<p>
289: *
290: * Please note: This does not parse a full request URI/URL, only the query part that
291: * starts after the "?". For example, in the URI <code>/system/index.html?a=b&c=d</code>,
292: * the query part is <code>a=b&c=d</code>.<p>
293: *
294: * If the given String is empty, an empty map is returned.<p>
295: *
296: * @param query the query to parse
297: * @return the parameter map created from the query
298: */
299: public static Map createParameterMap(String query) {
300:
301: if (CmsStringUtil.isEmpty(query)) {
302: // empty query
303: return new HashMap();
304: }
305: if (query.charAt(0) == URL_DELIMITER.charAt(0)) {
306: // remove leading '?' if required
307: query = query.substring(1);
308: }
309: // cut along the different parameters
310: String[] params = CmsStringUtil.splitAsArray(query,
311: PARAMETER_DELIMITER);
312: HashMap parameters = new HashMap(params.length);
313: for (int i = 0; i < params.length; i++) {
314: String key = null;
315: String value = null;
316: // get key and value, separated by a '='
317: int pos = params[i].indexOf(PARAMETER_ASSIGNMENT);
318: if (pos > 0) {
319: key = params[i].substring(0, pos);
320: value = params[i].substring(pos + 1);
321: } else if (pos < 0) {
322: key = params[i];
323: value = "";
324: }
325: // adjust the key if it starts with "amp;"
326: // this happens when "&" is used instead of a simple "&"
327: if ((key != null) && (key.startsWith(AMP))) {
328: key = key.substring(AMP.length());
329: }
330: // now make sure the values are of type String[]
331: if (key != null) {
332: String[] values = (String[]) parameters.get(key);
333: if (values == null) {
334: // this is the first value, create new array
335: values = new String[] { value };
336: } else {
337: // append to the existing value array
338: String[] copy = new String[values.length + 1];
339: System.arraycopy(values, 0, copy, 0, values.length);
340: copy[copy.length - 1] = value;
341: values = copy;
342: }
343: parameters.put(key, values);
344: }
345: }
346: return parameters;
347: }
348:
349: /**
350: * Returns all parameters of the given request
351: * as a request parameter URL String, that is in the form <code>key1=value1&key2=value2</code> etc.
352: *
353: * The result will be encoded using the <code>{@link CmsEncoder#encode(String)}</code> function.<p>
354: *
355: * @param req the request to read the parameters from
356: *
357: * @return all initialized parameters of the given request as request parameter URL String
358: */
359: public static String encodeParams(HttpServletRequest req) {
360:
361: StringBuffer result = new StringBuffer(512);
362: Map params = req.getParameterMap();
363: Iterator i = params.entrySet().iterator();
364: while (i.hasNext()) {
365: Map.Entry entry = (Map.Entry) i.next();
366: String param = (String) entry.getKey();
367: String[] values = (String[]) entry.getValue();
368: for (int j = 0; j < values.length; j++) {
369: result.append(param);
370: result.append("=");
371: result.append(CmsEncoder.encode(values[j]));
372: if ((j + 1) < values.length) {
373: result.append("&");
374: }
375: }
376: if (i.hasNext()) {
377: result.append("&");
378: }
379: }
380: return CmsEncoder.encode(result.toString());
381: }
382:
383: /**
384: * Encodes the given URI, with all parameters from the given request appended.<p>
385: *
386: * The result will be encoded using the <code>{@link CmsEncoder#encode(String)}</code> function.<p>
387: *
388: * @param req the request where to read the parameters from
389: * @param uri the URI to encode
390: * @return the encoded URI, with all parameters from the given request appended
391: */
392: public static String encodeParamsWithUri(String uri,
393: HttpServletRequest req) {
394:
395: String result;
396: String params = encodeParams(req);
397: if (CmsStringUtil.isNotEmpty(params)) {
398: result = CmsEncoder.encode(uri + "?") + params;
399: } else {
400: result = CmsEncoder.encode(uri);
401: }
402: return result;
403: }
404:
405: /**
406: * Forwards the response to the given target, which may contain parameters appended like for example <code>?a=b&c=d</code>.<p>
407: *
408: * Please note: If possible, use <code>{@link #forwardRequest(String, Map, HttpServletRequest, HttpServletResponse)}</code>
409: * where the parameters are passed as a map, since the parsing of the parameters may introduce issues with encoding
410: * and is in general much less effective.<p>
411: *
412: * The parsing of parameters will likely fail for "large values" (e.g. full blown web forms with <textarea>
413: * elements etc. Use this method only if you know that the target will just contain up to 3 parameters which
414: * are relatively short and have no encoding or line break issues.<p>
415: *
416: * @param target the target to forward to (may contain parameters like <code>?a=b&c=d</code>)
417: * @param req the request to forward
418: * @param res the response to forward
419: *
420: * @throws IOException in case the forwarding fails
421: * @throws ServletException in case the forwarding fails
422: */
423: public static void forwardRequest(String target,
424: HttpServletRequest req, HttpServletResponse res)
425: throws IOException, ServletException {
426:
427: // clear the current parameters
428: CmsUriSplitter uri = new CmsUriSplitter(target);
429: Map params = createParameterMap(uri.getQuery());
430: forwardRequest(uri.getPrefix(), params, req, res);
431: }
432:
433: /**
434: * Forwards the response to the given target, with the provided parameter map.<p>
435: *
436: * The target URI must NOT have parameters appended like for example <code>?a=b&c=d</code>.
437: * The values in the provided map must be of type <code>String[]</code>. If required, use
438: * <code>{@link #createParameterMap(Map)}</code> before calling this method to make sure
439: * all values are actually of the required array type.<p>
440: *
441: * @param target the target to forward to (may NOT contain parameters like <code>?a=b&c=d</code>)
442: * @param params the parameter map (the values must be of type <code>String[]</code>
443: * @param req the request to forward
444: * @param res the response to forward
445: *
446: * @throws IOException in case the forwarding fails
447: * @throws ServletException in case the forwarding fails
448: */
449: public static void forwardRequest(String target, Map params,
450: HttpServletRequest req, HttpServletResponse res)
451: throws IOException, ServletException {
452:
453: // cast the request back to a flex request so the parameter map can be accessed
454: CmsFlexRequest f_req = (CmsFlexRequest) req;
455: // set the parameters
456: f_req.setParameterMap(params);
457: // check for links "into" OpenCms, these may need the webapp name to be removed
458: String vfsPrefix = OpenCms.getStaticExportManager()
459: .getVfsPrefix();
460: if (target.startsWith(vfsPrefix)) {
461: // remove VFS prefix (will also work for empty vfs prefix in ROOT webapp case with proxy rules)
462: target = target.substring(vfsPrefix.length());
463: // append the servlet name
464: target = OpenCms.getSystemInfo().getServletPath() + target;
465: }
466: // forward the request
467: f_req.getRequestDispatcher(target).forward(f_req, res);
468: }
469:
470: /**
471: * Returns the value of the cookie with the given name.<p/>
472: *
473: * @param jsp the CmsJspActionElement to use
474: * @param name the name of the cookie
475: *
476: * @return the value of the cookie with the given name or null, if no cookie exists with the name
477: */
478: public static String getCookieValue(CmsJspActionElement jsp,
479: String name) {
480:
481: Cookie[] cookies = jsp.getRequest().getCookies();
482: for (int i = 0; (cookies != null) && (i < cookies.length); i++) {
483: if (name.equalsIgnoreCase(cookies[i].getName())) {
484: return cookies[i].getValue();
485: }
486: }
487: return null;
488: }
489:
490: /**
491: * Reads value from the request parameters,
492: * will return <code>null</code> if the value is not available or only white space.<p>
493: *
494: * The value of the request will also be decoded using <code>{@link CmsEncoder#decode(String)}</code>
495: * and also trimmed using <code>{@link String#trim()}</code>.<p>
496: *
497: * @param request the request to read the parameter from
498: * @param paramName the parameter name to read
499: *
500: * @return the request parameter value for the given parameter
501: */
502: public static String getNotEmptyDecodedParameter(
503: HttpServletRequest request, String paramName) {
504:
505: String result = getNotEmptyParameter(request, paramName);
506: if (result != null) {
507: result = CmsEncoder.decode(result.trim());
508: }
509: return result;
510: }
511:
512: /**
513: * Reads value from the request parameters,
514: * will return <code>null</code> if the value is not available or only white space.<p>
515: *
516: * @param request the request to read the parameter from
517: * @param paramName the parameter name to read
518: *
519: * @return the request parameter value for the given parameter
520: */
521: public static String getNotEmptyParameter(
522: HttpServletRequest request, String paramName) {
523:
524: String result = request.getParameter(paramName);
525: if (CmsStringUtil.isEmptyOrWhitespaceOnly(result)) {
526: result = null;
527: }
528: return result;
529: }
530:
531: /**
532: * Reads an object from the session of the given HTTP request.<p>
533: *
534: * A session will be initialized if the request does not currently have a session.
535: * As a result, the request will always have a session after this method has been called.<p>
536: *
537: * Will return <code>null</code> if no corresponding object is found in the session.<p>
538: *
539: * @param request the request to get the session from
540: * @param key the key of the object to read from the session
541: * @return the object received form the session, or <code>null</code>
542: */
543: public static Object getSessionValue(HttpServletRequest request,
544: String key) {
545:
546: HttpSession session = request.getSession(true);
547: return session.getAttribute(key);
548: }
549:
550: /**
551: * Parses a request of the form <code>multipart/form-data</code>.
552: *
553: * The result list will contain items of type <code>{@link FileItem}</code>.
554: * If the request is not of type <code>multipart/form-data</code>, then <code>null</code> is returned.<p>
555: *
556: * @param request the HTTP servlet request to parse
557: *
558: * @return the list of <code>{@link FileItem}</code> extracted from the multipart request,
559: * or <code>null</code> if the request was not of type <code>multipart/form-data</code>
560: */
561: public static List readMultipartFileItems(HttpServletRequest request) {
562:
563: if (!FileUploadBase.isMultipartContent(request)) {
564: return null;
565: }
566: DiskFileUpload fu = new DiskFileUpload();
567: // set encoding to correctly handle special chars (e.g. in filenames)
568: fu.setHeaderEncoding(request.getCharacterEncoding());
569: // maximum size that will be stored in memory
570: fu.setSizeThreshold(4096);
571: // the location for saving data that is larger than getSizeThreshold()
572: fu.setRepositoryPath(OpenCms.getSystemInfo()
573: .getPackagesRfsPath());
574: List result = new ArrayList();
575: try {
576: List items = fu.parseRequest(request);
577: if (items != null) {
578: result = items;
579: }
580: } catch (FileUploadException e) {
581: LOG.error(Messages.get().getBundle().key(
582: Messages.LOG_PARSE_MULIPART_REQ_FAILED_0), e);
583: }
584: return result;
585: }
586:
587: /**
588: * Creates a "standard" request parameter map from the values of a
589: * <code>multipart/form-data</code> request.<p>
590: *
591: * @param encoding the encoding to use when creating the values
592: * @param multiPartFileItems the list of parsed multi part file items
593: *
594: * @return a map containing all non-file request parameters
595: *
596: * @see #readMultipartFileItems(HttpServletRequest)
597: */
598: public static Map readParameterMapFromMultiPart(String encoding,
599: List multiPartFileItems) {
600:
601: Map parameterMap = new HashMap();
602: Iterator i = multiPartFileItems.iterator();
603: while (i.hasNext()) {
604: FileItem item = (FileItem) i.next();
605: String name = item.getFieldName();
606: String value = null;
607: if ((name != null) && (item.getName() == null)) {
608: // only put to map if current item is no file and not null
609: try {
610: value = item.getString(encoding);
611: } catch (UnsupportedEncodingException e) {
612: LOG.error(Messages.get().getBundle().key(
613: Messages.LOG_ENC_MULTIPART_REQ_ERROR_0), e);
614: value = item.getString();
615: }
616: if (parameterMap.containsKey(name)) {
617:
618: // append value to parameter values array
619: String[] oldValues = (String[]) parameterMap
620: .get(name);
621: String[] newValues = new String[oldValues.length + 1];
622: System.arraycopy(oldValues, 0, newValues, 0,
623: oldValues.length);
624: newValues[oldValues.length] = value;
625: parameterMap.put(name, newValues);
626:
627: } else {
628: parameterMap.put(name, new String[] { value });
629: }
630: }
631: }
632: return parameterMap;
633: }
634:
635: /**
636: * Redirects the response to the target link using a "301 - Moved Permanently" header.<p>
637: *
638: * This implementation will work only on JSP pages in OpenCms that use the default JSP loader implementation.<p>
639: *
640: * @param jsp the OpenCms JSP context
641: * @param target the target link
642: */
643: public static void redirectPermanently(CmsJspActionElement jsp,
644: String target) {
645:
646: String newTarget = OpenCms.getLinkManager().substituteLink(
647: jsp.getCmsObject(), target, null, true);
648: jsp.getRequest().setAttribute(
649: CmsRequestUtil.ATTRIBUTE_ERRORCODE,
650: new Integer(HttpServletResponse.SC_MOVED_PERMANENTLY));
651: jsp.getResponse().setHeader(HEADER_LOCATION, newTarget);
652: jsp.getResponse().setHeader(HEADER_CONNECTION, "close");
653: }
654:
655: /**
656: * Redirects the response to the target link.<p>
657: *
658: * Use this method instead of {@link javax.servlet.http.HttpServletResponse#sendRedirect(java.lang.String)}
659: * to avoid relative links with secure sites (and issues with apache).<p>
660: *
661: * @param jsp the OpenCms JSP context
662: * @param target the target link
663: *
664: * @throws IOException if something goes wrong during redirection
665: */
666: public static void redirectRequestSecure(CmsJspActionElement jsp,
667: String target) throws IOException {
668:
669: jsp.getResponse().sendRedirect(
670: OpenCms.getLinkManager().substituteLink(
671: jsp.getCmsObject(), target, null, true));
672: }
673:
674: /**
675: * Removes an object from the session of the given http request.<p>
676: *
677: * A session will be initialized if the request does not currently have a session.
678: * As a result, the request will always have a session after this method has been called.<p>
679: *
680: * @param request the request to get the session from
681: * @param key the key of the object to be removed from the session
682: */
683: public static void removeSessionValue(HttpServletRequest request,
684: String key) {
685:
686: HttpSession session = request.getSession(true);
687: session.removeAttribute(key);
688: }
689:
690: /**
691: * Sets the value of a specific cookie.<p>
692: * If no cookie exists with the value, a new cookie will be created.
693: *
694: * @param jsp the CmsJspActionElement to use
695: * @param name the name of the cookie
696: * @param value the value of the cookie
697: */
698: public static void setCookieValue(CmsJspActionElement jsp,
699: String name, String value) {
700:
701: Cookie[] cookies = jsp.getRequest().getCookies();
702: for (int i = 0; (cookies != null) && (i < cookies.length); i++) {
703: if (name.equalsIgnoreCase(cookies[i].getName())) {
704: cookies[i].setValue(value);
705: return;
706: }
707: }
708: Cookie cookie = new Cookie(name, value);
709: jsp.getResponse().addCookie(cookie);
710: }
711:
712: /**
713: * Sets headers to the given response to prevent client side caching.<p>
714: *
715: * The following headers are set:<p>
716: * <code>
717: * Cache-Control: max-age=0<br>
718: * Cache-Control: must-revalidate<br>
719: * Pragma: no-cache
720: * </code>
721: *
722: * @param res the request where to set the no-cache headers
723: */
724: public static void setNoCacheHeaders(HttpServletResponse res) {
725:
726: res.setHeader(CmsRequestUtil.HEADER_CACHE_CONTROL,
727: CmsRequestUtil.HEADER_VALUE_MAX_AGE + "0");
728: res.addHeader(CmsRequestUtil.HEADER_CACHE_CONTROL,
729: CmsRequestUtil.HEADER_VALUE_MUST_REVALIDATE);
730: res.setHeader(CmsRequestUtil.HEADER_PRAGMA,
731: CmsRequestUtil.HEADER_VALUE_NO_CACHE);
732: }
733:
734: /**
735: * Adds an object to the session of the given HTTP request.<p>
736: *
737: * A session will be initialized if the request does not currently have a session.
738: * As a result, the request will always have a session after this method has been called.<p>
739: *
740: * @param request the request to get the session from
741: * @param key the key of the object to be stored in the session
742: * @param value the object to be stored in the session
743: */
744: public static void setSessionValue(HttpServletRequest request,
745: String key, Object value) {
746:
747: HttpSession session = request.getSession(true);
748: session.setAttribute(key, value);
749: }
750: }
|