JavaWeb学习笔记(8)——request和response对象

时间:2020-12-19 13:17:38
Response对象: 一、在Servlet中控制输出中文:
1、通过getoutputstream方法
 // 程序以什么码表输,就要控制浏览器以什么码表打开
  private void test1(HttpServletResponse response) throws IOException,
    UnsupportedEncodingException {
   // 注意:若 "text/html;charset=utf-8"中的分号写成逗号则变为下载文件
   response.setHeader("Content-type","text/html;charset=utf-8");
   String data = "中国";    response.getOutputStream().write(data.getBytes("utf-8"));
  }
 
 // 另一种方式:通过html技术中的meta技术模拟了一个http响应头,来控制浏览器的行为
  private void test2(HttpServletResponse response) throws IOException,
    UnsupportedEncodingException {
   String data = "中国";    response.getOutputStream().write(
     "<meta http-equiv='Content-type' content='text/html;charset=utf-8'>"
       .getBytes());
   response.getOutputStream().write(data.getBytes("utf-8"));
  }  
2、通过getwriter方法
private void test2(HttpServletResponse response) throws IOException {
  
  response.setContentType("text/html;charset=UTF-8");
  /*
  具体实现:
  //控制response输出的码表
  response.setCharacterEncoding("UTF-8");
  
  //指定浏览器输出的码表与response的码表一致
  response.setHeader("Content-type", "text/html;charset=utf-8");
  */
  
  String data = "美国";
  PrintWriter pw = response.getWriter();
  pw.write(data);
 }
 
二、文件下载
private void test(HttpServletResponse response)
   throws UnsupportedEncodingException, FileNotFoundException,
   IOException {
  String path = this.getServletContext().getRealPath("/download/花菇.jpg");
  String filename = path.substring(path.lastIndexOf("\\")+1);
  
  //如果文件名是中文,要对文件名进行utf-8编码以避免出现乱码
  response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
  
  InputStream in = null;
  OutputStream out = null;
  try {
   in = new FileInputStream(path);
   int len = 0;
   byte buffer[] = new byte[1024];
   out = response.getOutputStream();
   while ((len = in.read(buffer)) > 0) {
    out.write(buffer, 0, len);
   }
  } finally {
   if (in != null) {
    try {
     in.close();
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
   if (out != null) {
    try {
     out.close();
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  }
 }
 
三、输出随机图片(即验证码)
public class ResponseDemo4 extends HttpServlet {
 public static final int WIDTH = 130;
 public static final int HEIGHT = 35;
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
    BufferedImage.TYPE_INT_RGB);
  Graphics g = image.getGraphics();
  
  //设置背景色
  setBackgroud(g);
  
  //设置边框
  setBoader(g);
  
  //设置干扰线
  setRandomLine(g);
  
  //设置随机数
  setRandomNum((Graphics2D)g);
    
  //控制浏览器不缓存
  response.setDateHeader("Expries", -1);
  response.setHeader("Cache-Control", "no-cache");
  response.setHeader("Pragma", "no-cache");
  
  //将图形写入浏览器
  response.setContentType("image/jpeg");  
  ImageIO.write(image, "jpg", response.getOutputStream());
 }
 private void setRandomNum(Graphics2D g) {
  // TODO Auto-generated method stub
  g.setColor(Color.RED);
  g.setFont(new Font("宋体", Font.BOLD, 20));
  
  //常用汉字的编码
  String base = "\u7684\u4e00\u662f\u4e86\u6211\u4e0d\u4eba\u5728\u4ed6\u6709\u8fd9\u4e2a\u4e0a\u4eec\u6765\u5230\u65f6\u5927\u5730\u4e3a\u5b50\u4e2d\u4f60\u8bf4\u751f\u56fd\u5e74\u7740\u5c31\u90a3\u548c\u8981\u5979\u51fa\u4e5f\u5f97\u91cc\u540e\u81ea\u4ee5\u4f1a\u5bb6\u53ef\u4e0b\u800c \u8fc7\u5929\u53bb\u80fd\u5bf9\u5c0f\u591a\u7136\u4e8e\u5fc3\u5b66\u4e48\u4e4b\u90fd\u597d\u770b\u8d77\u53d1\u5f53\u6ca1\u6210\u53ea\u5982\u4e8b\u628a\u8fd8\u7528\u7b2c\u6837\u9053\u60f3\u4f5c\u79cd\u5f00\u7f8e\u603b\u4ece\u65e0\u60c5\u5df1\u9762\u6700\u5973\u4f46\u73b0\u524d\u4e9b\u6240\u540c\u65e5\u624b\u53c8\u884c\u610f\u52a8\u65b9\u671f\u5b83\u5934\u7ecf\u957f\u513f\u56de\u4f4d\u5206\u7231\u8001\u56e0\u5f88\u7ed9\u540d\u6cd5\u95f4\u65af\u77e5\u4e16\u4ec0\u4e24\u6b21\u4f7f\u8eab\u8005\u88ab\u9ad8\u5df2\u4eb2\u5176\u8fdb\u6b64\u8bdd\u5e38\u4e0e\u6d3b\u6b63\u611f\u89c1\u660e\u95ee\u529b\u7406\u5c14\u70b9\u6587\u51e0\u5b9a\u672c\u516c\u7279\u505a\u5916\u5b69\u76f8\u897f\u679c\u8d70\u5c06\u6708\u5341\u5b9e\u5411\u58f0\u8f66\u5168\u4fe1\u91cd\u4e09\u673a\u5de5\u7269\u6c14\u6bcf\u5e76\u522b\u771f\u6253\u592a\u65b0\u6bd4\u624d\u4fbf\u592b\u518d\u4e66\u90e8\u6c34\u50cf\u773c\u7b49\u4f53\u5374\u52a0\u7535\u4e3b\u754c\u95e8\u5229\u6d77\u53d7\u542c\u8868\u5fb7\u5c11\u514b\u4ee3\u5458\u8bb8\u7a1c\u5148\u53e3\u7531\u6b7b\u5b89\u5199\u6027\u9a6c\u5149\u767d\u6216\u4f4f\u96be\u671b\u6559\u547d\u82b1\u7ed3\u4e50\u8272\u66f4\u62c9\u4e1c\u795e\u8bb0\u5904\u8ba9\u6bcd";
  int x = 5;
  for(int i=0;i<4;i++){
   int degree  = new Random().nextInt()%30;
   String ch = base.charAt(new Random().nextInt(base.length()))+"";
   g.rotate(degree*Math.PI/180, x, 20);
   g.drawString(ch, x, 20);
   g.rotate(-degree*Math.PI/180, x, 20);
   x+=30;
  }
 }
 private void setRandomLine(Graphics g) {
  // TODO Auto-generated method stub
  g.setColor(Color.GREEN);
  
  for(int i=0;i<5;i++){
   
   int x1 = new Random().nextInt(WIDTH);
   int y1 = new Random().nextInt(HEIGHT);
   
   int x2 = new Random().nextInt(WIDTH);
   int y2 = new Random().nextInt(HEIGHT);
   
   g.drawLine(x1, y1, x2, y2);
  }
 }
 private void setBoader(Graphics g) {
  // TODO Auto-generated method stub
  g.setColor(Color.BLUE);
  g.drawRect(1, 1, WIDTH-2, HEIGHT-2);
 }
 private void setBackgroud(Graphics g) {
  // TODO Auto-generated method stub
  g.setColor(Color.WHITE);
  g.fillRect(0, 0, WIDTH, HEIGHT);
 }
 
四、控制页面的自动刷新和缓存
//控制页面刷新的简单demo
private void test1(HttpServletResponse response) throws IOException {
  response.setHeader("refresh", "2");
  String data = new Random().nextInt(9999)+"";
  response.getOutputStream().write(data.getBytes());
 }
//控制页面缓存的简单demo 
private void test(HttpServletResponse response) throws IOException {
  response.setDateHeader("expires", System.currentTimeMillis()+1000*3600);
  
  String data = "a simple expiresDemo";
  response.getOutputStream().write(data.getBytes());
 }
 
五、页面转发和重定向技术
//页面转发Dispatcher
private void test2(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
  
  //假设这是一个用于处理登陆的Servlet,且用户登录成功了  
  String message = "<meta http-equiv='refresh' content='3;url=/day4/index.jsp'>登录成功!如果没有跳转成功,请点击<a href=''>此链接</a>";
  this.getServletContext().setAttribute("message", message);
  this.getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
  
 } 
/*
 * 重定向的特点:
 * 1、浏览器会向服务器发送两次请求,所以会有两个response/request
 * 2、用重定向技术,地址栏会发生变化
 *
 * 常见于登录模块和购物车模块的设计中
 * */
private void test(HttpServletResponse response) throws IOException {
  /*请求重定向的具体实现:
   * response.setStatus(302);
   * response.setHeader("location", "/day4/index.jsp");
   */
  response.sendRedirect("/day4/index.jsp");
 }
 
request对象
一、request中的常用方法:
private void test(HttpServletRequest request) {
  //返回请求行中的资源名部分
  System.out.println("URI:" + request.getRequestURI());
  //返回客户端发出请求时的完整URL
  System.out.println("URL:" + request.getRequestURL());
  // http://localhost:8080/day4/servlet/RequestDemo1?name=querynameDemo
  //返回请求行中的参数部分
  System.out.println("queryname:" + request.getQueryString());
  
  //返回发出请求的客户机IP地址
  System.out.println("RemoteAddr:" + request.getRemoteAddr());
  //返回发出请求的客户机完整主机名
  System.out.println("RemoteHost:" + request.getRemoteHost());
  //返回客户机所使用的端口号
  System.out.println("RemotePort:" + request.getRemotePort());
  
  //返回服务器的IP地址
  System.out.println("LocalAddr:" + request.getLocalAddr());
  //返回服务器的主机名
  System.out.println("LocalName" + request.getLocalName());
  
  //得到客户机的请求方式
  System.out.println("Method:" + request.getMethod());
 }
二、获取请求头和数据
//获取请求头的方法
 private void test1(HttpServletRequest request) {
  /*
  System.out.println("------------------------");
  String headValue = request.getHeader("Accept-Encoding");
  System.out.println(headValue);
  
  System.out.println("------------------------");
  Enumeration e = request.getHeaders("Accept-Encoding");
  while(e.hasMoreElements()){
   String value = (String) e.nextElement();
   System.out.println(value);
  }
  */
  
  System.out.println("------------------------");
  Enumeration e = request.getHeaderNames();
  while(e.hasMoreElements()){
   String name = (String) e.nextElement();
   String value = request.getHeader(name);
   System.out.println(name + ":" + value);
  }
 }
//获取数据的方法
private void test2(HttpServletRequest request) {
  System.out.println("---------获取数据的方式1---------------");
  String value = request.getParameter("username");
  //注意,拿到数据使用前必须要先检查数据
  if(value!=null&&!value.trim().equals("")){
   System.out.println(value);
  }
  
  System.out.println("---------获取数据的方式2---------------");
  Enumeration e = request.getParameterNames();
  while(e.hasMoreElements()){
   String name = (String) e.nextElement();
   value = request.getParameter(name);
   System.out.println(name + "=" + value);
  }
 }
//乱码问题的解决
//方法二:手动处理,用于任何情况
 private void test2(HttpServletRequest request)
   throws UnsupportedEncodingException {
  String name = request.getParameter("username");
  name = new String(name.getBytes("iso8859-1"),"utf-8");
  System.out.println(name);
 }
 //方法一:只对post方法有效
 private void test1(HttpServletRequest request)
   throws UnsupportedEncodingException {
  request.setCharacterEncoding("utf-8");//只对post方法有效
  String name = request.getParameter("username");
  System.out.println(name);
 }
 
三、请求转发和MVC模式
/*
请求转发,以及使用request域将数据带给转发资源
请求转发的特点:
1、客户端只有一次请求,而服务器端有多个资源调用
2、客户端浏览地址栏没有发生变化
MVC模式:m  module(javabean)  v  view(jsp) c controlle(servlet)r
*/
private void test(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  String data = "requestdispatcher";
  request.setAttribute("data", data);
  
  request.getRequestDispatcher("/message.jsp").forward(request, response);
 }
//在jsp中取数据有以下两种方式:
  ${data}
  <!-- 等价于以下代码 -->>
  <%
   String data = (String) request.getAttribute("data");
   out.write(data);
  %>
 
四、防盗链应用
private void test(HttpServletRequest request, HttpServletResponse response)
   throws IOException {
  String referer = request.getHeader("referer");
  //检查请求头referer是否为空或来自诱导页面
  if(referer==null||referer.startsWith("http:///localhost")){
   response.sendRedirect("/day4/index.jsp");
   return;
   //注意一定要写return,否则可能会导致下面的代码一同执行
  }
  
  response.setContentType("text/html;charset=utf-8");
  String data = "精美套图";
  response.getWriter().write(data);
 }