Servlet The Request

The Request

HTTP Protocol Parameters

所有的HTTP Protocol Parameters都会放在一个Map中, 可以通过getParameterMap得到. 对于Query String和Post Body中的请求, 会将两者放在同一个set中, Query String的顺序靠前.

query string: a = hello
post body: a = goodbye & a = world
result set: a = (hello, goodbye, world)

而通过GET方式拼在url后面的参数不会在这里体现, 是通过getRequestURI()和getPathInfo()得到的.

如果符合下列情况, 则可以在参数Map中得到参数:

  1. HTTP or HTTPS
  2. HTTP Method: POST
  3. Content Type: application/x-www-form-urlencoded
  4. Servlet被正确创建和实例化, 并调用getParameters方法族.

如果不符合以上条件, 还可以从Request的InputStream中读取, 而满足条件后InputStream不能读出数据.

File Upload

如果Request的Type是"multipart/form-data", 并且处理的servlet上加了"@MultipartConfig", 那么HttpServletRequest可以通过以下函数处理文件上传:

public Collection<Part> getParts()
public Part getPart(String name).

并且每一个Part都可以取的头信息, Type, 并通过getInputStream取的内容.
又因为使用了form-data的形式, 其实也可以通过getParameter的方式得到内容.

Attributes

Attributes是和Request相关的信息, 但是可以由container访问到, 比如可以使用在两个servlet的通信中, 可以通过下列方法访问. 一般Attributes的命名也使用倒序的文件结构名.

getAttribute
getAttributeNames
setAttribute

Headers

Request Path Elements

Request Path Elements包含几个部分, 有:

  • Context Path
  • Servlet Path
  • PathInfo

requestURI = contextPath + servletPath + pathInfo

Servlet的配置信息:

Context Path /catalog

Servlet Mapping Pattern: /lawn/*
				Servlet: LawnServlet

Servlet Mapping Pattern: /garden/*
				Servlet: GardenServlet

Servlet Mapping Pattern: *.jsp
				Servlet: JSPServlet

访问的URL示例:

/catalog/lawn/index.html ContextPath: /catalog
						 ServletPath: /lawn
						 PathInfo: /index.html

/catalog/garden/implements/ ContextPath: /catalog
						    ServletPath: /garden
							PathInfo: /implements/

/catalog/help/feedback.jsp ContextPath: /catalog
						   ServletPath: /help/feedback.jsp
						   PathInfo: null

Path Translation Methods

可以通过两个函数得到真实的Servlet对应的文件系统的信息:

  • ServletContext.getRealPath
  • HttpServletRequest.getPathTranslated

返回本地的文件系统的路径, 如果是远程或者是得不到则返回null.

Resources inside the META-INF/resources directory of JAR file must be
considered only if the container has unpacked them from their containing JAR file
when a call to getRealPath() is made, and in this case MUST return the unpacked
location.

SSL Attributes

如果Request使用了secure protocol, 如HTTPS. 下列信息必须由Web Container暴露给Servlet

Attribute Attribute Name Java Type
cipher suite javax.servlet.request.cipher_suite String
bit size of the algorithm javax.servlet.request.key_size Integer
SSL session id javax.servlet.request.ssl_session_id String

Lifetime of the Request Object

Each request object is valid only within the scope of a servlet’s service method, or
within the scope of a filter’s doFilter method, unless the asynchronous processing
is enabled for the component and the startAsync method is invoked on the request
object.

原文地址:https://www.cnblogs.com/putuotingchan/p/8630955.html