📄 cmsrequestutil.java
字号:
Iterator i = params.keySet().iterator();
while (i.hasNext()) {
String param = (String)i.next();
String[] values = (String[])params.get(param);
for (int j = 0; j < values.length; j++) {
result.append(param);
result.append("=");
result.append(CmsEncoder.encode(values[j]));
if ((j + 1) < values.length) {
result.append("&");
}
}
if (i.hasNext()) {
result.append("&");
}
}
return CmsEncoder.encode(result.toString());
}
/**
* Encodes the given uri, with all parameters from the given request appended.<p>
*
* The result will be encoded using the <code>{@link CmsEncoder#encode(String)}</code> function.<p>
*
* @param req the request where to read the parameters from
* @param uri the uri to encode
* @return the encoded uri, with all parameters from the given request appended
*/
public static String encodeParamsWithUri(String uri, HttpServletRequest req) {
String result;
String params = encodeParams(req);
if (CmsStringUtil.isNotEmpty(params)) {
result = CmsEncoder.encode(uri + "?") + params;
} else {
result = CmsEncoder.encode(uri);
}
return result;
}
/**
* Forwards the response to the given target, which may contain parameters appended like for example <code>?a=b&c=d</code>.<p>
*
* Please note: If possible, use <code>{@link #forwardRequest(String, Map, HttpServletRequest, HttpServletResponse)}</code>
* where the parameters are passed as a map, since the parsing of the parameters may introduce issues with encoding
* and is in general much less effective.<p>
*
* The parsing of parameters will likley fail for "large values" (e.g. full blown web forms with <textarea>
* elements etc. Use this method only if you know that the target will just contain up to 3 parameters which
* are relativly short and have no encoding or linebreak issues.<p>
*
* @param target the target to forward to (may contain parameters like <code>?a=b&c=d</code>)
* @param req the request to forward
* @param res the response to forward
*
* @throws IOException in case the forwarding fails
* @throws ServletException in case the forwarding fails
*/
public static void forwardRequest(String target, HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
// clear the current parameters
CmsUriSplitter uri = new CmsUriSplitter(target);
Map params = createParameterMap(uri.getQuery());
forwardRequest(uri.getPrefix(), params, req, res);
}
/**
* Forwards the response to the given target, with the provided parameter map.<p>
*
* The target uri must NOT have parameters appended like for example <code>?a=b&c=d</code>.
* The values in the provided map must be of type <code>String[]</code>. If required, use
* <code>{@link #createParameterMap(Map)}</code> before calling this method to make sure
* all values are actually of the required array type.<p>
*
* @param target the target to forward to (may NOT contain parameters like <code>?a=b&c=d</code>)
* @param params the parameter map (the values must be of type <code>String[]</code>
* @param req the request to forward
* @param res the response to forward
*
* @throws IOException in case the forwarding fails
* @throws ServletException in case the forwarding fails
*/
public static void forwardRequest(String target, Map params, HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
// cast the request back to a flex request so the parameter map can be accessed
CmsFlexRequest f_req = (CmsFlexRequest)req;
// set the parameters
f_req.setParameterMap(params);
// check for links "into" OpenCms, these may need the webapp name to be removed
String vfsPrefix = OpenCms.getStaticExportManager().getVfsPrefix();
if (target.startsWith(vfsPrefix)) {
// remove VFS prefix (will also work for empty vfs prefix in ROOT webapp case with proxy rules)
target = target.substring(vfsPrefix.length());
// append the servlet name
target = OpenCms.getSystemInfo().getServletPath() + target;
}
// forward the request
f_req.getRequestDispatcher(target).forward(f_req, res);
}
/**
* Returns the value of the cookie with the given name.<p/>
*
* @param jsp the CmsJspActionElement to use
* @param name the name of the cookie
*
* @return the value of the cookie with the given name or null, if no cookie exists with the name
*/
public static String getCookieValue(CmsJspActionElement jsp, String name) {
Cookie[] cookies = jsp.getRequest().getCookies();
for (int i = 0; cookies != null && i < cookies.length; i++) {
if (name.equalsIgnoreCase(cookies[i].getName())) {
return cookies[i].getValue();
}
}
return null;
}
/**
* Reads value from the request parameters,
* will return <code>null</code> if the value is not available or only white space.<p>
*
* The value of the request will also be decoded using <code>{@link CmsEncoder#decode(String)}</code>
* and also trimmed using <code>{@link String#trim()}</code>.<p>
*
* @param request the request to read the parameter from
* @param paramName the parameter name to read
*
* @return the request parameter value for the given parameter
*/
public static String getNotEmptyDecodedParameter(HttpServletRequest request, String paramName) {
String result = getNotEmptyParameter(request, paramName);
if (result != null) {
result = CmsEncoder.decode(result.trim());
}
return result;
}
/**
* Reads value from the request parameters,
* will return <code>null</code> if the value is not available or only white space.<p>
*
* @param request the request to read the parameter from
* @param paramName the parameter name to read
*
* @return the request parameter value for the given parameter
*/
public static String getNotEmptyParameter(HttpServletRequest request, String paramName) {
String result = request.getParameter(paramName);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(result)) {
result = null;
}
return result;
}
/**
* Reads an object from the session of the given http request.<p>
*
* A session will be initilaized if the request does not currently have a session.
* As a result, the request will always have a session after this method has been called.<p>
*
* Will return <code>null</code> if no corresponding object is found in the session.<p>
*
* @param request the request to get the session from
* @param key the key of the object to read from the session
* @return the object received form the session, or <code>null</code>
*/
public static Object getSessionValue(HttpServletRequest request, String key) {
HttpSession session = request.getSession(true);
return session.getAttribute(key);
}
/**
* Parses a request of the form <code>multipart/form-data</code>.
*
* The result list will contain items of type <code>{@link FileItem}</code>.
* If the request is not of type <code>multipart/form-data</code>, then <code>null</code> is returned.<p>
*
* @param request the HTTP servlet request to parse
*
* @return the list of <code>{@link FileItem}</code> extracted from the multipart request,
* or <code>null</code> if the request was not of type <code>multipart/form-data</code>
*/
public static List readMultipartFileItems(HttpServletRequest request) {
if (!FileUploadBase.isMultipartContent(request)) {
return null;
}
DiskFileUpload fu = new DiskFileUpload();
// maximum size that will be stored in memory
fu.setSizeThreshold(4096);
// the location for saving data that is larger than getSizeThreshold()
fu.setRepositoryPath(OpenCms.getSystemInfo().getPackagesRfsPath());
List result = new ArrayList();
try {
List items = fu.parseRequest(request);
if (items != null) {
result = items;
}
} catch (FileUploadException e) {
LOG.error(Messages.get().getBundle().key(Messages.LOG_PARSE_MULIPART_REQ_FAILED_0), e);
}
return result;
}
/**
* Creates a "standard" request parameter map from the values of a
* <code>multipart/form-data</code> request.<p>
*
* @param encoding the encoding to use when creating the values
* @param multiPartFileItems the list of parsed multi part file items
*
* @return a map containing all non-file request parameters
*
* @see #readMultipartFileItems(HttpServletRequest)
*/
public static Map readParameterMapFromMultiPart(String encoding, List multiPartFileItems) {
Map parameterMap = new HashMap();
Iterator i = multiPartFileItems.iterator();
while (i.hasNext()) {
FileItem item = (FileItem)i.next();
String name = item.getFieldName();
String value = null;
if (name != null && item.getName() == null) {
// only put to map if current item is no file and not null
try {
value = item.getString(encoding);
} catch (UnsupportedEncodingException e) {
LOG.error(Messages.get().getBundle().key(Messages.LOG_ENC_MULTIPART_REQ_ERROR_0), e);
value = item.getString();
}
parameterMap.put(name, new String[] {value});
}
}
return parameterMap;
}
/**
* Redirects the response to the target link.<p>
*
* Use this method instead of {@link javax.servlet.http.HttpServletResponse#sendRedirect(java.lang.String)}
* to avoid relative links with secure sites (and issues with apache).<p>
*
* @param jsp the jsp context
* @param target the target link
*
* @throws IOException if something goes wrong during redirection
*/
public static void redirectRequestSecure(CmsJspActionElement jsp, String target) throws IOException {
jsp.getResponse().sendRedirect(OpenCms.getLinkManager().substituteLink(jsp.getCmsObject(), target, null, true));
}
/**
* Removes an object from the session of the given http request.<p>
*
* A session will be initilaized if the request does not currently have a session.
* As a result, the request will always have a session after this method has been called.<p>
*
* @param request the request to get the session from
* @param key the key of the object to be removed from the session
*/
public static void removeSessionValue(HttpServletRequest request, String key) {
HttpSession session = request.getSession(true);
session.removeAttribute(key);
}
/**
* Sets the value of a specific cookie.<p>
* If no cookie exists with the value, a new cookie will be created.
*
* @param jsp the CmsJspActionElement to use
* @param name the name of the cookie
* @param value the value of the cookie
*/
public static void setCookieValue(CmsJspActionElement jsp, String name, String value) {
Cookie[] cookies = jsp.getRequest().getCookies();
for (int i = 0; cookies != null && i < cookies.length; i++) {
if (name.equalsIgnoreCase(cookies[i].getName())) {
cookies[i].setValue(value);
return;
}
}
Cookie cookie = new Cookie(name, value);
jsp.getResponse().addCookie(cookie);
}
/**
* Sets headers to the given response to prevent client side caching.<p>
*
* The following headers are set:<p>
* <code>
* Cache-Control: max-age=0<br>
* Cache-Control: must-revalidate<br>
* Pragma: no-cache
* </code>
*
* @param res the request where to set the no-cache headers
*/
public static void setNoCacheHeaders(HttpServletResponse res) {
res.setHeader(CmsRequestUtil.HEADER_CACHE_CONTROL, CmsRequestUtil.HEADER_VALUE_MAX_AGE + "0");
res.addHeader(CmsRequestUtil.HEADER_CACHE_CONTROL, CmsRequestUtil.HEADER_VALUE_MUST_REVALIDATE);
res.setHeader(CmsRequestUtil.HEADER_PRAGMA, CmsRequestUtil.HEADER_VALUE_NO_CACHE);
}
/**
* Adds an object to the session of the given http request.<p>
*
* A session will be initilaized if the request does not currently have a session.
* As a result, the request will always have a session after this method has been called.<p>
*
* @param request the request to get the session from
* @param key the key of the object to be stored in the session
* @param value the object to be stored in the session
*/
public static void setSessionValue(HttpServletRequest request, String key, Object value) {
HttpSession session = request.getSession(true);
session.setAttribute(key, value);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -