WebUtils工具类解析

WebUtils根据名称,知道是Spring当中一个工具类,主要用于Web应用程序,供各种框架使用。

其中有些方法还是挺有用的,比如可以获取Session中的会话属性,获取Cookies,设置Session中的会话属性的值等等

翻译了WebUtils类的文档,其中WebUtils中的方法如下:

1.将一个系统性质设置到上下文根路径


    
    
    
    
  1. public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException {
  2. Assert.notNull(servletContext, "ServletContext must not be null");
  3. String root = servletContext.getRealPath( "/");
  4. if (root == null) {
  5. throw new IllegalStateException(
  6. "Cannot set web app root system property when WAR file is not expanded");
  7. }
  8. String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);
  9. String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);
  10. String oldValue = System.getProperty(key);
  11. if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) {
  12. throw new IllegalStateException(
  13. "Web app root system property already set to different value: '" +
  14. key + "' = [" + oldValue + "] instead of [" + root + "] - " +
  15. "Choose unique values for the 'webAppRootKey' context-param in your web.xml files!");
  16. }
  17. System.setProperty(key, root);
  18. servletContext.log( "Set web app root system property: '" + key + "' = [" + root + "]");
  19. }

2.移除系统性质


    
    
    
    
  1. public static void removeWebAppRootSystemProperty(ServletContext servletContext) {
  2. Assert.notNull(servletContext, "ServletContext must not be null");
  3. String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);
  4. String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);
  5. System.getProperties().remove(key);
  6. }

3.判断“HTML escaping”(HTML转义)对应用是否允许,即看web.xml中的defaultHtmlEscape的值是否设置为true


    
    
    
    
  1. public static Boolean getDefaultHtmlEscape(ServletContext servletContext) {
  2. if (servletContext == null) {
  3. return null;
  4. }
  5. String param = servletContext.getInitParameter(HTML_ESCAPE_CONTEXT_PARAM);
  6. return (StringUtils.hasText(param)? Boolean.valueOf(param) : null);
  7. }

4.返回由当前servlet容器提供的 当前Web应用程序的临时目录


    
    
    
    
  1. public static File getTempDir(ServletContext servletContext) {
  2. Assert.notNull(servletContext, "ServletContext must not be null");
  3. return (File) servletContext.getAttribute(TEMP_DIR_CONTEXT_ATTRIBUTE);
  4. }

5.返回由servlet容器提供的,Web应用程序中给定路径的实际路径


    
    
    
    
  1. public static String getRealPath(ServletContext servletContext, String path) throws FileNotFoundException {
  2. Assert.notNull(servletContext, "ServletContext must not be null");
  3. // Interpret location as relative to the web application root directory.
  4. if (!path.startsWith( "/")) {
  5. path = "/" + path;
  6. }
  7. String realPath = servletContext.getRealPath(path);
  8. if (realPath == null) {
  9. throw new FileNotFoundException(
  10. "ServletContext resource [" + path + "] cannot be resolved to absolute file path - " +
  11. "web application archive not expanded?");
  12. }
  13. return realPath;
  14. }

6.通过一个请求确定会话Session的标识(Id)


    
    
    
    
  1. public static String getSessionId(HttpServletRequest request) {
  2. Assert.notNull(request, "Request must not be null");
  3. HttpSession session = request.getSession( false);
  4. return (session != null ? session.getId() : null);
  5. }

7.通过一个请求,通过name获取session中的属性,如果session中没有属性或者没有session会返回一个null


    
    
    
    
  1. public static Object getSessionAttribute(HttpServletRequest request, String name) {
  2. Assert.notNull(request, "Request must not be null");
  3. HttpSession session = request.getSession( false);
  4. return (session != null ? session.getAttribute(name) : null);
  5. }

8.和7中方法相似,只不过不会返回null,会抛出异常


    
    
    
    
  1. public static Object getRequiredSessionAttribute(HttpServletRequest request, String name)
  2. throws IllegalStateException {
  3. Object attr = getSessionAttribute(request, name);
  4. if (attr == null) {
  5. throw new IllegalStateException( "No session attribute '" + name + "' found");
  6. }
  7. return attr;
  8. }

9.通过给定的名称和值设置session中的属性,若果session值为空,会移除session的属性


    
    
    
    
  1. public static void setSessionAttribute(HttpServletRequest request, String name, Object value) {
  2. Assert.notNull(request, "Request must not be null");
  3. if (value != null) {
  4. request.getSession().setAttribute(name, value);
  5. }
  6. else {
  7. HttpSession session = request.getSession( false);
  8. if (session != null) {
  9. session.removeAttribute(name);
  10. }
  11. }
  12. }

10.获取指定的会话属性,如果没有找到的话会创建并设置新的属性。其中给定的类需要有一个公共的无参构造函数。


    
    
    
    
  1. public static Object getOrCreateSessionAttribute(HttpSession session, String name, Class clazz)
  2. throws IllegalArgumentException {
  3. Assert.notNull(session, "Session must not be null");
  4. Object sessionObject = session.getAttribute(name);
  5. if (sessionObject == null) {
  6. try {
  7. sessionObject = clazz.newInstance();
  8. }
  9. catch (InstantiationException ex) {
  10. throw new IllegalArgumentException(
  11. "Could not instantiate class [" + clazz.getName() +
  12. "] for session attribute '" + name + "': " + ex.getMessage());
  13. }
  14. catch (IllegalAccessException ex) {
  15. throw new IllegalArgumentException(
  16. "Could not access default constructor of class [" + clazz.getName() +
  17. "] for session attribute '" + name + "': " + ex.getMessage());
  18. }
  19. session.setAttribute(name, sessionObject);
  20. }
  21. return sessionObject;
  22. }

11.返回给定会话的最佳可用互斥量:即为给定会话同步的对象。返回会话互斥属性(如果可用);通常情况下,这意味着需要定义HttpSessionMutexListener在{code web.xml}中。 回到HttpSession本身如果没有找到互斥属性。会话互斥确保在期间是相同的对象会话的整个生命周期,在定义的密钥下可用由SESSION_MUTEX_ATTRIBUTE常量定义。 它作为一个在当前会话上同步锁定的安全引用。在很多情况下,HttpSession引用本身是一个安全的互斥体同样,因为它始终是相同的对象参考相同的活动逻辑会话。 但是,这并不能保证不同的servlet容器; 唯一的100%安全方式是会话互斥。


    
    
    
    
  1. public static Object getSessionMutex(HttpSession session) {
  2. Assert.notNull(session, "Session must not be null");
  3. Object mutex = session.getAttribute(SESSION_MUTEX_ATTRIBUTE);
  4. if (mutex == null) {
  5. mutex = session;
  6. }
  7. return mutex;
  8. }

12.返回指定类型的合适的请求对象,如果可用,会unwrapping给定的request请求


    
    
    
    
  1. public static T getNativeRequest(ServletRequest request, Class requiredType) {
  2. if (requiredType != null) {
  3. if (requiredType.isInstance(request)) {
  4. return (T) request;
  5. }
  6. else if (request instanceof ServletRequestWrapper) {
  7. return getNativeRequest(((ServletRequestWrapper) request).getRequest(), requiredType);
  8. }
  9. }
  10. return null;
  11. }

13.和12方法类似,应用于response


    
    
    
    
  1. public static T getNativeResponse(ServletResponse response, Class requiredType) {
  2. if (requiredType != null) {
  3. if (requiredType.isInstance(response)) {
  4. return (T) response;
  5. }
  6. else if (response instanceof ServletResponseWrapper) {
  7. return getNativeResponse(((ServletResponseWrapper) response).getResponse(), requiredType);
  8. }
  9. }
  10. return null;
  11. }

14.判断请求是否是一个包含(Include)请求,即不是从外部进入的顶级Http请求。


    
    
    
    
  1. public static boolean isIncludeRequest(ServletRequest request) {
  2. return (request.getAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE) != null);
  3. }

15.Servlet规范的错误属性,Servlet2.3规范中定义的属性,用于错误页面直接呈现,而不是通过Servlet容器的错误页面解析


    
    
    
    
  1. public static void exposeErrorRequestAttributes(HttpServletRequest request, Throwable ex, String servletName) {
  2. exposeRequestAttributeIfNotPresent(request, ERROR_STATUS_CODE_ATTRIBUTE, HttpServletResponse.SC_OK);
  3. exposeRequestAttributeIfNotPresent(request, ERROR_EXCEPTION_TYPE_ATTRIBUTE, ex.getClass());
  4. exposeRequestAttributeIfNotPresent(request, ERROR_MESSAGE_ATTRIBUTE, ex.getMessage());
  5. exposeRequestAttributeIfNotPresent(request, ERROR_EXCEPTION_ATTRIBUTE, ex);
  6. exposeRequestAttributeIfNotPresent(request, ERROR_REQUEST_URI_ATTRIBUTE, request.getRequestURI());
  7. exposeRequestAttributeIfNotPresent(request, ERROR_SERVLET_NAME_ATTRIBUTE, servletName);
  8. }

16.如果不存在? 公开指定的请求属性       (有疑问)


    
    
    
    
  1. private static void exposeRequestAttributeIfNotPresent(ServletRequest request, String name, Object value) {
  2. if (request.getAttribute(name) == null) {
  3. request.setAttribute(name, value);
  4. }
  5. }

17.清除类似方法15中定义的错误属性,遵循servlet2.3规范


    
    
    
    
  1. public static void clearErrorRequestAttributes(HttpServletRequest request) {
  2. request.removeAttribute(ERROR_STATUS_CODE_ATTRIBUTE);
  3. request.removeAttribute(ERROR_EXCEPTION_TYPE_ATTRIBUTE);
  4. request.removeAttribute(ERROR_MESSAGE_ATTRIBUTE);
  5. request.removeAttribute(ERROR_EXCEPTION_ATTRIBUTE);
  6. request.removeAttribute(ERROR_REQUEST_URI_ATTRIBUTE);
  7. request.removeAttribute(ERROR_SERVLET_NAME_ATTRIBUTE);
  8. }

18.将给定的Map公开为请求属性,使用键作为属性名称并将值作为相应的属性值。 键需要是字符串


    
    
    
    
  1. public static void exposeRequestAttributes(ServletRequest request, Map attributes) {
  2. Assert.notNull(request, "Request must not be null");
  3. Assert.notNull(attributes, "Attributes Map must not be null");
  4. for (Map.Entry entry : attributes.entrySet()) {
  5. request.setAttribute(entry.getKey(), entry.getValue());
  6. }
  7. }

19.检索具有给定名称的第一个cookie。注意多个Cookie可以具有相同的名称,但路径和域不同。


    
    
    
    
  1. public static Cookie getCookie(HttpServletRequest request, String name) {
  2. Assert.notNull(request, "Request must not be null");
  3. Cookie cookies[] = request.getCookies();
  4. if (cookies != null) {
  5. for (Cookie cookie : cookies) {
  6. if (name.equals(cookie.getName())) {
  7. return cookie;
  8. }
  9. }
  10. }
  11. return null;
  12. }

20.检查请求中是否有通过按钮或者图像的特定的输入类型=“submit”参数


    
    
    
    
  1. public static boolean hasSubmitParameter(ServletRequest request, String name) {
  2. Assert.notNull(request, "Request must not be null");
  3. if (request.getParameter(name) != null) {
  4. return true;
  5. }
  6. for (String suffix : SUBMIT_IMAGE_SUFFIXES) {
  7. if (request.getParameter(name + suffix) != null) {
  8. return true;
  9. }
  10. }
  11. return false;
  12. }

21.从给定的请求参数中获取一个命名参数。可以参阅方法{findParameterValue}用于查找算法的描述


    
    
    
    
  1. public static String findParameterValue(ServletRequest request, String name) {
  2. return findParameterValue(request.getParameterMap(), name);
  3. }

22.获取参数值通过以下的算法:(算法补充)


    
    
    
    
  1. public static String findParameterValue(Map parameters, String name) {
  2. // First try to get it as a normal name=value parameter
  3. Object value = parameters.get(name);
  4. if (value instanceof String[]) {
  5. String[] values = (String[]) value;
  6. return (values.length > 0 ? values[ 0] : null);
  7. }
  8. else if (value != null) {
  9. return value.toString();
  10. }
  11. // If no value yet, try to get it as a name_value=xyz parameter
  12. String prefix = name + "_";
  13. for (String paramName : parameters.keySet()) {
  14. if (paramName.startsWith(prefix)) {
  15. // Support images buttons, which would submit parameters as name_value.x=123
  16. for (String suffix : SUBMIT_IMAGE_SUFFIXES) {
  17. if (paramName.endsWith(suffix)) {
  18. return paramName.substring(prefix.length(), paramName.length() - suffix.length());
  19. }
  20. }
  21. return paramName.substring(prefix.length());
  22. }
  23. }
  24. // We couldn't find the parameter value...
  25. return null;
  26. }

23.返回包含具有给定前缀的所有参数的map。将单个值映射为String,多个值映射到String数组。


    
    
    
    
  1. public static Map getParametersStartingWith(ServletRequest request, String prefix) {
  2. Assert.notNull(request, "Request must not be null");
  3. Enumeration paramNames = request.getParameterNames();
  4. Map params = new TreeMap();
  5. if (prefix == null) {
  6. prefix = "";
  7. }
  8. while (paramNames != null && paramNames.hasMoreElements()) {
  9. String paramName = paramNames.nextElement();
  10. if ( "".equals(prefix) || paramName.startsWith(prefix)) {
  11. String unprefixed = paramName.substring(prefix.length());
  12. String[] values = request.getParameterValues(paramName);
  13. if (values == null || values.length == 0) {
  14. // Do nothing, no values found at all.
  15. }
  16. else if (values.length > 1) {
  17. params.put(unprefixed, values);
  18. }
  19. else {
  20. params.put(unprefixed, values[ 0]);
  21. }
  22. }
  23. }
  24. return params;
  25. }

24.返回请求中指定的目标页面


    
    
    
    
  1. public static int getTargetPage(ServletRequest request, String paramPrefix, int currentPage) {
  2. Enumeration paramNames = request.getParameterNames();
  3. while (paramNames.hasMoreElements()) {
  4. String paramName = paramNames.nextElement();
  5. if (paramName.startsWith(paramPrefix)) {
  6. for ( int i = 0; i < WebUtils.SUBMIT_IMAGE_SUFFIXES.length; i++) {
  7. String suffix = WebUtils.SUBMIT_IMAGE_SUFFIXES[i];
  8. if (paramName.endsWith(suffix)) {
  9. paramName = paramName.substring( 0, paramName.length() - suffix.length());
  10. }
  11. }
  12. return Integer.parseInt(paramName.substring(paramPrefix.length()));
  13. }
  14. }
  15. return currentPage;
  16. }

25.从给定的请求URL路径中提取URL文件名


    
    
    
    
  1. public static String extractFilenameFromUrlPath(String urlPath) {
  2. String filename = extractFullFilenameFromUrlPath(urlPath);
  3. int dotIndex = filename.lastIndexOf( '.');
  4. if (dotIndex != - 1) {
  5. filename = filename.substring( 0, dotIndex);
  6. }
  7. return filename;
  8. }

26.从给定的请求URL路径中提取完整的URL文件名(包括文件扩展名)。正确地解析嵌套路径,例如“/products/view.html”。


    
    
    
    
  1. public static String extractFullFilenameFromUrlPath(String urlPath) {
  2. int end = urlPath.indexOf( ';');
  3. if (end == - 1) {
  4. end = urlPath.indexOf( '?');
  5. if (end == - 1) {
  6. end = urlPath.length();
  7. }
  8. }
  9. int begin = urlPath.lastIndexOf( '/', end) + 1;
  10. return urlPath.substring(begin, end);
  11. }
27.用矩阵变量解析给定的字符串。 一个例子字符串会看起来像这样{@code“q1 = a; q1 = b; q2 = a,b,c”}。 结果地图将包含

使用值{@code [“a”,“b”]}的密钥{@code“q1”}和{@code“q2”}和{@code [“a”,“b”,“c”]}。


    
    
    
    
  1. public static MultiValueMap parseMatrixVariables(String matrixVariables) {
  2. MultiValueMap result = new LinkedMultiValueMap();
  3. if (!StringUtils.hasText(matrixVariables)) {
  4. return result;
  5. }
  6. StringTokenizer pairs = new StringTokenizer(matrixVariables, ";");
  7. while (pairs.hasMoreTokens()) {
  8. String pair = pairs.nextToken();
  9. int index = pair.indexOf( '=');
  10. if (index != - 1) {
  11. String name = pair.substring( 0, index);
  12. String rawValue = pair.substring(index + 1);
  13. for (String value : StringUtils.commaDelimitedListToStringArray(rawValue)) {
  14. result.add(name, value);
  15. }
  16. }
  17. else {
  18. result.add(pair, "");
  19. }
  20. }
  21. return result;
  22. }

你可能感兴趣的:(JAVA_Web)