Servlet-HttpServletResponse
Servlet-HttpServletResponse
HttpServletResponse是一个接口,其父接口是ServletResponse
他是由Tomcat将请求报文转换封装而来的对象,在Tomcat调用service时传入
他代表着对客户端的响应,该对象会被转换成响应报文发送给客户端,通过该对象我们可以设置响应信息
设置响应行相关
API | 说明 |
---|---|
void setStatus(int code) | 设置响应状态 |
@WebServlet("/HttpServletResponseTest")
public class HttpServletResponseTest extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setStatus(404);//故意响应404
}
}
设置响应头相关
API | 说明 |
---|---|
void setHeader(String headerName,String headerValue) | 设置/修改响应头键值对 |
void setContentType(String contentType) | 设置content-type响应头及相应字符集(设置MIME类型) |
void setContentLength(int length) | 设置content-length响应头(设置响应体的字节长度) |
@WebServlet("/HttpServletResponseTest")
public class HttpServletResponseTest extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//这两种方法是一样的,是因为Content参数过于重要,所以单独出现了API
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")*😦
@WebServlet("/HttpServletResponseTest")
public class HttpServletResponseTest extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String info = "<h1>hello</h1>";
//先转成字符串转字节数组,再获取长度,作为content-length的参数,这里的字符串如果有中文,要写成getBytes("UTF-8")
resp.setContentLength(info.getBytes().length);
PrintWriter writer = resp.getWriter();
writer.write(info);
}
}
getOutputStream()
ServletOutputStream outputStream = resp.getOutputStream();//获取字节输出流,将文件通过此流写入响应体中
其他API
API | 说明 |
---|---|
void sendError(int code,String message) throws IOException | 向客户端相应错误信息的方法,需要制定响应码和响应信息 |
void addCookie(Cookie cookie) | 向响应体中增加cookie |
void setCharacterEncoding(String encoding) | 设置响应体字符集 |