一、前言
关于springframework框架spring-web包(4.1.4)的org.springframework.web.util.WebUtils网页处理工具类,对前端请求HttpRequest(org.springframework.http.HttpRequest)、头部信息Header(org.springframework.http.HttpHeaders)、服务端servlet请求对象(org.springframework.http.server.ServletServerHttpRequest.ServletServerHttpRequest)常见逻辑处理。
二、源码说明
1. WebUtils类
package org.springframework.web.util;@b@@b@import java.io.File;@b@import java.io.FileNotFoundException;@b@import java.util.Collection;@b@import java.util.Enumeration;@b@import java.util.Map;@b@import java.util.Map.Entry;@b@import java.util.Properties;@b@import java.util.StringTokenizer;@b@import java.util.TreeMap;@b@import javax.servlet.ServletContext;@b@import javax.servlet.ServletRequest;@b@import javax.servlet.ServletRequestWrapper;@b@import javax.servlet.ServletResponse;@b@import javax.servlet.ServletResponseWrapper;@b@import javax.servlet.http.Cookie;@b@import javax.servlet.http.HttpServletRequest;@b@import javax.servlet.http.HttpSession;@b@import org.springframework.http.HttpHeaders;@b@import org.springframework.http.HttpRequest;@b@import org.springframework.http.server.ServletServerHttpRequest;@b@import org.springframework.util.Assert;@b@import org.springframework.util.CollectionUtils;@b@import org.springframework.util.LinkedMultiValueMap;@b@import org.springframework.util.MultiValueMap;@b@import org.springframework.util.ObjectUtils;@b@import org.springframework.util.StringUtils;@b@@b@public abstract class WebUtils@b@{@b@ public static final String INCLUDE_REQUEST_URI_ATTRIBUTE = "javax.servlet.include.request_uri";@b@ public static final String INCLUDE_CONTEXT_PATH_ATTRIBUTE = "javax.servlet.include.context_path";@b@ public static final String INCLUDE_SERVLET_PATH_ATTRIBUTE = "javax.servlet.include.servlet_path";@b@ public static final String INCLUDE_PATH_INFO_ATTRIBUTE = "javax.servlet.include.path_info";@b@ public static final String INCLUDE_QUERY_STRING_ATTRIBUTE = "javax.servlet.include.query_string";@b@ public static final String FORWARD_REQUEST_URI_ATTRIBUTE = "javax.servlet.forward.request_uri";@b@ public static final String FORWARD_CONTEXT_PATH_ATTRIBUTE = "javax.servlet.forward.context_path";@b@ public static final String FORWARD_SERVLET_PATH_ATTRIBUTE = "javax.servlet.forward.servlet_path";@b@ public static final String FORWARD_PATH_INFO_ATTRIBUTE = "javax.servlet.forward.path_info";@b@ public static final String FORWARD_QUERY_STRING_ATTRIBUTE = "javax.servlet.forward.query_string";@b@ public static final String ERROR_STATUS_CODE_ATTRIBUTE = "javax.servlet.error.status_code";@b@ public static final String ERROR_EXCEPTION_TYPE_ATTRIBUTE = "javax.servlet.error.exception_type";@b@ public static final String ERROR_MESSAGE_ATTRIBUTE = "javax.servlet.error.message";@b@ public static final String ERROR_EXCEPTION_ATTRIBUTE = "javax.servlet.error.exception";@b@ public static final String ERROR_REQUEST_URI_ATTRIBUTE = "javax.servlet.error.request_uri";@b@ public static final String ERROR_SERVLET_NAME_ATTRIBUTE = "javax.servlet.error.servlet_name";@b@ public static final String CONTENT_TYPE_CHARSET_PREFIX = ";charset=";@b@ public static final String DEFAULT_CHARACTER_ENCODING = "ISO-8859-1";@b@ public static final String TEMP_DIR_CONTEXT_ATTRIBUTE = "javax.servlet.context.tempdir";@b@ public static final String HTML_ESCAPE_CONTEXT_PARAM = "defaultHtmlEscape";@b@ public static final String RESPONSE_ENCODED_HTML_ESCAPE_CONTEXT_PARAM = "responseEncodedHtmlEscape";@b@ public static final String WEB_APP_ROOT_KEY_PARAM = "webAppRootKey";@b@ public static final String DEFAULT_WEB_APP_ROOT_KEY = "webapp.root";@b@ public static final String[] SUBMIT_IMAGE_SUFFIXES = { ".x", ".y" };@b@ public static final String SESSION_MUTEX_ATTRIBUTE = WebUtils.class.getName() + ".MUTEX";@b@@b@ public static void setWebAppRootSystemProperty(ServletContext servletContext)@b@ throws IllegalStateException@b@ {@b@ Assert.notNull(servletContext, "ServletContext must not be null");@b@ String root = servletContext.getRealPath("/");@b@ if (root == null) {@b@ throw new IllegalStateException("Cannot set web app root system property when WAR file is not expanded");@b@ }@b@@b@ String param = servletContext.getInitParameter("webAppRootKey");@b@ String key = (param != null) ? param : "webapp.root";@b@ String oldValue = System.getProperty(key);@b@ if ((oldValue != null) && (!(StringUtils.pathEquals(oldValue, root)))) {@b@ throw new IllegalStateException("Web app root system property already set to different value: '" + key + "' = [" + oldValue + "] instead of [" + root + "] - Choose unique values for the 'webAppRootKey' context-param in your web.xml files!");@b@ }@b@@b@ System.setProperty(key, root);@b@ servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]");@b@ }@b@@b@ public static void removeWebAppRootSystemProperty(ServletContext servletContext)@b@ {@b@ Assert.notNull(servletContext, "ServletContext must not be null");@b@ String param = servletContext.getInitParameter("webAppRootKey");@b@ String key = (param != null) ? param : "webapp.root";@b@ System.getProperties().remove(key);@b@ }@b@@b@ @Deprecated@b@ public static boolean isDefaultHtmlEscape(ServletContext servletContext)@b@ {@b@ if (servletContext == null)@b@ return false;@b@@b@ String param = servletContext.getInitParameter("defaultHtmlEscape");@b@ return Boolean.valueOf(param).booleanValue();@b@ }@b@@b@ public static Boolean getDefaultHtmlEscape(ServletContext servletContext)@b@ {@b@ if (servletContext == null)@b@ return null;@b@@b@ String param = servletContext.getInitParameter("defaultHtmlEscape");@b@ return ((StringUtils.hasText(param)) ? Boolean.valueOf(param) : null);@b@ }@b@@b@ public static Boolean getResponseEncodedHtmlEscape(ServletContext servletContext)@b@ {@b@ if (servletContext == null)@b@ return null;@b@@b@ String param = servletContext.getInitParameter("responseEncodedHtmlEscape");@b@ return ((StringUtils.hasText(param)) ? Boolean.valueOf(param) : null);@b@ }@b@@b@ public static File getTempDir(ServletContext servletContext)@b@ {@b@ Assert.notNull(servletContext, "ServletContext must not be null");@b@ return ((File)servletContext.getAttribute("javax.servlet.context.tempdir"));@b@ }@b@@b@ public static String getRealPath(ServletContext servletContext, String path)@b@ throws FileNotFoundException@b@ {@b@ Assert.notNull(servletContext, "ServletContext must not be null");@b@@b@ if (!(path.startsWith("/")))@b@ path = "/" + path;@b@@b@ String realPath = servletContext.getRealPath(path);@b@ if (realPath == null) {@b@ throw new FileNotFoundException("ServletContext resource [" + path + "] cannot be resolved to absolute file path - web application archive not expanded?");@b@ }@b@@b@ return realPath;@b@ }@b@@b@ public static String getSessionId(HttpServletRequest request)@b@ {@b@ Assert.notNull(request, "Request must not be null");@b@ HttpSession session = request.getSession(false);@b@ return ((session != null) ? session.getId() : null);@b@ }@b@@b@ public static Object getSessionAttribute(HttpServletRequest request, String name)@b@ {@b@ Assert.notNull(request, "Request must not be null");@b@ HttpSession session = request.getSession(false);@b@ return ((session != null) ? session.getAttribute(name) : null);@b@ }@b@@b@ public static Object getRequiredSessionAttribute(HttpServletRequest request, String name)@b@ throws IllegalStateException@b@ {@b@ Object attr = getSessionAttribute(request, name);@b@ if (attr == null)@b@ throw new IllegalStateException("No session attribute '" + name + "' found");@b@@b@ return attr;@b@ }@b@@b@ public static void setSessionAttribute(HttpServletRequest request, String name, Object value)@b@ {@b@ Assert.notNull(request, "Request must not be null");@b@ if (value != null) {@b@ request.getSession().setAttribute(name, value);@b@ }@b@ else {@b@ HttpSession session = request.getSession(false);@b@ if (session != null)@b@ session.removeAttribute(name);@b@ }@b@ }@b@@b@ @Deprecated@b@ public static Object getOrCreateSessionAttribute(HttpSession session, String name, Class<?> clazz)@b@ throws IllegalArgumentException@b@ {@b@ Assert.notNull(session, "Session must not be null");@b@ Object sessionObject = session.getAttribute(name);@b@ if (sessionObject == null) {@b@ try {@b@ sessionObject = clazz.newInstance();@b@ }@b@ catch (InstantiationException ex)@b@ {@b@ throw new IllegalArgumentException("Could not instantiate class [" + clazz@b@ .getName() + "] for session attribute '" + name + "': " + ex@b@ .getMessage());@b@ }@b@ catch (IllegalAccessException ex)@b@ {@b@ throw new IllegalArgumentException("Could not access default constructor of class [" + clazz@b@ .getName() + "] for session attribute '" + name + "': " + ex@b@ .getMessage());@b@ }@b@ session.setAttribute(name, sessionObject);@b@ }@b@ return sessionObject;@b@ }@b@@b@ public static Object getSessionMutex(HttpSession session)@b@ {@b@ Assert.notNull(session, "Session must not be null");@b@ Object mutex = session.getAttribute(SESSION_MUTEX_ATTRIBUTE);@b@ if (mutex == null)@b@ mutex = session;@b@@b@ return mutex;@b@ }@b@@b@ public static <T> T getNativeRequest(ServletRequest request, Class<T> requiredType)@b@ {@b@ if (requiredType != null) {@b@ if (requiredType.isInstance(request))@b@ return request;@b@@b@ if (request instanceof ServletRequestWrapper)@b@ return getNativeRequest(((ServletRequestWrapper)request).getRequest(), requiredType);@b@ }@b@@b@ return null;@b@ }@b@@b@ public static <T> T getNativeResponse(ServletResponse response, Class<T> requiredType)@b@ {@b@ if (requiredType != null) {@b@ if (requiredType.isInstance(response))@b@ return response;@b@@b@ if (response instanceof ServletResponseWrapper)@b@ return getNativeResponse(((ServletResponseWrapper)response).getResponse(), requiredType);@b@ }@b@@b@ return null;@b@ }@b@@b@ public static boolean isIncludeRequest(ServletRequest request)@b@ {@b@ return (request.getAttribute("javax.servlet.include.request_uri") != null);@b@ }@b@@b@ public static void exposeErrorRequestAttributes(HttpServletRequest request, Throwable ex, String servletName)@b@ {@b@ exposeRequestAttributeIfNotPresent(request, "javax.servlet.error.status_code", Integer.valueOf(200));@b@ exposeRequestAttributeIfNotPresent(request, "javax.servlet.error.exception_type", ex.getClass());@b@ exposeRequestAttributeIfNotPresent(request, "javax.servlet.error.message", ex.getMessage());@b@ exposeRequestAttributeIfNotPresent(request, "javax.servlet.error.exception", ex);@b@ exposeRequestAttributeIfNotPresent(request, "javax.servlet.error.request_uri", request.getRequestURI());@b@ exposeRequestAttributeIfNotPresent(request, "javax.servlet.error.servlet_name", servletName);@b@ }@b@@b@ private static void exposeRequestAttributeIfNotPresent(ServletRequest request, String name, Object value)@b@ {@b@ if (request.getAttribute(name) == null)@b@ request.setAttribute(name, value);@b@ }@b@@b@ public static void clearErrorRequestAttributes(HttpServletRequest request)@b@ {@b@ request.removeAttribute("javax.servlet.error.status_code");@b@ request.removeAttribute("javax.servlet.error.exception_type");@b@ request.removeAttribute("javax.servlet.error.message");@b@ request.removeAttribute("javax.servlet.error.exception");@b@ request.removeAttribute("javax.servlet.error.request_uri");@b@ request.removeAttribute("javax.servlet.error.servlet_name");@b@ }@b@@b@ @Deprecated@b@ public static void exposeRequestAttributes(ServletRequest request, Map<String, ?> attributes)@b@ {@b@ Assert.notNull(request, "Request must not be null");@b@ Assert.notNull(attributes, "Attributes Map must not be null");@b@ for (Map.Entry entry : attributes.entrySet())@b@ request.setAttribute((String)entry.getKey(), entry.getValue());@b@ }@b@@b@ public static Cookie getCookie(HttpServletRequest request, String name)@b@ {@b@ Cookie[] arrayOfCookie1;@b@ int j;@b@ Assert.notNull(request, "Request must not be null");@b@ Cookie[] cookies = request.getCookies();@b@ if (cookies != null) {@b@ arrayOfCookie1 = cookies; int i = arrayOfCookie1.length; for (j = 0; j < i; ++j) { Cookie cookie = arrayOfCookie1[j];@b@ if (name.equals(cookie.getName()))@b@ return cookie;@b@ }@b@ }@b@@b@ return null;@b@ }@b@@b@ public static boolean hasSubmitParameter(ServletRequest request, String name)@b@ {@b@ Assert.notNull(request, "Request must not be null");@b@ if (request.getParameter(name) != null)@b@ return true;@b@@b@ String[] arrayOfString = SUBMIT_IMAGE_SUFFIXES; int i = arrayOfString.length; for (int j = 0; j < i; ++j) { String suffix = arrayOfString[j];@b@ if (request.getParameter(name + suffix) != null)@b@ return true;@b@ }@b@@b@ return false;@b@ }@b@@b@ public static String findParameterValue(ServletRequest request, String name)@b@ {@b@ return findParameterValue(request.getParameterMap(), name);@b@ }@b@@b@ public static String findParameterValue(Map<String, ?> parameters, String name)@b@ {@b@ Object value = parameters.get(name);@b@ if (value instanceof String[]) {@b@ String[] values = (String[])(String[])value;@b@ return ((values.length > 0) ? values[0] : null);@b@ }@b@ if (value != null) {@b@ return value.toString();@b@ }@b@@b@ String prefix = name + "_";@b@ for (String paramName : parameters.keySet())@b@ if (paramName.startsWith(prefix))@b@ {@b@ String[] arrayOfString1 = SUBMIT_IMAGE_SUFFIXES; int i = arrayOfString1.length; for (int j = 0; j < i; ++j) { String suffix = arrayOfString1[j];@b@ if (paramName.endsWith(suffix))@b@ return paramName.substring(prefix.length(), paramName.length() - suffix.length());@b@ }@b@@b@ return paramName.substring(prefix.length());@b@ }@b@@b@@b@ return null;@b@ }@b@@b@ public static Map<String, Object> getParametersStartingWith(ServletRequest request, String prefix)@b@ {@b@ Assert.notNull(request, "Request must not be null");@b@ Enumeration paramNames = request.getParameterNames();@b@ Map params = new TreeMap();@b@ if (prefix == null)@b@ prefix = "";@b@@b@ while ((paramNames != null) && (paramNames.hasMoreElements())) {@b@ String paramName = (String)paramNames.nextElement();@b@ if (("".equals(prefix)) || (paramName.startsWith(prefix))) {@b@ String unprefixed = paramName.substring(prefix.length());@b@ String[] values = request.getParameterValues(paramName);@b@ if (values != null) { if (values.length == 0) { continue;@b@ }@b@@b@ if (values.length > 1) {@b@ params.put(unprefixed, values);@b@ }@b@ else@b@ params.put(unprefixed, values[0]);@b@ }@b@ }@b@ }@b@ return params;@b@ }@b@@b@ @Deprecated@b@ public static int getTargetPage(ServletRequest request, String paramPrefix, int currentPage)@b@ {@b@ Enumeration paramNames = request.getParameterNames();@b@ while (paramNames.hasMoreElements()) {@b@ String paramName = (String)paramNames.nextElement();@b@ if (paramName.startsWith(paramPrefix)) {@b@ for (int i = 0; i < SUBMIT_IMAGE_SUFFIXES.length; ++i) {@b@ String suffix = SUBMIT_IMAGE_SUFFIXES[i];@b@ if (paramName.endsWith(suffix))@b@ paramName = paramName.substring(0, paramName.length() - suffix.length());@b@ }@b@@b@ return Integer.parseInt(paramName.substring(paramPrefix.length()));@b@ }@b@ }@b@ return currentPage;@b@ }@b@@b@ @Deprecated@b@ public static String extractFilenameFromUrlPath(String urlPath)@b@ {@b@ String filename = extractFullFilenameFromUrlPath(urlPath);@b@ int dotIndex = filename.lastIndexOf(46);@b@ if (dotIndex != -1)@b@ filename = filename.substring(0, dotIndex);@b@@b@ return filename;@b@ }@b@@b@ @Deprecated@b@ public static String extractFullFilenameFromUrlPath(String urlPath)@b@ {@b@ int end = urlPath.indexOf(63);@b@ if (end == -1) {@b@ end = urlPath.indexOf(35);@b@ if (end == -1)@b@ end = urlPath.length();@b@ }@b@@b@ int begin = urlPath.lastIndexOf(47, end) + 1;@b@ int paramIndex = urlPath.indexOf(59, begin);@b@ end = ((paramIndex != -1) && (paramIndex < end)) ? paramIndex : end;@b@ return urlPath.substring(begin, end);@b@ }@b@@b@ public static MultiValueMap<String, String> parseMatrixVariables(String matrixVariables)@b@ {@b@ MultiValueMap result = new LinkedMultiValueMap();@b@ if (!(StringUtils.hasText(matrixVariables)))@b@ return result;@b@@b@ StringTokenizer pairs = new StringTokenizer(matrixVariables, ";");@b@ while (pairs.hasMoreTokens()) {@b@ String name;@b@ String[] arrayOfString;@b@ int j;@b@ String pair = pairs.nextToken();@b@ int index = pair.indexOf(61);@b@ if (index != -1) {@b@ name = pair.substring(0, index);@b@ String rawValue = pair.substring(index + 1);@b@ arrayOfString = StringUtils.commaDelimitedListToStringArray(rawValue); int i = arrayOfString.length; for (j = 0; j < i; ++j) { String value = arrayOfString[j];@b@ result.add(name, value);@b@ }@b@ }@b@ else {@b@ result.add(pair, "");@b@ }@b@ }@b@ return result;@b@ }@b@@b@ public static boolean isValidOrigin(HttpRequest request, Collection<String> allowedOrigins)@b@ {@b@ Assert.notNull(request, "Request must not be null");@b@ Assert.notNull(allowedOrigins, "Allowed origins must not be null");@b@@b@ String origin = request.getHeaders().getOrigin();@b@ if ((origin == null) || (allowedOrigins.contains("*")))@b@ return true;@b@@b@ if (CollectionUtils.isEmpty(allowedOrigins)) {@b@ return isSameOrigin(request);@b@ }@b@@b@ return allowedOrigins.contains(origin);@b@ }@b@@b@ public static boolean isSameOrigin(HttpRequest request)@b@ {@b@ UriComponentsBuilder urlBuilder;@b@ String origin = request.getHeaders().getOrigin();@b@ if (origin == null) {@b@ return true;@b@ }@b@@b@ if (request instanceof ServletServerHttpRequest)@b@ {@b@ HttpServletRequest servletRequest = ((ServletServerHttpRequest)request).getServletRequest();@b@@b@ urlBuilder = new UriComponentsBuilder()@b@ .scheme(servletRequest@b@ .getScheme())@b@ .host(servletRequest@b@ .getServerName())@b@ .port(servletRequest@b@ .getServerPort())@b@ .adaptFromForwardedHeaders(request@b@ .getHeaders());@b@ }@b@ else {@b@ urlBuilder = UriComponentsBuilder.fromHttpRequest(request);@b@ }@b@ UriComponents actualUrl = urlBuilder.build();@b@ UriComponents originUrl = UriComponentsBuilder.fromOriginHeader(origin).build();@b@ return ((ObjectUtils.nullSafeEquals(actualUrl.getHost(), originUrl.getHost())) && @b@ (getPort(actualUrl) == @b@ getPort(originUrl)));@b@ }@b@@b@ private static int getPort(UriComponents uri) {@b@ int port = uri.getPort();@b@ if (port == -1)@b@ if (("http".equals(uri.getScheme())) || ("ws".equals(uri.getScheme()))) {@b@ port = 80;@b@ }@b@ else if (("https".equals(uri.getScheme())) || ("wss".equals(uri.getScheme())))@b@ port = 443;@b@@b@@b@ return port;@b@ }@b@}
2. HttpHeaders、HttpRequest、HttpMethod类及接口
package org.springframework.http;@b@@b@import java.io.Serializable;@b@import java.net.URI;@b@import java.nio.charset.Charset;@b@import java.text.ParseException;@b@import java.text.SimpleDateFormat;@b@import java.util.ArrayList;@b@import java.util.Collection;@b@import java.util.Collections;@b@import java.util.Date;@b@import java.util.EnumSet;@b@import java.util.Iterator;@b@import java.util.LinkedHashMap;@b@import java.util.LinkedList;@b@import java.util.List;@b@import java.util.Locale;@b@import java.util.Map;@b@import java.util.Map.Entry;@b@import java.util.Set;@b@import java.util.TimeZone;@b@import java.util.regex.Matcher;@b@import java.util.regex.Pattern;@b@import org.springframework.util.Assert;@b@import org.springframework.util.LinkedCaseInsensitiveMap;@b@import org.springframework.util.MultiValueMap;@b@import org.springframework.util.StringUtils;@b@@b@public class HttpHeaders@b@ implements MultiValueMap<String, String>, Serializable@b@{@b@ private static final long serialVersionUID = -8578554704772377436L;@b@ public static final String ACCEPT = "Accept";@b@ public static final String ACCEPT_CHARSET = "Accept-Charset";@b@ public static final String ACCEPT_ENCODING = "Accept-Encoding";@b@ public static final String ACCEPT_LANGUAGE = "Accept-Language";@b@ public static final String ACCEPT_RANGES = "Accept-Ranges";@b@ public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";@b@ public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";@b@ public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";@b@ public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";@b@ public static final String ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers";@b@ public static final String ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age";@b@ public static final String ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers";@b@ public static final String ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method";@b@ public static final String AGE = "Age";@b@ public static final String ALLOW = "Allow";@b@ public static final String AUTHORIZATION = "Authorization";@b@ public static final String CACHE_CONTROL = "Cache-Control";@b@ public static final String CONNECTION = "Connection";@b@ public static final String CONTENT_ENCODING = "Content-Encoding";@b@ public static final String CONTENT_DISPOSITION = "Content-Disposition";@b@ public static final String CONTENT_LANGUAGE = "Content-Language";@b@ public static final String CONTENT_LENGTH = "Content-Length";@b@ public static final String CONTENT_LOCATION = "Content-Location";@b@ public static final String CONTENT_RANGE = "Content-Range";@b@ public static final String CONTENT_TYPE = "Content-Type";@b@ public static final String COOKIE = "Cookie";@b@ public static final String DATE = "Date";@b@ public static final String ETAG = "ETag";@b@ public static final String EXPECT = "Expect";@b@ public static final String EXPIRES = "Expires";@b@ public static final String FROM = "From";@b@ public static final String HOST = "Host";@b@ public static final String IF_MATCH = "If-Match";@b@ public static final String IF_MODIFIED_SINCE = "If-Modified-Since";@b@ public static final String IF_NONE_MATCH = "If-None-Match";@b@ public static final String IF_RANGE = "If-Range";@b@ public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since";@b@ public static final String LAST_MODIFIED = "Last-Modified";@b@ public static final String LINK = "Link";@b@ public static final String LOCATION = "Location";@b@ public static final String MAX_FORWARDS = "Max-Forwards";@b@ public static final String ORIGIN = "Origin";@b@ public static final String PRAGMA = "Pragma";@b@ public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate";@b@ public static final String PROXY_AUTHORIZATION = "Proxy-Authorization";@b@ public static final String RANGE = "Range";@b@ public static final String REFERER = "Referer";@b@ public static final String RETRY_AFTER = "Retry-After";@b@ public static final String SERVER = "Server";@b@ public static final String SET_COOKIE = "Set-Cookie";@b@ public static final String SET_COOKIE2 = "Set-Cookie2";@b@ public static final String TE = "TE";@b@ public static final String TRAILER = "Trailer";@b@ public static final String TRANSFER_ENCODING = "Transfer-Encoding";@b@ public static final String UPGRADE = "Upgrade";@b@ public static final String USER_AGENT = "User-Agent";@b@ public static final String VARY = "Vary";@b@ public static final String VIA = "Via";@b@ public static final String WARNING = "Warning";@b@ public static final String WWW_AUTHENTICATE = "WWW-Authenticate";@b@ private static final String[] DATE_FORMATS = { "EEE, dd MMM yyyy HH:mm:ss zzz", "EEE, dd-MMM-yy HH:mm:ss zzz", "EEE MMM dd HH:mm:ss yyyy" };@b@ private static final Pattern ETAG_HEADER_VALUE_PATTERN = Pattern.compile("\\*|\\s*((W\\/)?(\"[^\"]*\"))\\s*,?");@b@ private static TimeZone GMT = TimeZone.getTimeZone("GMT");@b@ private final Map<String, List<String>> headers;@b@@b@ public HttpHeaders()@b@ {@b@ this(new LinkedCaseInsensitiveMap(8, Locale.ENGLISH), false);@b@ }@b@@b@ private HttpHeaders(Map<String, List<String>> headers, boolean readOnly)@b@ {@b@ Assert.notNull(headers, "'headers' must not be null");@b@ if (readOnly)@b@ {@b@ Map map = new LinkedCaseInsensitiveMap(headers@b@ .size(), Locale.ENGLISH);@b@ for (Map.Entry entry : headers.entrySet()) {@b@ List values = Collections.unmodifiableList((List)entry.getValue());@b@ map.put(entry.getKey(), values);@b@ }@b@ this.headers = Collections.unmodifiableMap(map);@b@ }@b@ else {@b@ this.headers = headers;@b@ }@b@ }@b@@b@ public void setAccept(List<MediaType> acceptableMediaTypes)@b@ {@b@ set("Accept", MediaType.toString(acceptableMediaTypes));@b@ }@b@@b@ public List<MediaType> getAccept()@b@ {@b@ return MediaType.parseMediaTypes(get("Accept"));@b@ }@b@@b@ public void setAccessControlAllowCredentials(boolean allowCredentials)@b@ {@b@ set("Access-Control-Allow-Credentials", Boolean.toString(allowCredentials));@b@ }@b@@b@ public boolean getAccessControlAllowCredentials()@b@ {@b@ return Boolean.parseBoolean(getFirst("Access-Control-Allow-Credentials"));@b@ }@b@@b@ public void setAccessControlAllowHeaders(List<String> allowedHeaders)@b@ {@b@ set("Access-Control-Allow-Headers", toCommaDelimitedString(allowedHeaders));@b@ }@b@@b@ public List<String> getAccessControlAllowHeaders()@b@ {@b@ return getValuesAsList("Access-Control-Allow-Headers");@b@ }@b@@b@ public void setAccessControlAllowMethods(List<HttpMethod> allowedMethods)@b@ {@b@ set("Access-Control-Allow-Methods", StringUtils.collectionToCommaDelimitedString(allowedMethods));@b@ }@b@@b@ public List<HttpMethod> getAccessControlAllowMethods()@b@ {@b@ String[] arrayOfString1;@b@ int j;@b@ List result = new ArrayList();@b@ String value = getFirst("Access-Control-Allow-Methods");@b@ if (value != null) {@b@ String[] tokens = StringUtils.tokenizeToStringArray(value, ",");@b@ arrayOfString1 = tokens; int i = arrayOfString1.length; for (j = 0; j < i; ++j) { String token = arrayOfString1[j];@b@ HttpMethod resolved = HttpMethod.resolve(token);@b@ if (resolved != null)@b@ result.add(resolved);@b@ }@b@ }@b@@b@ return result;@b@ }@b@@b@ public void setAccessControlAllowOrigin(String allowedOrigin)@b@ {@b@ set("Access-Control-Allow-Origin", allowedOrigin);@b@ }@b@@b@ public String getAccessControlAllowOrigin()@b@ {@b@ return getFieldValues("Access-Control-Allow-Origin");@b@ }@b@@b@ public void setAccessControlExposeHeaders(List<String> exposedHeaders)@b@ {@b@ set("Access-Control-Expose-Headers", toCommaDelimitedString(exposedHeaders));@b@ }@b@@b@ public List<String> getAccessControlExposeHeaders()@b@ {@b@ return getValuesAsList("Access-Control-Expose-Headers");@b@ }@b@@b@ public void setAccessControlMaxAge(long maxAge)@b@ {@b@ set("Access-Control-Max-Age", Long.toString(maxAge));@b@ }@b@@b@ public long getAccessControlMaxAge()@b@ {@b@ String value = getFirst("Access-Control-Max-Age");@b@ return ((value != null) ? Long.parseLong(value) : -1L);@b@ }@b@@b@ public void setAccessControlRequestHeaders(List<String> requestHeaders)@b@ {@b@ set("Access-Control-Request-Headers", toCommaDelimitedString(requestHeaders));@b@ }@b@@b@ public List<String> getAccessControlRequestHeaders()@b@ {@b@ return getValuesAsList("Access-Control-Request-Headers");@b@ }@b@@b@ public void setAccessControlRequestMethod(HttpMethod requestMethod)@b@ {@b@ set("Access-Control-Request-Method", requestMethod.name());@b@ }@b@@b@ public HttpMethod getAccessControlRequestMethod()@b@ {@b@ return HttpMethod.resolve(getFirst("Access-Control-Request-Method"));@b@ }@b@@b@ public void setAcceptCharset(List<Charset> acceptableCharsets)@b@ {@b@ StringBuilder builder = new StringBuilder();@b@ for (Iterator iterator = acceptableCharsets.iterator(); iterator.hasNext(); ) {@b@ Charset charset = (Charset)iterator.next();@b@ builder.append(charset.name().toLowerCase(Locale.ENGLISH));@b@ if (iterator.hasNext())@b@ builder.append(", ");@b@ }@b@@b@ set("Accept-Charset", builder.toString());@b@ }@b@@b@ public List<Charset> getAcceptCharset()@b@ {@b@ String value = getFirst("Accept-Charset");@b@ if (value != null) {@b@ String[] tokens = StringUtils.tokenizeToStringArray(value, ",");@b@ List result = new ArrayList(tokens.length);@b@ String[] arrayOfString1 = tokens; int i = arrayOfString1.length; for (int j = 0; j < i; ++j) { String charsetName;@b@ String token = arrayOfString1[j];@b@ int paramIdx = token.indexOf(59);@b@@b@ if (paramIdx == -1) {@b@ charsetName = token;@b@ }@b@ else@b@ charsetName = token.substring(0, paramIdx);@b@@b@ if (!(charsetName.equals("*")))@b@ result.add(Charset.forName(charsetName));@b@ }@b@@b@ return result;@b@ }@b@@b@ return Collections.emptyList();@b@ }@b@@b@ public void setAllow(Set<HttpMethod> allowedMethods)@b@ {@b@ set("Allow", StringUtils.collectionToCommaDelimitedString(allowedMethods));@b@ }@b@@b@ public Set<HttpMethod> getAllow()@b@ {@b@ String value = getFirst("Allow");@b@ if (!(StringUtils.isEmpty(value))) {@b@ String[] tokens = StringUtils.tokenizeToStringArray(value, ",");@b@ List result = new ArrayList(tokens.length);@b@ String[] arrayOfString1 = tokens; int i = arrayOfString1.length; for (int j = 0; j < i; ++j) { String token = arrayOfString1[j];@b@ HttpMethod resolved = HttpMethod.resolve(token);@b@ if (resolved != null)@b@ result.add(resolved);@b@ }@b@@b@ return EnumSet.copyOf(result);@b@ }@b@@b@ return EnumSet.noneOf(HttpMethod.class);@b@ }@b@@b@ public void setCacheControl(String cacheControl)@b@ {@b@ set("Cache-Control", cacheControl);@b@ }@b@@b@ public String getCacheControl()@b@ {@b@ return getFieldValues("Cache-Control");@b@ }@b@@b@ public void setConnection(String connection)@b@ {@b@ set("Connection", connection);@b@ }@b@@b@ public void setConnection(List<String> connection)@b@ {@b@ set("Connection", toCommaDelimitedString(connection));@b@ }@b@@b@ public List<String> getConnection()@b@ {@b@ return getValuesAsList("Connection");@b@ }@b@@b@ public void setContentDispositionFormData(String name, String filename)@b@ {@b@ Assert.notNull(name, "'name' must not be null");@b@ StringBuilder builder = new StringBuilder("form-data; name=\"");@b@ builder.append(name).append('"');@b@ if (filename != null) {@b@ builder.append("; filename=\"");@b@ builder.append(filename).append('"');@b@ }@b@ set("Content-Disposition", builder.toString());@b@ }@b@@b@ @Deprecated@b@ public void setContentDispositionFormData(String name, String filename, Charset charset)@b@ {@b@ Assert.notNull(name, "'name' must not be null");@b@ StringBuilder builder = new StringBuilder("form-data; name=\"");@b@ builder.append(name).append('"');@b@ if (filename != null)@b@ if ((charset == null) || (charset.name().equals("US-ASCII"))) {@b@ builder.append("; filename=\"");@b@ builder.append(filename).append('"');@b@ }@b@ else {@b@ builder.append("; filename*=");@b@ builder.append(encodeHeaderFieldParam(filename, charset));@b@ }@b@@b@ set("Content-Disposition", builder.toString());@b@ }@b@@b@ public void setContentLength(long contentLength)@b@ {@b@ set("Content-Length", Long.toString(contentLength));@b@ }@b@@b@ public long getContentLength()@b@ {@b@ String value = getFirst("Content-Length");@b@ return ((value != null) ? Long.parseLong(value) : -1L);@b@ }@b@@b@ public void setContentType(MediaType mediaType)@b@ {@b@ Assert.isTrue(!(mediaType.isWildcardType()), "'Content-Type' cannot contain wildcard type '*'");@b@ Assert.isTrue(!(mediaType.isWildcardSubtype()), "'Content-Type' cannot contain wildcard subtype '*'");@b@ set("Content-Type", mediaType.toString());@b@ }@b@@b@ public MediaType getContentType()@b@ {@b@ String value = getFirst("Content-Type");@b@ return ((StringUtils.hasLength(value)) ? MediaType.parseMediaType(value) : null);@b@ }@b@@b@ public void setDate(long date)@b@ {@b@ setDate("Date", date);@b@ }@b@@b@ public long getDate()@b@ {@b@ return getFirstDate("Date");@b@ }@b@@b@ public void setETag(String etag)@b@ {@b@ if (etag != null) {@b@ Assert.isTrue((etag.startsWith("\"")) || (etag.startsWith("W/")), "Invalid ETag: does not start with W/ or \"");@b@@b@ Assert.isTrue(etag.endsWith("\""), "Invalid ETag: does not end with \"");@b@ }@b@ set("ETag", etag);@b@ }@b@@b@ public String getETag()@b@ {@b@ return getFirst("ETag");@b@ }@b@@b@ public void setExpires(long expires)@b@ {@b@ setDate("Expires", expires);@b@ }@b@@b@ public long getExpires()@b@ {@b@ return getFirstDate("Expires", false);@b@ }@b@@b@ public void setIfMatch(String ifMatch)@b@ {@b@ set("If-Match", ifMatch);@b@ }@b@@b@ public void setIfMatch(List<String> ifMatchList)@b@ {@b@ set("If-Match", toCommaDelimitedString(ifMatchList));@b@ }@b@@b@ public List<String> getIfMatch()@b@ {@b@ return getETagValuesAsList("If-Match");@b@ }@b@@b@ public void setIfModifiedSince(long ifModifiedSince)@b@ {@b@ setDate("If-Modified-Since", ifModifiedSince);@b@ }@b@@b@ public long getIfModifiedSince()@b@ {@b@ return getFirstDate("If-Modified-Since", false);@b@ }@b@@b@ public void setIfNoneMatch(String ifNoneMatch)@b@ {@b@ set("If-None-Match", ifNoneMatch);@b@ }@b@@b@ public void setIfNoneMatch(List<String> ifNoneMatchList)@b@ {@b@ set("If-None-Match", toCommaDelimitedString(ifNoneMatchList));@b@ }@b@@b@ public List<String> getIfNoneMatch()@b@ {@b@ return getETagValuesAsList("If-None-Match");@b@ }@b@@b@ public void setIfUnmodifiedSince(long ifUnmodifiedSince)@b@ {@b@ setDate("If-Unmodified-Since", ifUnmodifiedSince);@b@ }@b@@b@ public long getIfUnmodifiedSince()@b@ {@b@ return getFirstDate("If-Unmodified-Since", false);@b@ }@b@@b@ public void setLastModified(long lastModified)@b@ {@b@ setDate("Last-Modified", lastModified);@b@ }@b@@b@ public long getLastModified()@b@ {@b@ return getFirstDate("Last-Modified", false);@b@ }@b@@b@ public void setLocation(URI location)@b@ {@b@ set("Location", location.toASCIIString());@b@ }@b@@b@ public URI getLocation()@b@ {@b@ String value = getFirst("Location");@b@ return ((value != null) ? URI.create(value) : null);@b@ }@b@@b@ public void setOrigin(String origin)@b@ {@b@ set("Origin", origin);@b@ }@b@@b@ public String getOrigin()@b@ {@b@ return getFirst("Origin");@b@ }@b@@b@ public void setPragma(String pragma)@b@ {@b@ set("Pragma", pragma);@b@ }@b@@b@ public String getPragma()@b@ {@b@ return getFirst("Pragma");@b@ }@b@@b@ public void setRange(List<HttpRange> ranges)@b@ {@b@ String value = HttpRange.toString(ranges);@b@ set("Range", value);@b@ }@b@@b@ public List<HttpRange> getRange()@b@ {@b@ String value = getFirst("Range");@b@ return HttpRange.parseRanges(value);@b@ }@b@@b@ public void setUpgrade(String upgrade)@b@ {@b@ set("Upgrade", upgrade);@b@ }@b@@b@ public String getUpgrade()@b@ {@b@ return getFirst("Upgrade");@b@ }@b@@b@ public void setVary(List<String> requestHeaders)@b@ {@b@ set("Vary", toCommaDelimitedString(requestHeaders));@b@ }@b@@b@ public List<String> getVary()@b@ {@b@ return getValuesAsList("Vary");@b@ }@b@@b@ public void setDate(String headerName, long date)@b@ {@b@ SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMATS[0], Locale.US);@b@ dateFormat.setTimeZone(GMT);@b@ set(headerName, dateFormat.format(new Date(date)));@b@ }@b@@b@ public long getFirstDate(String headerName)@b@ {@b@ return getFirstDate(headerName, true);@b@ }@b@@b@ private long getFirstDate(String headerName, boolean rejectInvalid)@b@ {@b@ int j;@b@ SimpleDateFormat simpleDateFormat;@b@ String headerValue = getFirst(headerName);@b@ if (headerValue == null)@b@ {@b@ return -1L;@b@ }@b@ if (headerValue.length() >= 3)@b@ {@b@ String[] arrayOfString = DATE_FORMATS; int i = arrayOfString.length; j = 0; if (j < i) { String dateFormat = arrayOfString[j];@b@ simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US);@b@ simpleDateFormat.setTimeZone(GMT); } }@b@ try {@b@ return simpleDateFormat.parse(headerValue).getTime();@b@ }@b@ catch (ParseException localParseException)@b@ {@b@ while (true) {@b@ ++j;@b@ }@b@@b@ if (rejectInvalid)@b@ throw new IllegalArgumentException(new StringBuilder().append("Cannot parse date value \"").append(headerValue).append("\" for \"").append(headerName).append("\" header").toString());@b@ }@b@@b@ return -1L;@b@ }@b@@b@ public List<String> getValuesAsList(String headerName)@b@ {@b@ List values = get(headerName);@b@ if (values != null) {@b@ String[] arrayOfString1;@b@ int j;@b@ List result = new ArrayList();@b@ for (String value : values)@b@ if (value != null) {@b@ String[] tokens = StringUtils.tokenizeToStringArray(value, ",");@b@ arrayOfString1 = tokens; int i = arrayOfString1.length; for (j = 0; j < i; ++j) { String token = arrayOfString1[j];@b@ result.add(token);@b@ }@b@ }@b@@b@ return result;@b@ }@b@ return Collections.emptyList();@b@ }@b@@b@ protected List<String> getETagValuesAsList(String headerName)@b@ {@b@ List values = get(headerName);@b@ if (values != null) {@b@ List result = new ArrayList();@b@ for (String value : values)@b@ if (value != null) {@b@ Matcher matcher = ETAG_HEADER_VALUE_PATTERN.matcher(value);@b@ while (true) { while (true) { if (!(matcher.find())) break label115;@b@ if (!("*".equals(matcher.group()))) break;@b@ result.add(matcher.group());@b@ }@b@@b@ result.add(matcher.group(1));@b@ }@b@@b@ if (result.isEmpty())@b@ throw new IllegalArgumentException(new StringBuilder().append("Could not parse header '").append(headerName).append("' with value '").append(value).append("'").toString());@b@@b@ }@b@@b@@b@ label115: return result;@b@ }@b@ return Collections.emptyList();@b@ }@b@@b@ protected String getFieldValues(String headerName)@b@ {@b@ List headerValues = get(headerName);@b@ return ((headerValues != null) ? toCommaDelimitedString(headerValues) : null);@b@ }@b@@b@ protected String toCommaDelimitedString(List<String> headerValues)@b@ {@b@ StringBuilder builder = new StringBuilder();@b@ for (Iterator it = headerValues.iterator(); it.hasNext(); ) {@b@ String val = (String)it.next();@b@ builder.append(val);@b@ if (it.hasNext())@b@ builder.append(", ");@b@ }@b@@b@ return builder.toString();@b@ }@b@@b@ public String getFirst(String headerName)@b@ {@b@ List headerValues = (List)this.headers.get(headerName);@b@ return ((headerValues != null) ? (String)headerValues.get(0) : null);@b@ }@b@@b@ public void add(String headerName, String headerValue)@b@ {@b@ List headerValues = (List)this.headers.get(headerName);@b@ if (headerValues == null) {@b@ headerValues = new LinkedList();@b@ this.headers.put(headerName, headerValues);@b@ }@b@ headerValues.add(headerValue);@b@ }@b@@b@ public void set(String headerName, String headerValue)@b@ {@b@ List headerValues = new LinkedList();@b@ headerValues.add(headerValue);@b@ this.headers.put(headerName, headerValues);@b@ }@b@@b@ public void setAll(Map<String, String> values)@b@ {@b@ for (Map.Entry entry : values.entrySet())@b@ set((String)entry.getKey(), (String)entry.getValue());@b@ }@b@@b@ public Map<String, String> toSingleValueMap()@b@ {@b@ LinkedHashMap singleValueMap = new LinkedHashMap(this.headers.size());@b@ for (Map.Entry entry : this.headers.entrySet())@b@ singleValueMap.put(entry.getKey(), ((List)entry.getValue()).get(0));@b@@b@ return singleValueMap;@b@ }@b@@b@ public int size()@b@ {@b@ return this.headers.size();@b@ }@b@@b@ public boolean isEmpty()@b@ {@b@ return this.headers.isEmpty();@b@ }@b@@b@ public boolean containsKey(Object key)@b@ {@b@ return this.headers.containsKey(key);@b@ }@b@@b@ public boolean containsValue(Object value)@b@ {@b@ return this.headers.containsValue(value);@b@ }@b@@b@ public List<String> get(Object key)@b@ {@b@ return ((List)this.headers.get(key));@b@ }@b@@b@ public List<String> put(String key, List<String> value)@b@ {@b@ return ((List)this.headers.put(key, value));@b@ }@b@@b@ public List<String> remove(Object key)@b@ {@b@ return ((List)this.headers.remove(key));@b@ }@b@@b@ public void putAll(Map<? extends String, ? extends List<String>> map)@b@ {@b@ this.headers.putAll(map);@b@ }@b@@b@ public void clear()@b@ {@b@ this.headers.clear();@b@ }@b@@b@ public Set<String> keySet()@b@ {@b@ return this.headers.keySet();@b@ }@b@@b@ public Collection<List<String>> values()@b@ {@b@ return this.headers.values();@b@ }@b@@b@ public Set<Map.Entry<String, List<String>>> entrySet()@b@ {@b@ return this.headers.entrySet();@b@ }@b@@b@ public boolean equals(Object other)@b@ {@b@ if (this == other)@b@ return true;@b@@b@ if (!(other instanceof HttpHeaders))@b@ return false;@b@@b@ HttpHeaders otherHeaders = (HttpHeaders)other;@b@ return this.headers.equals(otherHeaders.headers);@b@ }@b@@b@ public int hashCode()@b@ {@b@ return this.headers.hashCode();@b@ }@b@@b@ public String toString()@b@ {@b@ return this.headers.toString();@b@ }@b@@b@ public static HttpHeaders readOnlyHttpHeaders(HttpHeaders headers)@b@ {@b@ return new HttpHeaders(headers, true);@b@ }@b@@b@ static String encodeHeaderFieldParam(String input, Charset charset)@b@ {@b@ Assert.notNull(input, "Input String should not be null");@b@ Assert.notNull(charset, "Charset should not be null");@b@ if (charset.name().equals("US-ASCII"))@b@ return input;@b@@b@ Assert.isTrue((charset.name().equals("UTF-8")) || (charset.name().equals("ISO-8859-1")), "Charset should be UTF-8 or ISO-8859-1");@b@@b@ byte[] source = input.getBytes(charset);@b@ int len = source.length;@b@ StringBuilder sb = new StringBuilder(len << 1);@b@ sb.append(charset.name());@b@ sb.append("''");@b@ byte[] arrayOfByte1 = source; int i = arrayOfByte1.length; for (int j = 0; j < i; ++j) { byte b = arrayOfByte1[j];@b@ if (isRFC5987AttrChar(b)) {@b@ sb.append((char)b);@b@ }@b@ else {@b@ sb.append('%');@b@ char hex1 = Character.toUpperCase(Character.forDigit(b >> 4 & 0xF, 16));@b@ char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, 16));@b@ sb.append(hex1);@b@ sb.append(hex2);@b@ }@b@ }@b@ return sb.toString();@b@ }@b@@b@ private static boolean isRFC5987AttrChar(byte c) {@b@ return (((c >= 48) && (c <= 57)) || ((c >= 97) && (c <= 122)) || ((c >= 65) && (c <= 90)) || (c == 33) || (c == 35) || (c == 36) || (c == 38) || (c == 43) || (c == 45) || (c == 46) || (c == 94) || (c == 95) || (c == 96) || (c == 124) || (c == 126));@b@ }@b@}
package org.springframework.http;@b@@b@import java.util.HashMap;@b@import java.util.Map;@b@@b@public enum HttpMethod@b@{@b@ GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;@b@@b@ private static final Map<String, HttpMethod> mappings;@b@@b@ public static HttpMethod resolve(String method)@b@ {@b@ return ((method != null) ? (HttpMethod)mappings.get(method) : null);@b@ }@b@@b@ public boolean matches(String method)@b@ {@b@ return (this == resolve(method));@b@ }@b@@b@ static@b@ {@b@ mappings = new HashMap(8);@b@@b@ HttpMethod[] arrayOfHttpMethod = values(); int i = arrayOfHttpMethod.length; for (int j = 0; j < i; ++j) { HttpMethod httpMethod = arrayOfHttpMethod[j];@b@ mappings.put(httpMethod.name(), httpMethod);@b@ }@b@ }@b@}
package org.springframework.http;@b@@b@import java.net.URI;@b@@b@public abstract interface HttpRequest extends HttpMessage@b@{@b@ public abstract HttpMethod getMethod();@b@@b@ public abstract URI getURI();@b@}