首页

关于springframework的spring-web包定义ServerHttpResponse/ServerHttpRequest接口及实现类源码说明

标签:springframework,spring-web,ServerHttpResponseServerHttpRequest,ServletServerHttpRequest,ServletServerHttpResponse     发布时间:2018-09-22   

一、前言

关于springframework的spring-web包org.springframework.http.server.ServerHttpRequest、org.springframework.http.server.ServerHttpResponse请求响应接口类,并通过org.springframework.http.server.ServletServerHttpRequest、org.springframework.http.server.ServletServerHttpResponse请求响应实现类。

二、源码说明

1. ServerHttpRequest、ServerHttpResponse接口

package org.springframework.http.server;@b@@b@import java.net.InetSocketAddress;@b@import java.security.Principal;@b@import org.springframework.http.HttpInputMessage;@b@import org.springframework.http.HttpRequest;@b@@b@public abstract interface ServerHttpRequest extends HttpRequest, HttpInputMessage@b@{@b@  public abstract Principal getPrincipal();@b@@b@  public abstract InetSocketAddress getLocalAddress();@b@@b@  public abstract InetSocketAddress getRemoteAddress();@b@@b@  public abstract ServerHttpAsyncRequestControl getAsyncRequestControl(ServerHttpResponse paramServerHttpResponse);@b@}
package org.springframework.http.server;@b@@b@import java.io.Closeable;@b@import java.io.Flushable;@b@import java.io.IOException;@b@import org.springframework.http.HttpOutputMessage;@b@import org.springframework.http.HttpStatus;@b@@b@public abstract interface ServerHttpResponse extends HttpOutputMessage, Flushable, Closeable@b@{@b@  public abstract void setStatusCode(HttpStatus paramHttpStatus);@b@@b@  public abstract void flush()@b@    throws IOException;@b@@b@  public abstract void close();@b@}

2. ServletServerHttpRequest、ServletServerHttpResponse实现类

package org.springframework.http.server;@b@@b@import java.io.ByteArrayInputStream;@b@import java.io.ByteArrayOutputStream;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.io.OutputStreamWriter;@b@import java.io.Writer;@b@import java.net.InetSocketAddress;@b@import java.net.URI;@b@import java.net.URISyntaxException;@b@import java.net.URLEncoder;@b@import java.nio.charset.Charset;@b@import java.security.Principal;@b@import java.util.Arrays;@b@import java.util.Enumeration;@b@import java.util.Iterator;@b@import java.util.List;@b@import java.util.Map;@b@import java.util.Set;@b@import javax.servlet.http.HttpServletRequest;@b@import org.springframework.http.HttpHeaders;@b@import org.springframework.http.HttpMethod;@b@import org.springframework.http.MediaType;@b@import org.springframework.util.Assert;@b@import org.springframework.util.LinkedCaseInsensitiveMap;@b@import org.springframework.util.StringUtils;@b@@b@public class ServletServerHttpRequest@b@  implements ServerHttpRequest@b@{@b@  protected static final String FORM_CONTENT_TYPE = "application/x-www-form-urlencoded";@b@  protected static final String FORM_CHARSET = "UTF-8";@b@  private final HttpServletRequest servletRequest;@b@  private HttpHeaders headers;@b@  private ServerHttpAsyncRequestControl asyncRequestControl;@b@@b@  public ServletServerHttpRequest(HttpServletRequest servletRequest)@b@  {@b@    Assert.notNull(servletRequest, "HttpServletRequest must not be null");@b@    this.servletRequest = servletRequest;@b@  }@b@@b@  public HttpServletRequest getServletRequest()@b@  {@b@    return this.servletRequest;@b@  }@b@@b@  public HttpMethod getMethod()@b@  {@b@    return HttpMethod.resolve(this.servletRequest.getMethod());@b@  }@b@@b@  public URI getURI() {@b@    StringBuffer url;@b@    try {@b@      url = this.servletRequest.getRequestURL();@b@      String query = this.servletRequest.getQueryString();@b@      if (StringUtils.hasText(query))@b@        url.append('?').append(query);@b@@b@      return new URI(url.toString());@b@    }@b@    catch (URISyntaxException ex) {@b@      throw new IllegalStateException("Could not get HttpServletRequest URI: " + ex.getMessage(), ex);@b@    }@b@  }@b@@b@  public HttpHeaders getHeaders()@b@  {@b@    if (this.headers == null) {@b@      this.headers = new HttpHeaders();@b@@b@      for (Enumeration headerNames = this.servletRequest.getHeaderNames(); headerNames.hasMoreElements(); ) {@b@        String headerName = (String)headerNames.nextElement();@b@        Enumeration headerValues = this.servletRequest.getHeaders(headerName);@b@        while (headerValues.hasMoreElements()) {@b@          String headerValue = (String)headerValues.nextElement();@b@          this.headers.add(headerName, headerValue);@b@        }@b@      }@b@@b@      try@b@      {@b@        contentType = this.headers.getContentType();@b@        if (contentType == null) {@b@          String requestContentType = this.servletRequest.getContentType();@b@          if (StringUtils.hasLength(requestContentType)) {@b@            contentType = MediaType.parseMediaType(requestContentType);@b@            this.headers.setContentType(contentType);@b@          }@b@        }@b@        if ((contentType != null) && (contentType.getCharset() == null)) {@b@          String requestEncoding = this.servletRequest.getCharacterEncoding();@b@          if (StringUtils.hasLength(requestEncoding)) {@b@            Charset charSet = Charset.forName(requestEncoding);@b@            Map params = new LinkedCaseInsensitiveMap();@b@            params.putAll(contentType.getParameters());@b@            params.put("charset", charSet.toString());@b@            MediaType newContentType = new MediaType(contentType.getType(), contentType.getSubtype(), params);@b@            this.headers.setContentType(newContentType);@b@          }@b@        }@b@      }@b@      catch (org.springframework.http.InvalidMediaTypeException contentType)@b@      {@b@      }@b@@b@      if (this.headers.getContentLength() < 0L) {@b@        int requestContentLength = this.servletRequest.getContentLength();@b@        if (requestContentLength != -1)@b@          this.headers.setContentLength(requestContentLength);@b@      }@b@@b@    }@b@@b@    return this.headers;@b@  }@b@@b@  public Principal getPrincipal()@b@  {@b@    return this.servletRequest.getUserPrincipal();@b@  }@b@@b@  public InetSocketAddress getLocalAddress()@b@  {@b@    return new InetSocketAddress(this.servletRequest.getLocalName(), this.servletRequest.getLocalPort());@b@  }@b@@b@  public InetSocketAddress getRemoteAddress()@b@  {@b@    return new InetSocketAddress(this.servletRequest.getRemoteHost(), this.servletRequest.getRemotePort());@b@  }@b@@b@  public InputStream getBody() throws IOException@b@  {@b@    if (isFormPost(this.servletRequest)) {@b@      return getBodyFromServletRequestParameters(this.servletRequest);@b@    }@b@@b@    return this.servletRequest.getInputStream();@b@  }@b@@b@  public ServerHttpAsyncRequestControl getAsyncRequestControl(ServerHttpResponse response)@b@  {@b@    if (this.asyncRequestControl == null) {@b@      if (!(ServletServerHttpResponse.class.isInstance(response)))@b@        throw new IllegalArgumentException("Response must be a ServletServerHttpResponse: " + response.getClass());@b@@b@      ServletServerHttpResponse servletServerResponse = (ServletServerHttpResponse)response;@b@      this.asyncRequestControl = new ServletServerHttpAsyncRequestControl(this, servletServerResponse);@b@    }@b@    return this.asyncRequestControl;@b@  }@b@@b@  private static boolean isFormPost(HttpServletRequest request)@b@  {@b@    String contentType = request.getContentType();@b@    return ((contentType != null) && (contentType.contains("application/x-www-form-urlencoded")) && @b@      (HttpMethod.POST@b@      .matches(request@b@      .getMethod())));@b@  }@b@@b@  private static InputStream getBodyFromServletRequestParameters(HttpServletRequest request)@b@    throws IOException@b@  {@b@    ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);@b@    Writer writer = new OutputStreamWriter(bos, "UTF-8");@b@@b@    Map form = request.getParameterMap();@b@    for (Iterator nameIterator = form.keySet().iterator(); nameIterator.hasNext(); ) {@b@      String name = (String)nameIterator.next();@b@      List values = Arrays.asList((Object[])form.get(name));@b@      for (Iterator valueIterator = values.iterator(); valueIterator.hasNext(); ) {@b@        String value = (String)valueIterator.next();@b@        writer.write(URLEncoder.encode(name, "UTF-8"));@b@        if (value != null) {@b@          writer.write(61);@b@          writer.write(URLEncoder.encode(value, "UTF-8"));@b@          if (valueIterator.hasNext())@b@            writer.write(38);@b@        }@b@      }@b@@b@      if (nameIterator.hasNext())@b@        writer.append('&');@b@    }@b@@b@    writer.flush();@b@@b@    return new ByteArrayInputStream(bos.toByteArray());@b@  }@b@}
package org.springframework.http.server;@b@@b@import java.io.IOException;@b@import java.io.OutputStream;@b@import java.nio.charset.Charset;@b@import java.util.ArrayList;@b@import java.util.Collection;@b@import java.util.List;@b@import java.util.Map.Entry;@b@import javax.servlet.http.HttpServletResponse;@b@import org.springframework.http.HttpHeaders;@b@import org.springframework.http.HttpStatus;@b@import org.springframework.http.MediaType;@b@import org.springframework.util.Assert;@b@import org.springframework.util.ClassUtils;@b@import org.springframework.util.CollectionUtils;@b@@b@public class ServletServerHttpResponse@b@  implements ServerHttpResponse@b@{@b@  private static final boolean servlet3Present = ClassUtils.hasMethod(HttpServletResponse.class, "getHeader", new Class[] { String.class });@b@  private final HttpServletResponse servletResponse;@b@  private final HttpHeaders headers;@b@  private boolean headersWritten = false;@b@  private boolean bodyUsed = false;@b@@b@  public ServletServerHttpResponse(HttpServletResponse servletResponse)@b@  {@b@    Assert.notNull(servletResponse, "HttpServletResponse must not be null");@b@    this.servletResponse = servletResponse;@b@    this.headers = new HttpHeaders();@b@  }@b@@b@  public HttpServletResponse getServletResponse()@b@  {@b@    return this.servletResponse;@b@  }@b@@b@  public void setStatusCode(HttpStatus status)@b@  {@b@    Assert.notNull(status, "HttpStatus must not be null");@b@    this.servletResponse.setStatus(status.value());@b@  }@b@@b@  public HttpHeaders getHeaders()@b@  {@b@    return ((this.headersWritten) ? HttpHeaders.readOnlyHttpHeaders(this.headers) : this.headers);@b@  }@b@@b@  public OutputStream getBody() throws IOException@b@  {@b@    this.bodyUsed = true;@b@    writeHeaders();@b@    return this.servletResponse.getOutputStream();@b@  }@b@@b@  public void flush() throws IOException@b@  {@b@    writeHeaders();@b@    if (this.bodyUsed)@b@      this.servletResponse.flushBuffer();@b@  }@b@@b@  public void close()@b@  {@b@    writeHeaders();@b@  }@b@@b@  private void writeHeaders() {@b@    if (!(this.headersWritten)) {@b@      String headerName;@b@      for (Map.Entry entry : this.headers.entrySet()) {@b@        headerName = (String)entry.getKey();@b@        for (String headerValue : (List)entry.getValue())@b@          this.servletResponse.addHeader(headerName, headerValue);@b@@b@      }@b@@b@      if ((this.servletResponse.getContentType() == null) && (this.headers.getContentType() != null))@b@        this.servletResponse.setContentType(this.headers.getContentType().toString());@b@@b@      if ((this.servletResponse.getCharacterEncoding() == null) && (this.headers.getContentType() != null) && @b@        (this.headers@b@        .getContentType().getCharset() != null))@b@        this.servletResponse.setCharacterEncoding(this.headers.getContentType().getCharset().name());@b@@b@      this.headersWritten = true;@b@    }@b@  }@b@@b@  private class ServletResponseHttpHeaders extends HttpHeaders@b@  {@b@    private static final long serialVersionUID = 3410708522401046302L;@b@@b@    public boolean containsKey()@b@    {@b@      return ((super.containsKey(key)) || (get(key) != null));@b@    }@b@@b@    public String getFirst()@b@    {@b@      String value = ServletServerHttpResponse.access$100(this.this$0).getHeader(headerName);@b@      if (value != null) {@b@        return value;@b@      }@b@@b@      return super.getFirst(headerName);@b@    }@b@@b@    public List<String> get()@b@    {@b@      Assert.isInstanceOf(String.class, key, "Key must be a String-based header name");@b@@b@      Collection values1 = ServletServerHttpResponse.access$100(this.this$0).getHeaders((String)key);@b@      boolean isEmpty1 = CollectionUtils.isEmpty(values1);@b@@b@      List values2 = super.get(key);@b@      boolean isEmpty2 = CollectionUtils.isEmpty(values2);@b@@b@      if ((isEmpty1) && (isEmpty2)) {@b@        return null;@b@      }@b@@b@      List values = new ArrayList();@b@      if (!(isEmpty1))@b@        values.addAll(values1);@b@@b@      if (!(isEmpty2))@b@        values.addAll(values2);@b@@b@      return values;@b@    }@b@  }@b@}
<<热门下载>>