1.HttpServletResponse接口简介
- 该接口来自于Servlet规范中,在Tomcat中存在servlet-api.jar
- 该接口实现类由Http服务器负责提供
- 该接口负责将doPost/doGet方法执行结果写入到【响应体】交给浏览器
- 习惯将该接口修饰的对象称为【响应对象】、
2.主要功能
- 将执行结果以二进制形式写入到【响应体】
- 设置响应头中【content-type】属性值,从而控制浏览器使用,对应编译器将响应体【二进制数据】编译为【文字,图片,视频,命令,,】
- 设置响应头中【location】属性,将一个请求地址赋值给location,从而控制浏览器向指定服务器发送请求
3.实例
抽象类的作用:降低接口实现类对接口实现过程难度
将接口中不需要使用抽象方法交给抽象类进行完成
接口实现类只需要对接口需要的方法进行实现
Tomcat根据Servlet规范调用Servlet接口实现类实例对象
1.Tomcat有权创建Servlet接口实现类实例对象
Servlet OneServlet = new OneServlet();
2.Tomcat根据实例对象调用service方法处理当前请求
3.1输出流
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String str = "hello world!!";
PrintWriter out = response.getWriter();
out.write(str);
}
3.2 输出文本,字符编码
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String result = "java<br/>html<br/>mysql<br/>";
String result2 = "红烧肉";
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.print(result);
out.print(result2);
}
3.3 输出流为数字用print
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int money=40;
PrintWriter out = response.getWriter();
out.println(money);
out.println(money+20);
}
3.4 location属性跳转
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String re = "http://www.baidu.com?userName=f";
resp.sendRedirect(re);
}