response发送状态码
response.sendError(int sc,String msg):发送错误状态码与说明
response.sendError(int sc):发送错误状态码
response.SetStatus(int sc):发送正常状态码
//发送404
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendError(404,"您访问的资源存在,不想显示");
}
response响应头:Content-Type、Refresh、Location等等
setHeader(String name,String value):适用于单值的响应头
addHeader(String name,String value):适用于多值的响应头
setIntHeader(String name,int value):适用于单值的int类型的响应头,如"Content-Length"
addIntHeader(String name,int value)):适用于多值的int类型的响应头
setDateHeader(String name,long value):适用于单值的毫秒类型的响应头,如"expires"(过期)
addDateHeader(String name,long value):适用于多值的毫秒类型的响应头
会出现一个头(一个名字,一个值),也会出现一个头(一个名称,多个值)
response重定向
设置302代码并设置Location
//方法一
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//给出请求uri
response.setHeader("Location","/send404");
response.setStatus(302);
System.out.println("RedirectionServlet");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//快捷的重定向方法(requestURI
response.sendRedirect("/TextServlet");
}
定时跳转并刷新
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//发送响应体
PrintWriter writer = response.getWriter();
writer.print("欢迎XXX登陆,5秒钟后自动跳转到主页!");
//设置名为refresh的响应头
response.setHeader("Refresh","5;URL=/TextServlet");
}
response两个流
1、ServletOutPutStream:用来向客户端发送字节数据(图片)
ServletOutPutStream out = response.getOutPutStream();
//演示响应字节数据
String path = "G:/22.jpg";
FileInputStream in = new FileInputStream(path);
//读取输入流内容的字节到字节数组中
byte[] bytes1 = IOUtils.toByteArray(in);
response.getOutputStream().write(bytes1);
2、PrintWriter:用来向客户端发送字符数据,需要设置编码
PrintWriter writer = response.getWriter();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().print("Hello");
}
两个流不能同时使用