Response设置响应数据功能介绍
1.响应行:HTTP/1.1 200 OK
void setStatus(int sc):设置响应状态码
2.响应头:Content-Type:text、html
void setHeader(String name, String value):设置响应头键值对
3.响应体:<html><head><head><body></body></html>
PrintWriter getWriter():获取字符输出流
ServletOutPutStream getOutPutStream():获取字节输出流
Response完成重定向
重定向:一种资源跳转方式
@WebServlet("/resp1")
public class ResponseDemo1 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("resp1......");
// //重定向
// //1.设置响应状态码
// response.setStatus(302);
// //2.设置响应头Location
// response.setHeader("Location","resp2");
//
//
//简化方法完成重定向
response.sendRedirect("demo1/resp2");
//动态获取虚拟目录
// String contextPath = request.getContextPath();
// response.sendRedirect(contextPath+"/resp2");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
重定向的特点:
1.浏览器地址栏路径发生变化
2.可以重定向到任意位置的资源(服务器的内部、外部均可)
3.两次请求,不能在多个资源使用request共享数据
总结:转发和重定向的区别?
1、转发只发送一次请求:重定向发送两次请求
2、转发时地址栏的地址值不发生改变 :重定向时地址栏的地址发生改变
3、重定向是客户端行为,转发是服务端行为
4、重定向可以跳转到任意URL(可以是本项目下的;也可以是外部的);转发只跳转到本项目下
5、重定向不共享数据:转发一次请求共享数据
Response响应字符数据
@WebServlet("/resp3")
public class ResponseDemo3 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//不仅可以设置html还能设置字符流编码格式为UTF-8
response.setContentType("text/html; charset=UTF-8");
//获取字符输出流
PrintWriter writer = response.getWriter();
//content-type
// response.setHeader("content-type","text/html");
writer.write("你好");
writer.write("<h1>aaaa</h1>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
完成流的copy
采用工具类
在pom.xml配置
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
//3.完成流的copy
IOUtils.copy(fileInputStream, outputStream);