1.介绍:
1)HttpServletResponse接口来自于Servlet规范中,在Tomcat中存在servlet-api.jar
2)HttpServletResponse接口实现类由Http服务器负责提供
3)HttpServletResponse接口负责将doGet/doPost方法执行结果写入到【响应体】交给浏览器
4)开发人员习惯于将HttpServletResponse接口修饰的对象称为【响应对象】
2.主要功能:
- 将执行结果以二进制形式写入到【响应体】
- 设置响应头中[content-type]属性值,从而控制浏览器使用
对应编译器将响应体二进制数据编译为【文字,图片,视频,命令】
public class OneServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String result ="Hello World"; //执行结果
//--------响应对象将结果写入到响应体--------------start
//1.通过响应对象,向Tomcat索要输出流
PrintWriter out = response.getWriter();
//2.通过输出流,将执行结果以二进制形式写入到响应体
//当收到的是数字时,会输出对应的ASC11编码值的数值
//在实际的开发中一般用的是out.print()方法,该方法可以接受任何形式的数据类型
out.write(result);
//--------响应对象将结果写入到响应体--------------start
}//doGet执行完毕
//Tomcat将响应包推送给浏览器
}
- 设置响应头中【location】属性,将一个请求地址赋值给location.
从而控制浏览器向指定服务器发送请求
public class FourServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String result ="http://www.baidu.com?userName=mike";
//通过响应对象,将地址赋值给响应头中location属性
response.sendRedirect(result);//[响应头 location="http://www.baidu.com"]
}
/*
* 浏览器在接收到响应包之后,如果
* 发现响应头中存在location属性
* 自动通过地址栏向location指定网站发送请求
*
* sendRedirect方法远程控制浏览器请求行为【请求地址,请求方式,请求参数】
*/
}