HttpServletRequest basic functions


HttpServletRequest function


HttpServletRequest JavaWeb very important in a class. It is one of the parameters of Servlet service () method! So you must have to master it!
The request can be divided into the following functions:
l encapsulates the request header data;
l encapsulating text data request, if the request is GET, then there is no text;
l request is a domain object, it can be added to obtain the data as Map ;
l do request forwarding

2 request header data acquisition request

String value = request.getHeader ( "Request header name");
request object can be used to obtain data request header, of course, these requests are Tomcat data package to the request and going. We can get directly to the service () method!
request header and request related methods are:
l getHeader String (String name): the first specified name acquisition request;
l getHeaderNames the Enumeration (): Get all request header name;
l int getIntHeader (String name): Get value of type int request header.

	response.setContentType("text/html;charset=utf-8");
	Enumeration names = request.getHeaderNames();
	while(names.hasMoreElements()) {
		String name = (String)names.nextElement();
		String value = request.getHeader(name);
		System.out.println(name + ": " + value);
		response.getWriter().println(name + ": " + value + "<br/>");
	}

Other methods relevant to 3 request acquisition request

request also provides other methods associated with the request, some of which are more convenient for our request header data and design methods, some of which are associated with the request URL method.

	int getContentLength():获取请求正文的字节数,GET请求没有正文,没有正文返回-1;
	String getContentType():获取请求类型,如果请求是GET,那么这个方法返回null;如果是POST请求,那么默认为application/x-www-form-urlencoded(理解为字符串类型),其它类型以后再学;
	String getMethod():返回请求方法,例如:GET
	Locale getLocale():返回当前客户端浏览器支持的Locale。java.util.Locale表示国家和言语,这个东西在国际化中很有用;
	String getCharacterEncoding():获取请求编码,如果没有setCharacterEncoding(),那么返回null。表示使用ISO-8859-1编码;
	void setCharacterEncoding(String code):设置请求编码,只对正文有效!注意,对于GET而言,没有正文!!!所以此方法只能对POST请求中的参数有效!
http://localhost:8080/hello/oneServlet?name=zhangSan
	String getContextPath():返回上下文路径,例如:/项目名称
	String getQueryString():返回请求URL中的参数,例如:name=zhangSan
	String getRequestURI():返回请求URI路径,例如:/hello/oneServlet
	StringBuffer getRequestURL():返回请求URL路径,例如:http://localhost/hello/oneServlet,即返回除了参数以外的路径信息;
	String getServletPath():返回Servlet路径,例如:/oneServlet
	String getRemoteAddr():返回当前客户端的IP地址;
	String getRemoteHost():返回当前客户端的主机名,但这个方法的实现还是获取IP地址;
	int getRemotePort():返回客户端的端口号,每次请求都会变;
	String getSchema():返回请求协议,例如:http;
	String getServerName():返回主机名,例如:localhost
	int getServerPort():返回服务器端口号,例如:80
System.out.println("request.getContentLength(): " + request.getContentLength());
System.out.println("request.getContentType(): " + request.getContentType());
System.out.println("request.getContextPath(): " + request.getContextPath());
System.out.println("request.getMethod(): " + request.getMethod());
System.out.println("request.getLocale(): " + request.getLocale());
	
System.out.println("request.getQueryString(): " + request.getQueryString());
System.out.println("request.getRequestURI(): " + request.getRequestURI());
System.out.println("request.getRequestURL(): " + request.getRequestURL());
System.out.println("request.getServletPath(): " + request.getServletPath());
System.out.println("request.getRemoteAddr(): " + request.getRemoteAddr());
System.out.println("request.getRemoteHost(): " + request.getRemoteHost());
System.out.println("request.getRemotePort(): " + request.getRemotePort());
System.out.println("request.getScheme(): " + request.getScheme());
System.out.println("request.getServerName(): " + request.getServerName());
System.out.println("request.getServerPort(): " + request.getServerPort());

4.HttpServletRequest acquisition parameters (important)

. 1 HttpServletRequest method of acquisition parameters
may be used HttpServletRequest acquisition request parameter client, related as follows:
l String the getParameter (String name): Gets the parameter values by specifying the name;
l String [] the getParameterValues (String name): Gets parameter array by specifying the name , a name corresponding to a plurality of possible values, for example in the form of a plurality of check boxes when using the same name;
l the Enumeration the getParameterNames (): Get a list of all parameters;
l getParameterMap the Map (): Get all the parameters corresponding to the Map, where key is the parameter name, value for the parameter value.

2 way of passing parameters of
the way of passing parameters: GET and POST.
GET:
l the address bar directly given parameters: HTTP: // localhost / param / ParamServlet p1 = v1 & v2 = P2;?
L hyperlinks given parameters: <a href = "http:= v1 & P2 = p1 v2 "> ???
l parameters given in the form: ...
l Ajax temporarily introduced

The POST:
l form given parameters: ...
l Ajax introduces temporarily
received 3 single value of the parameter
a single parameter comprises radio, a single value of the drop-down boxes, text, hidden fields
whether the POST or GET, the parameters are the same method to obtain of.
String s1 = request.getParameter ( "p1" ); // Returns V1
String S2 = request.getParameter ( "P2"); // Returns v2

<form action="ParamServlet" method="post">
	<input type="text" name="p1"/><br/>
	<input type="text" name="p2"/><br/>
	<input type="submit" value="提交"/><br/>
</form>
<a href="ParamServlet?p1=v1&p2=v2">Param</a>
	String s1 = request.getParameter("p1");
	String s2 = request.getParameter("p2");
	response.getWriter().print("p1 = " + s1 + "<br/>");
	response.getWriter().print("p2 = " + s2 + "<br/>");
	Enumeration names = request.getParameterNames();
	while(names.hasMoreElements()) {
		String name = (String)names.nextElement();
		String value = request.getParameter(name);
		System.out.println(name + " = " + value);
	}

4 Multi-parameter receiving
multi-value parameter is mainly multiple choice checkbox
For example, in the registration form, if you let the user fill in the hobby, it might be more loving. It will correspond to a plurality of parameter values hobby:

   <form action="ParamServlet" method="post">
		上网:<input type="checkbox" name="hobby" value="netplay" /><br/>
		踢球:<input type="checkbox" name="hobby" value="football" /><br/>
		看书:<input type="checkbox" name="hobby" value="read" /><br/>
		编程:<input type="checkbox" name="hobby" value="programme" /><br/>
    	<input type="submit" value="提交"/><br/>
    </form>
	// 获取所有名为hoby的参数值
	String[] hobbies = request.getParameterValues("hobby");
	System.out.println(Arrays.toString(hobbies));

request.getParameterMap () method returns the type of Map, all the corresponding parameters. Map key corresponding to the name in which the parameter; parameter value corresponding to the value of the Map.

   <form action="ParamServlet" method="post">
		姓名:<input type="text" name="name"/><br/>
		年龄:<input type="text" name="age"/><br/>
		性别:<input type="text" name="sex"/><br/>
    	<input type="submit" value="提交"/><br/>
    </form>
Map<String,String[]> map = request.getParameterMap();
Set<String> keys = map.keySet();
for(String key : keys) {
	String[] value = map.get(key);
	System.out.println(key + " = " + value[0]);
}

sex = male
name = zhangSan
age = 23

Single-valued parameters, may also be used request.getParameterValues (String) acquiring, when the value of the parameter is in fact a single time, may also be used request.getParameterValues (String) method to get the value of the parameter, but the returned value of this parameter String [] , then we need to go to get the array element subscript 0.
; String name = request.getParameterValues ( "name ") [0]
obtained 5.Request treatment of Chinese garbled
when get and post two kinds of ways when the request is received Request parameters, but the Chinese encoding process is not the same, we are doing the project the whole station will have a unified coding, the most common is UTF-8, UTF-8 encoding in the project
 when we use the Post request:
handling POST coding problem!
We know, request information, there is only POST body, the so-called POST request body parameter coding is that code.
By default, when using getParameter () Gets POST request parameters, using the ISO-8859-1 encoding.
Request.getParameter name = String ( "name");
name = new new String (name.getBytes ( "the ISO-8859-1"), "UTF-. 8");
System.out.println (name);

Because the parameters have been getting error code, but because we know, for two reasons garbled: originally using UTF-8 encoding, it is also wrong to use the ISO-8859-1 encoding. Therefore, we can use the ISO-8859-1 to obtain an array of bytes, then use the correct UTF-8 encoded string obtained, so that no problem.
request of setCharacterEncodng () can set the encoding, of course, all of this must be called getParameter () setCharacterEncodng () method is called before the request to set the encoding method, so that you will not use the ISO interpreted byte string, but rather to use you given encoding to interpret.

request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
System.out.println(name);

For each request, just call setCharacterEncodng request of () once, then all getParameter () will use this code to interpret parameters. Note, however, valid only for the request body, namely POST parameters.

When we get request when using
the above-described treatment of post no longer work
 first embodiment:
of the character string transcoding to handle we can use
String request.getParameter S = ( "S");
S = new new String (S .getBytes ( "ISO-8859-1"), "UTF-. 8");
Ø second way:
the GET request parameter is not the body, but in the URL. The request can not be used setCharacterEncodng () to set the encoding parameters of the GET.
GET process parameters can be encoded in two ways: The first is a set of attributes of the element URIEncoding is UTF-8. That conf \ URIEncoding properties of the elements in server.xml.

Once this property is set, then for a GET parameter directly in the UTF-8 encoding. However, the elements, it is valid for the whole of Tomcat!

 The third encoded JavaScript URL hyperlink to do
to deal with this problem is the GET request parameters using JavaScript to do URL encoding, the contents of the URL encoding is no longer Chinese, so IE6 will not lose byte a.
ff

http://localhost/encoding/EncodingServlet?name=大家好

After using URL encoding, Hello, everyone has become% E5% A4% A7% E5 % AE% B6% E5% A5% BD. So you do not lose a byte.
Val request.getParameter = String ( "NameA");
Val URLDecoder.decode = (Val, "UTF-. 8");
System.out.println (Val);

6. HttpServletRequest request forwarding (server-side jumps forward)
forwards the request is a lot to be used in the Servlet, because when we visit a Servlet when usually perform the business logic of some background, and then jump to a results page, then jump this process is to result page is forwarding the request, for example we do have logged on, we fill in the username and password and then submitted to the Servlet responsible logged in, Servlet do check the user name and password for us, if we are correct, , we will jump to the page login prompt, if the error would jump to the login failure page.
Request forwarding of requests can also be called a jump on the server side, although the page jump but we will find the address bar there will be no change.
request.getRequestDispatcher ( "/ success.html") forward

We can not only jump to static pages (mainly on the follow-up page is a dynamic we often jump to the page prompted a jsp (jsp generated after Servlet), because we want to return to that dynamic pages, all html is not suitable for (the follow-up explain)). May jump to the Servlet, then we can set the values in the current field to the request, in the field of (before the current request is completed) have access to the property value.
request.setAttribute ( "name", "any bright");
the request.getAttribute ( "name");

Scope 7.request field
in a talk we mentioned the concept of the ServletContext object it is also a domain, its scope is very large, is the designated public projects subject to all of the Servlet with the start of server generated, stop the server destroys, then the request is also a domain object, it is the role of small-scale multi, its scope only in response to a request within the scope of the request of each thread will produce a new HttpServletRequest and HttpServletResponse objects

Published 34 original articles · won praise 6 · views 3677

Guess you like

Origin blog.csdn.net/qq_35986709/article/details/85703675