自我体会:
HttpServletResponse中response主要是设置响应行,响应头,响应体 其中响应行 主要设置状态码 (重定向时设置为302)
响应头 主要设置(键值对形式)Location重定向 Content-Type编码类型 取值:text/html;charset=UTF-8 Refresh定时刷新
响应体设置文本和字节
一、运行流程:
二、运行描述
用户在客户端输入网址(虚拟路径)时,开始发送一个HTTP请求(请求行、请求头、请求体)至服务器。服务器内的Tomcat引擎会解析请求的地址,去找XML文件,然后根据虚拟路径找Servlet的真实路径,真实的Servlet会将请求的信息封装成request(请求)对象,然后再创建一个response(响应)对象,(此时的response内是空的)同时创建servlet对象,并调用service方法(或doGet和doPost方法)。这样就是把两个对象传给了服务器内的某个servlet的service方法,通过这个方法,我们可以获得request的所有的信息,并且向response内设置信息。response.getwriter().write()将内容写到response的缓冲区,这样service方法结束了,方法返回后,tomcat引擎会将从该response缓冲区中获取的设置信息封装成一个HTTP响应(响应行、响应头、响应体),发送给客户端。客户端解析响应回来的东西继而进行显示。
我们可以通过设置修改响应的信息进行相应的重定向(用户访问的网页不存在并跳转到其他网页上)、修改响应文本(需要修改浏览器和服务器两边的编码,并且还得处理兼容问题)。
三、通过response 设置响应行:
设置响应行的状态码:setStatus( int sc)
package com.oracle.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LineServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置响应行状态码 response.setStatus(404); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
四、通过response 设置响应头:
setHeader(String name,String value) 设置
1、重定向:(请求服务器两次,地址栏变化)
①、状态码:302;
②、响应头:location 代表重定向地址;
package com.oracle.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HeadServlet01 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*//重定向:1.设置状态码302 response.setStatus(302); //2.设置Location响应头 response.setHeader("Location", "/WEB03/HeadServlet02");*/ //开发中实际重定向的方法 response.sendRedirect("/WEB03/HeadServlet02"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } package com.oracle.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HeadServlet02 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("hello dandan..."); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
2.设置 Content-Type编码类型解决中文乱码问题
package com.oracle.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class BodyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置response缓冲区码表 //response.setCharacterEncoding("utf-8"); //设置页面码表 response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("你好"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
关于设置中文的乱码问题
原因:response缓冲区的默认编码是iso8859-1,此码表中没有中文,可以通过 response的setCharacterEncoding(
String charset)
设置response的编码,
但我们发现客户端还是不能正常显示文字。
原因:我们将response缓冲区的编码设置成UTF-8,但浏览器的默认编码是本地系统的编码,因为我们都是中文系统,所以客户端浏览器的默认编码是GBK,我们可以手动修改浏览器的编码是UTF-8。
我们还可以在代码中指定浏览器解析页面的编码方式,通过response的setContentType(
String type)
方法指定页面解析时的编码是UTF-8。
response.setContentType("text/html;charset=UTF-8");
上面的代码不仅可以指定浏览器解析页面时的编码,同时也内含 setCharacterEncoding的功能,所以在实际开发中只要编写 response.setContentType("text/html;charset=UTF-8"),就可以解决页面输出中文乱码问题。
3.定时刷新
response.setHeader("Refresh", "5;url=https://www.baidu.com");
package com.oracle.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RefreshServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置定时刷新头 response.setHeader("Refresh", "5;url=https://www.baidu.com"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
js实现
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> window.onload=function(){ var time=5; //获取second对象 var second=document.getElementById("second"); //设置定时器 var timer=setInterval(function () { second.innerHTML=time; time--; if (time==0) { //取消定时器 clearInterval(timer); //跳转 location.href="https://www.baidu.com"; } }, 1000) } </script> </head> <body> 恭喜你,注册成功! <span id="second" style="color:red">5</span>秒跳转,逐步跳转,请点击<a href="https://www.baidu.com">这里</a> </body> </html>
五、通过response 设置响应体:
1、响应体设置文本:
PrintWriter
getWriter()
获得字符流,通过字符流的write(
String s)
方法可以将字符串设置到response 缓冲区中,随后Tomcat会将response缓冲区中的内容组装成Http响应返回给浏览 器端。
2、响应体设置字节
ServletOutputStream
getOutputStream()
获得字节流,通过该字节流的write(byte[] bytes)可以向response缓冲区中写入字 节,在由Tomcat服务器将字节内容组成Http响应返回给浏览器
图片复制
package com.oracle.web; import java.io.FileInputStream; import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ImgServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取ServletContext对象 ServletContext context=getServletContext(); //获取a.png在服务器中的路径 String path=context.getRealPath("a.png"); //明确数据源 FileInputStream fis=new FileInputStream(path); //明确目的地 ServletOutputStream out=response.getOutputStream(); //开始复制 int len=0; byte bytes[]=new byte[1024]; while ((len=fis.read(bytes))!=-1) { out.write(bytes,0,len); } //关闭服务器 fis.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
.zip文件复制
package com.oracle.web; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.sun.org.apache.bcel.internal.generic.AALOAD; public class ZipServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取ServletContext对象 ServletContext context=getServletContext(); //找到实体路径 String path=context.getRealPath("aa.zip"); //明确数据源 FileInputStream fis=new FileInputStream(path); //明确目的地 ServletOutputStream out=response.getOutputStream(); //复制 byte bytes[]=new byte[1024]; int len=0; while ((len=fis.read(bytes))!=-1) { out.write(bytes,0,len); } //释放资源 fis.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
如果下载中文文件,页面在下载时会出现中文乱码或不能显示文件名的情况, 原因是不同的浏览器默认对下载文件的编码方式不同,ie是UTF-8编码方式,而火狐 浏览器是Base64编码方式。所里这里需要解决浏览器兼容性问题,解决浏览器兼容 性问题的首要任务是要辨别访问者是ie还是火狐(其他),通过Http请求体中的一 个属性可以辨别
解决乱码方法如下(不要记忆--了解):
String filenameEncoder=””;
if (agent.contains("MSIE")) {
// IE浏览器
filenameEncoder= URLEncoder.encode(filename, "utf-8");
filenameEncoder= filenameEncoder.replace("+", " ");
} else if (agent.contains("Firefox")) {
// 火狐浏览器
BASE64Encoder base64Encoder = new BASE64Encoder();
filenameEncoder= "=?utf-8?B?"
+ base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
} else {
// 其它浏览器
filenameEncoder= URLEncoder.encode(filename, "utf-8");
}
其中agent就是请求头User-Agent的值
package com.oracle.demo01; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import sun.misc.BASE64Encoder; public class DownLoadServlet extends HttpServlet { //http://localhost:8080/WEB04/download.jsp public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取要下载的文件名 String filename=request.getParameter("filename"); //解决请求中文乱码 filename=new String(filename.getBytes("ISO8859-1"),"UTF-8"); //获取User-Agent头判断该客户端是那个浏览器 String agent=request.getHeader("User-Agent"); String filenameEncoder=""; if (agent.contains("MSIE")) { // IE浏览器 filenameEncoder= URLEncoder.encode(filename, "utf-8"); filenameEncoder= filenameEncoder.replace("+", " "); } else if (agent.contains("Firefox")) { // 火狐浏览器 BASE64Encoder base64Encoder = new BASE64Encoder(); filenameEncoder= "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?="; } else { // 其它浏览器 filenameEncoder= URLEncoder.encode(filename, "utf-8"); } //告知浏览器mime类型 response.setContentType(getServletContext().getMimeType(filename)); //告知浏览器该文件以附件方式打开(下载) response.setHeader("Content-Disposition","attachment;filename="+filenameEncoder); //获取绝对路径 String path=getServletContext().getRealPath("download"+File.separator+filename); //明确数据源 FileInputStream fis=new FileInputStream(path); //明确目的地 ServletOutputStream out=response.getOutputStream(); //开始复制 int len=0; byte bytes[]=new byte[1024]; while ((len=fis.read(bytes))!=-1) { out.write(bytes,0,len); } //释放资源 fis.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
response细节点:
- response获得的流不需要手动关闭,web容器(tomcat容器)会帮助我们关闭,
- getWriter和getOutputStream不能同时调用
- 重定向语句一般作为终结代码