1. Overview of HttpServletResponse
When we create a Servlet, we will override the service()
methods, or doGet()/doPost(), these methods have two parameters, one is the request representing the request and the response representing the response. The type
in the service method response
is ServletResponse
, and the response type of the doGet/doPost method is HttpServletResponse. HttpServletResponse is a sub-interface of ServletResponse with more powerful functions and methods.
2. Grab Http response through packet capture tool
Because response represents the response, we can set the Http response through this objectResponse line,Response headerwithResponse body
Three, set the response line through response
Set the status code of the response line
setStatus(int sc)
response.setStatus(329);
Not much used in development, generally Tomcat will automatically set the status code. We can Baidu status code, the most common status code
Four, set the response header through response
Lists the commonly used methods for setting HTTP response headers. These methods are provided by the HttpServletResponse class.
addHeader(String name, String value)
——Add the response header and string value of the specified nameaddIntHeader(String name, int value)
——Add the response header and int value of the specified nameaddDateHeader(String name, long date)
——Add the response header and date value of the specified namesetHeader(String name, String value)
(重点)
——Use the specified name and value to set the name and content of the response headersetDateHeader(String name, long date)
——Use the specified name and value to set the name and content of the response headersetIntHeader(String name, int value)
——Specify the value of type int to the name header
Analysis of add and set methods:
add means adding, and set means setting
Case number one:
//设置响应头
Date date = new Date();
response.addHeader("name","张三");
//response.addIntHeader("age",28);
//response.addDateHeader("birthday",date.getTime());
response.setHeader("age","50");
Redirection problem: Set the status code and set the response header
step:
- Set status code 302
- Set the response header Location
understanding:
-
302 means temporary redirection. When you visit a url, you are redirected to another url.
Often used for page jumps. -
Add the Location parameter to the response header. When the browser receives a response with a location header, it will jump to the corresponding address.
Case 2:
The first step: writing Servlet1
@WebServlet("/Servlet1")
public class Servlet1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//没有响应 告知客户端去重定向到Servlet2
//1.设置状态码302
response.setStatus(302);
//2.设置响应头Location
response.setHeader("Location","/WEB14/Servlet2");
}
}
Step 2: Write redirected Servlet2
@WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write("hhh");
}
}
Five, set the response body through response
1. Response body setting text
PrintWriter getWriter()
To obtain the character stream, the string can be set into the response buffer by the write(String s) method of the character stream, and then Tomcat will assemble the content in the response buffer into an Http response and return it to the browser.
The most common way of writing is
response.getWriter().write("我是response!!");
2. Regarding the problem of garbled Chinese characters
Reason : The default encoding of the response buffer isiso8859-1, There is no Chinese in this code table, you can setCharacterEncoding(String charset)
set response code through response
But we found that the client still cannot display text normally
Reason : We set the encoding of the response buffer to UTF-8, but the default encoding of the browser is the encoding of the local system, because we are all Chinese systems, soThe default encoding of the client browser is GBKWe canManual modificationThe encoding of the browser is UTF-8.
We can also specify the encoding method for the browser to parse the page in the code, and specify the encoding when the page is parsed
by the response的setContentType(String type)
method to be UTF-8:
generally written as:
response.setContentType("text/html;charset=UTF-8");
The above code can not only specify the encoding when the browser parses the page, but also setCharacterEncoding
the functions it contains ,So just write in the actual development: response.setContentType("text/html;charset=UTF-8")
;
we can solve the problem of Chinese garbled output page.
Case number one:
public class TextServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置response查询的码表
response.setCharacterEncoding("UTF-8");
//通过一个头Content-Type 告知客户端使用何种码表进行解码
response.setHeader("ContentType","text/html;charset=UTF-8");
//该方法与上面方法等价,开发中常用
response.setContentType("text/html;charset=UTF-8");
PrintWriter writer = response.getWriter();
writer.write("hello response!!");
writer.write("中国");
}
Once again, the response.setContentType("text/html;charset=UTF-8");
problem of garbled characters can be solved by writing . If this method is not used, then we must first set the response buffer and set the browser's encoding to be utf-8.
3. Response header setting byte
ServletOutputStream getOutputStream()
Obtain the byte stream, through the write(byte[] bytes) of the byte stream, bytes can be written into the response buffer, and the Tomcat server will return the byte content to the browser as an Http response.
This is very empty, let's make a small demo of uploading a photo on the server to understand the bytes.
Case:
@WebServlet("/ByteServlet")
public class ByteServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//使用responce获得字节输出流
ServletOutputStream out=response.getOutputStream();
//获得服务器上的图片
String RealPath = this.getServletContext().getRealPath("a.jpg");
InputStream in = new FileInputStream(RealPath);
int len = 0;
//字节数组,详细可以常看io流的内容
byte [] buffer = new byte[1024];
while ((len = in.read(buffer))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
}
}
Six, response details
- The stream obtained by response does not need to be closed manually, the Tomcat container will be automatically closed
- getWriter() and getOutputStream cannot be called at the same time