Servlet-HttpServletResponse
HttpServletResponse是一个接口,其父接口是ServletResponse
他是由Tomcat将请求报文转换封装而来的对象,在Tomcat调用service时传入
他代表着对客户端的响应,该对象会被转换成响应报文发送给客户端,通过该对象我们可以设置响应信息
设置响应行相关
| API |
说明 |
| void setStatus(int code) |
设置响应状态 |
1 2 3 4 5 6 7
| @WebServlet("/HttpServletResponseTest") public class HttpServletResponseTest extends HttpServlet{ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(404); } }
|
设置响应头相关
| API |
说明 |
| void setHeader(String headerName,String headerValue) |
设置/修改响应头键值对 |
| void setContentType(String contentType) |
设置content-type响应头及相应字符集(设置MIME类型) |
| void setContentLength(int length) |
设置content-length响应头(设置响应体的字节长度) |
1 2 3 4 5 6 7 8 9 10 11
| @WebServlet("/HttpServletResponseTest") public class HttpServletResponseTest extends HttpServlet{ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setHeader("Content-Type","text/html;charset=utf-8"); resp.setContentType("text/html;charset=utf-8"); resp.setHeader("Content-Length","1234"); resp.setContentLength(1234); } }
|
设置响应体相关
| API |
说明 |
| PrintWriter getWriter() throws IOException |
获得向响应体放入信息的字符输出流 |
| ServletOutputStream getOutputStream() throws IOException |
获得向响应体放入信息的字节输出流 |
getWriter()
当包含中文的字符串转成字节数组时,应传参UTF-8作为字符集编码 getBytes(“UTF-8”)😦
1 2 3 4 5 6 7 8 9 10 11
| @WebServlet("/HttpServletResponseTest") public class HttpServletResponseTest extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String info = "<h1>hello</h1>"; resp.setContentLength(info.getBytes().length); PrintWriter writer = resp.getWriter(); writer.write(info); } }
|
getOutputStream()
1
| ServletOutputStream outputStream = resp.getOutputStream();
|
其他API
| API |
说明 |
| void sendError(int code,String message) throws IOException |
向客户端相应错误信息的方法,需要制定响应码和响应信息 |
| void addCookie(Cookie cookie) |
向响应体中增加cookie |
| void setCharacterEncoding(String encoding) |
设置响应体字符集 |