httpservletrespons
We will overwrite the service () method when creating the servlet, or doget ()/dopost (), which have two parameters, one for the request requested and the representative response response.
The type of response in the service method is Servletresponse, and the response type of the Doget/dopost method is HttpServletResponse, HttpServletResponse is a servletresponse sub-interface, with more powerful functions and methods.
request and response process for Tomcat under Servlet
Set HTTP response
Because the response represents a response, we can set the response line of the HTTP response, the response header and the response body, respectively, by this object
first, set the response line
Setting the response status code
Example: Setting redirection
Response.sendredirect ("http://www.baidu.com");
The following two lines of code are actually executed
Response.setstatus (302); Setting 302 Response Codes
Response.setheader ("Location", "http://www.baidu.com")//Set response header, redirect
1 <!DOCTYPE HTML>2 <HTML>3 <Head>4 <MetaCharSet= "UTF-8">5 <title>Insert Title here</title>6 </Head>7 <Body>8Congratulations, your registration is successful,<spanstyle= "Color:red"ID= "Second">5</span>Seconds after jump, if not jump click<ahref= "Http://www.baidu.com">Over here</a>!.9 <Scripttype= "Text/javascript">Ten window.onload= function(){ <!--execute after page load - One var Time= 5; A varSecondele=document.getElementById ("Second"); - varTimer=SetInterval (function(){ - secondele.innerhtml=Time ; the Time--; - if( time==0){ - clearinterval (timer); <!--Clear Timer - - Location.href="http://www.baidu.com"; <!--page Jump - + } - + }, +); <!--Timer - A } at - - <!--Timer format: setinterval (per specified millisecond value, function performed) (millisecond value) - - </Script> - </Body> - </HTML>
JS version jump pagesecond, set the response header
Response.setheader (Key,value)
Example:
Response.setheader ("Refresh", "5;url=http://www.baidu.com"); Set page load after 5s jump to the specified URL
third, set the response body
1) Set the response text
Response.getwriter (). Write ("Hello, World.");
Chinese garbled problem
Reason: There is a response buffer on the server side, when we write "Hello, world." , the iso-8859-1 encoding table will be queried to convert it into byte form , but there is no Chinese in this encoding table, so the return is a heap?
Workaround:
Response.setcharacterencoding ("UTF-8"); Sets the encoding set for the buffer to UTF-8 format
Response.setheader ("Content-type", "text/html; Charset=utf-8"); Set the response header to UTF-8 format
Easy mode
Response.setcontenttype ("text/html; Charset=utf-8 ");
Javaweb--httpservletresponse