1.什么是HttpServletResponse
2.使用HttpServletResponse向浏览器发送数据及相关实例。
HttpServletResponse:以在发送一个响应消息时提供 指定的HTTP功能性。例如它有访问HTTP 头和cookies的方法.servlet容器创建一个 HttpServletRequest
对象并将之作为一个参数传递给 servlet的 service方法 (如doGet
, doPost
等).
public void test(HttpServletResponse response) throws IOException { String date = "hello!"; //设置response使用的码表,以控制response以什么码表向浏览器写数据 response.setCharacterEncoding("UTF-8"); //指定浏览器以什么码表去读取传输过来的数据, response.setHeader("Content-type", "text/html;charset=UTF-8"); //response.setContentType("text/html;charset=UTF-8");//开发中不建议这样使用 PrintWriter pr=response.getWriter(); pr.write(date); }
在这里要注意一个乱码问题:以什么样的码表向浏览器写数据,浏览器就要用什么样的码表去读取传输过来是数据。如果两者分别使用的码表不一致,则会导致乱码问题。
我这里是用字节流向浏览器写数据,数据的读写分为两大板块:字节流,字符流,根据实际情况使用,当数据中全是字符类型的话可以使用字符流,否则的话使用字节流:比如读取一部影片就要使用字节流。
最保险的方法就是:无论读写什么样的数据都使用字节流。
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; 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; public class Response1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = this.getServletContext().getRealPath("/download/斗地主.png"); String filename = path.substring(path.lastIndexOf("\") + 1); // 如果下载文件是中文文件,则文件名需要经过URI编码 response.setContentType("text/html;charset=UTF-8");//开发中不建议这样使用
//Content-Disposition:浏览器弹出下载对话框 response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(filename, "UTF-8")); ServletOutputStream out = response.getOutputStream(); download(out, path); } //文件下载方法,通用 private void download(ServletOutputStream responseout, String path) { InputStream in = null; OutputStream out = null; try { try { in = new FileInputStream(path); int len = 0; byte buffer[] = new byte[1204]; out = responseout; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } finally { if (in != null) { try { in.close(); } catch (Exception e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (Exception e) { e.printStackTrace(); } } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.PrintWriter; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Response2 extends HttpServlet { public static final int HEIGHT = 30; public static final int WHITH = 120; public static String context=""; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedImage image = new BufferedImage(WHITH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); // 设置背景色 setBackground(g); // 设置边框 setBorder(g); // 设置干扰线 setRandomLine(g); // 写随机数 setRandomNum((Graphics2D) g); // 图形给浏览器 response.setContentType("image/jpeg"); // 发头,控制浏览器不要缓存 response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); ImageIO.write(image, "jpg", response.getOutputStream()); // String password =request.getParameter("userpassword"); // System.out.println("网页验证码为:"+request.getAttribute(password)); // System.out.println("验证码为:"+context); // if(!context.equals(password)){ // System.out.println("验证码输入错误!"); // }else{ // System.out.println("验证码输入正确!"); // } } private void setBackground(Graphics g) { g.setColor(Color.WHITE); g.fillRect(0, 0, WHITH, HEIGHT); } private void setBorder(Graphics g) { g.setColor(Color.BLUE); g.drawRect(1, 1, WHITH - 2, HEIGHT - 2); } private void setRandomLine(Graphics g) { g.setColor(Color.GREEN); for (int i = 0; i < 5; i++) { int x1 = new Random().nextInt(WHITH); int y1 = new Random().nextInt(HEIGHT); int x2 = new Random().nextInt(WHITH); int y2 = new Random().nextInt(HEIGHT); g.drawLine(x1, y1, x2, y2); } } private void setRandomNum(Graphics2D g) { g.setColor(Color.RED); g.setFont(new Font("微软雅黑", Font.BOLD, 15)); // 准备常用汉字集 String base = "u7684u4e00u4e86u662fu6211u4e0du5728u4ebau4eecu6709u6765u4ed6u8fd9u4e0au7740u4e2au5730u5230u5927u91ccu8bf4u5c31u53bbu5b50u5f97u4e5fu548cu90a3u8981
u4e0bu770bu5929u65f6u8fc7u51fau5c0fu4e48u8d77u4f60u90fdu628au597du8fd8u591au6ca1u4e3au53c8u53efu5bb6u5b66u53eau4ee5u4e3bu4f1au6837u5e74u60f3u751fu540cu8001u4e2du5341u4ece
u81eau9762u524du5934u9053u5b83u540eu7136u8d70u5f88u50cfu89c1u4e24u7528u5979u56fdu52a8u8fdbu6210u56deu4ec0u8fb9u4f5cu5bf9u5f00u800cu5df1u4e9bu73b0u5c71u6c11u5019u7ecfu53d1
u5de5u5411u4e8bu547du7ed9u957fu6c34u51e0u4e49u4e09u58f0u4e8eu9ad8u624bu77e5u7406u773cu5fd7u70b9u5fc3u6218u4e8cu95eeu4f46u8eabu65b9u5b9eu5403u505au53ebu5f53u4f4fu542cu9769
u6253u5462u771fu5168u624du56dbu5df2u6240u654cu4e4bu6700u5149u4ea7u60c5u8defu5206u603bu6761u767du8bddu4e1cu5e2du6b21u4eb2u5982u88abu82b1u53e3u653eu513fu5e38u6c14u4e94u7b2c
u4f7fu5199u519bu5427u6587u8fd0u518du679cu600eu5b9au8bb8u5febu660eu884cu56e0u522bu98deu5916u6811u7269u6d3bu90e8u95e8u65e0u5f80u8239u671bu65b0u5e26u961fu5148u529bu5b8cu5374
u7ad9u4ee3u5458u673au66f4u4e5du60a8u6bcfu98ceu7ea7u8ddfu7b11u554au5b69u4e07u5c11u76f4u610fu591cu6bd4u9636u8fdeu8f66u91cdu4fbfu6597u9a6cu54eau5316u592au6307u53d8u793eu4f3c
u58ebu8005u5e72u77f3u6ee1u65e5u51b3u767eu539fu62ffu7fa4u7a76u5404u516du672cu601du89e3u7acbu6cb3u6751u516bu96beu65e9u8bbau5417u6839u5171u8ba9u76f8u7814u4ecau5176u4e66u5750
u63a5u5e94u5173u4fe1u89c9u6b65u53cdu5904u8bb0u5c06u5343u627eu4e89u9886u6216u5e08u7ed3u5757u8dd1u8c01u8349u8d8au5b57u52a0u811au7d27u7231u7b49u4e60u9635u6015u6708u9752u534a
u706bu6cd5u9898u5efau8d76u4f4du5531u6d77u4e03u5973u4efbu4ef6u611fu51c6u5f20u56e2u5c4bu79bbu8272u8138u7247u79d1u5012u775bu5229u4e16u521au4e14u7531u9001u5207u661fu5bfcu665a
u8868u591fu6574u8ba4u54cdu96eau6d41u672au573au8be5u5e76u5e95u6df1u523bu5e73u4f1fu5fd9u63d0u786eu8fd1u4eaeu8f7bu8bb2u519cu53e4u9ed1u544au754cu62c9u540du5440u571fu6e05u9633
u7167u529eu53f2u6539u5386u8f6cu753bu9020u5634u6b64u6cbbu5317u5fc5u670du96e8u7a7fu5185u8bc6u9a8cu4f20u4e1au83dcu722cu7761u5174u5f62u91cfu54b1u89c2u82e6u4f53u4f17u901au51b2
u5408u7834u53cbu5ea6u672fu996du516cu65c1u623fu6781u5357u67aau8bfbu6c99u5c81u7ebfu91ceu575au7a7au6536u7b97u81f3u653fu57ceu52b3u843du94b1u7279u56f4u5f1fu80dcu6559u70edu5c55
u5305u6b4cu7c7bu6e10u5f3au6570u4e61u547cu6027u97f3u7b54u54e5u9645u65e7u795eu5ea7u7ae0u5e2eu5566u53d7u7cfbu4ee4u8df3u975eu4f55u725bu53d6u5165u5cb8u6562u6389u5ffdu79cdu88c5
u9876u6025u6797u505cu606fu53e5u533au8863u822cu62a5u53f6u538bu6162u53d4u80ccu7ec6"; int x = 10; for (int i = 0; i < 4; i++) { int degree = new Random().nextInt() % 30;// -30 +30 String ch = base.charAt(new Random().nextInt(base.length())) + ""; context += ch; g.rotate(degree * Math.PI / 180, x, 15); g.drawString(ch, x, 20); g.rotate(-degree * Math.PI / 180, x, 15); x += 25; } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
html显示代码:
<!DOCTYPE html> <html> <head> <title>index</title> <meta name="keywords" content="keyword1,keyword2,keyword3"> <meta name="description" content="this is my page"> <meta name="content-type" content="text/html; charset=gb2312"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> <script type="text/javascript"> function changerImage(img) { img.src = img.src + "?" + new Date().getTime(); } </script> </head> <body> <form action=""> 用户名:<input type="text" /><br> 密码:<input type="password" name="userpassword"><br> 认证码:<input type="text" name="checkcode"><img src="/day-02/Response2" onclick="changerImage(this)" style="cursor:pointer;"><br> <input type="button" value="注册"> </form> </body> </html>
实现效果:
import java.io.IOException; import java.io.PrintWriter; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Response3 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { test2(request, response); } //自动跳转技术 public void test2(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //在开发中最实用的 response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8");// 开发中不建议这样使用 String message="<meta http-equiv='refresh' content='3;url=/day-02/index.jsp'>恭喜你 !登录成功!本浏览器将在3秒后跳转到首页,如果没有跳,请点<a href=''>请继续</a>"; this.getServletContext().setAttribute("message", message); //页面跳转 this.getServletContext().getRequestDispatcher("/message.jsp").forward(request, response); } public void test1(HttpServletResponse response) throws IOException { // 假设这是一个用于处理登录的Servlet // 假设程序用运行到此,用户登录成功! response.setContentType("text/html;charset=UTF-8");// 开发中不建议这样使用 response.setHeader("refresh", "3;url='/day-02/index.html'"); response.getWriter().write("恭喜你 !登录成功!本浏览器将在3秒后跳转到首页,如果没有跳,请点<a href=''>请继续</a>"); } public void test(HttpServletResponse response) throws IOException { // 浏览器每过一秒刷新一次 response.setHeader("refresh", "1"); String date = new Random().nextInt(10000) + ""; response.getWriter().write(date); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
为什么要使用页面缓存:在实际开发中,为了实现二次加载速度,通常把一些固定的数据缓存起来,入图片,字等等,当浏览器二次访问时,直接从内存中获取缓存数据,不需要再次访问服务器进行数据传递。
具体实现代码:
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Response4 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*Expires实体报头域给出响应过期的日期和时间。为了让代理服务器或浏览器在一段时间以后更新缓存中(再次访问曾访问过的页面时, * 直接从缓存中加载,缩短响应时间和降低服务器负载)的页面,我们可以使用Expires实体报头域指定页面过期的时间。 * eg:Expires:Thu,15 Sep 2006 16:23:12 GMT HTTP1.1的客户端和缓存必须将其他非法的日期格式(包括0)看作已经过期。eg:为了让浏览器不要缓存页面, 我们也可以利用Expires实体报头域,设置为0,jsp中程序如下:response.setDateHeader("Expires","0"); */ response.setDateHeader("expires", System.currentTimeMillis()+1000*3600);//指定一小时后再向服务器在发送请求 String date="aaaaaaa"; response.getWriter().write(date); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Response5 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.浏览器会向服务器发送两次请求,意味着有两个request,response //2.用重定向技术,浏览器地址栏会发生变化 //请求重定向,登录情况和购物车、下必须要用请求重定向 /*response.setStatus(302); response.setHeader("location", "/day-02/index.jsp");*///同下面代码功能相同 response.sendRedirect("/day-02/index.jsp"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }