zoukankan      html  css  js  c++  java
  • 4.Servlet的Response和Request

    一.综述

    • web服务器接受到客户端的HTTP请求,对于这个请求分别创建一个代表请求的对象HttpServletRequest和一个代表响应的对象HttpServletResponse。

      • 如果要获得客户端请求过来的参数:找HttpServletRequest

      • 如果要给客户端响应一些参数信息:找HttpServletResponse

    二.HttpServletResponse

     1.简单分类

    负责向浏览器发送数据的方法

    1 public ServletOutputStream getOutputStream() throws IOException;
    2 public PrintWriter getWriter() throws IOException;

    负责向浏览器发送响应头的方法

     1 public void setCharacterEncoding(String charset);
     2 public void setContentLength(int len);
     3 public void setContentLengthLong(long len);
     4 public void setContentType(String type);
     5 public void setBufferSize(int size);
     6 public void setLocale(Locale loc);
     7 
     8 public void setDateHeader(String name, long date);
     9 public void addDateHeader(String name, long date);
    10 public void setHeader(String name, String value);
    11 public void addHeader(String name, String value);
    12 public void setIntHeader(String name, int value);
    13 public void addIntHeader(String name, int value);
    14 public void setStatus(int sc);

     响应的状态码常量

     1 int SC_CONTINUE = 100;
     2 int SC_SWITCHING_PROTOCOLS = 101;
     3 int SC_OK = 200;
     4 int SC_CREATED = 201;
     5 int SC_ACCEPTED = 202;
     6 int SC_NON_AUTHORITATIVE_INFORMATION = 203;
     7 int SC_NO_CONTENT = 204;
     8 int SC_RESET_CONTENT = 205;
     9 int SC_PARTIAL_CONTENT = 206;
    10 int SC_MULTIPLE_CHOICES = 300;
    11 int SC_MOVED_PERMANENTLY = 301;
    12 int SC_MOVED_TEMPORARILY = 302;
    13 int SC_FOUND = 302;
    14 int SC_SEE_OTHER = 303;
    15 int SC_NOT_MODIFIED = 304;
    16 int SC_USE_PROXY = 305;
    17 int SC_TEMPORARY_REDIRECT = 307;
    18 int SC_BAD_REQUEST = 400;
    19 int SC_UNAUTHORIZED = 401;
    20 int SC_PAYMENT_REQUIRED = 402;
    21 int SC_FORBIDDEN = 403;
    22 int SC_NOT_FOUND = 404;
    23 int SC_METHOD_NOT_ALLOWED = 405;
    24 int SC_NOT_ACCEPTABLE = 406;
    25 int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
    26 int SC_REQUEST_TIMEOUT = 408;
    27 int SC_CONFLICT = 409;
    28 int SC_GONE = 410;
    29 int SC_LENGTH_REQUIRED = 411;
    30 int SC_PRECONDITION_FAILED = 412;
    31 int SC_REQUEST_ENTITY_TOO_LARGE = 413;
    32 int SC_REQUEST_URI_TOO_LONG = 414;
    33 int SC_UNSUPPORTED_MEDIA_TYPE = 415;
    34 int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    35 int SC_EXPECTATION_FAILED = 417;
    36 int SC_INTERNAL_SERVER_ERROR = 500;
    37 int SC_NOT_IMPLEMENTED = 501;
    38 int SC_BAD_GATEWAY = 502;
    39 int SC_SERVICE_UNAVAILABLE = 503;
    40 int SC_GATEWAY_TIMEOUT = 504;
    41 int SC_HTTP_VERSION_NOT_SUPPORTED = 505;

    2.常见应用

    1. 向浏览器输出消息

    2. 下载文件

      1. 获得要下载文件的路径和文件名

      2. 设置浏览器能够支持下载

      3. 获取下载文件的输入流

      4. 创建缓冲区

      5. 获取OutputStream对象

      6. 将FileOutputStream流写入到buffer缓冲区中

      7. 使用OutputStream将缓冲区中的数据输出到客户端

    3. 验证码功能

    4. 实现重定向:使用场景用户登陆

    注:

    • 重定向的 / 表示:http://服务器ip:端口/    ,重定向编码302

    • 请求转发的 / 表示:http://服务器ip:端口/项目名  ,请求转发编码307

     

    下载文件代码:

     1 public class FileServlet extends HttpServlet {
     2     @Override
     3     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     4         //1.获取要下载的文件路径
     5         String realPath = "F:\java_code\ServletCode\Servlet-response\src\main\resources\1.jpg";
     6         System.out.println("下载文件的路径:" + realPath);
     7 
     8         //2.获取下载文件名
     9         String fileName = realPath.substring(realPath.lastIndexOf("\") + 1);
    10 
    11         //3.设置浏览器支持,设置将文件名进行编码,防止中文乱码
    12         resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    13 
    14         //4.获取下载文件的输入流
    15         FileInputStream in = new FileInputStream(realPath);
    16 
    17         //5.创建缓冲区
    18         int len = 0;
    19         byte[] buffer = new byte[1024];
    20 
    21         //6.获取OutputStream对象
    22         ServletOutputStream out = resp.getOutputStream();
    23 
    24         //7.将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端
    25         while ((len = in.read(buffer)) > 0) {
    26             out.write(buffer, 0, len);
    27         }
    28 
    29         in.close();
    30         out.close();
    31 
    32 
    33     }
    34 
    35     @Override
    36     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    37         doGet(req, resp);
    38     }
    39 }

    验证码功能:

     1 public class ImageServlet extends HttpServlet {
     2     @Override
     3     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
     4 
     5         //设置浏览器3秒刷新一次
     6         resp.setHeader("refresh","3");
     7 
     8         //在内存中建立一个图片
     9         BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
    10 
    11         //得到图片
    12         Graphics2D g = (Graphics2D) image.getGraphics();
    13 
    14         //设置图片样式
    15         g.setColor(Color.gray);
    16         g.fillRect(0,0,80,20);
    17 
    18         //给图片填充数据
    19         g.setColor(Color.orange);
    20         g.setFont(new Font(null,Font.BOLD,20));
    21         g.drawString(makeNum(7),0,20);
    22 
    23         //设置浏览器打开图片的方式
    24         resp.setContentType("image/jpeg");
    25         //设置浏览器不缓存
    26         resp.setDateHeader("expires",-1);
    27         resp.setHeader("Cache-Control","no-cache");
    28         resp.setHeader("Pragma","no-cache");
    29 
    30         //将图片写给浏览器
    31         ImageIO.write(image,"jpg",resp.getOutputStream());
    32 
    33     }
    34 
    35     //生成随机数
    36     private String makeNum(int len) {
    37         Random random = new Random();
    38         StringBuffer num = new StringBuffer();
    39         while (len > 0) {
    40             num.append(random.nextInt(9) + "");
    41             len--;
    42         }
    43         return num.toString();
    44     }
    45 
    46     @Override
    47     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    48         doGet(req, resp);
    49     }
    50 }

    重定向实现

     1 public class RedirectServlet extends HttpServlet {
     2     @Override
     3     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     4 
     5         /*
     6         传入参数为项目打包的路径名(sr1)+重定向的路径名(image)
     7         resp.sendRedirect("/sr1/image");
     8         等价于下面语句
     9         resp.setHeader("Location","/sr1/image");
    10         resp.setStatus(302);
    11         */
    12 
    13 
    14         resp.sendRedirect("/sr1/image");
    15     }
    16 
    17     @Override
    18     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    19         doGet(req, resp);
    20     }
    21 }

    重定向案例:登陆后重定向

    1. 在index.jsp中登陆
    2. 在RequestTestServlet中处理,然后重定向
    3. 重定向到Success.jsp中

    RequestTestServlet:

     1 public class RequestTestServlet extends HttpServlet {
     2 
     3     @Override
     4     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     5 
     6         String username = req.getParameter("username");
     7         String password = req.getParameter("password");
     8 
     9         System.out.println(username + ":" + password);
    10 
    11         resp.sendRedirect("/sr1/success.jsp");
    12     }
    13 
    14     @Override
    15     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    16         doGet(req, resp);
    17     }
    18 }

    index.jsp:

     1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
     2 <html>
     3 <body>
     4 <h2>Hello World!</h2>
     5 
     6 <%--${pageContext.request.contextPath}代表当前的项目名,login为web.xml中注册绑定的处理Servlet--%>
     7 <form action="${pageContext.request.contextPath}/login" method="get">
     8     用户名:<input type="text" name="username"> <br>
     9     密码:<input type="password" name="password"> <br>
    10     <input type="submit">
    11 </form>
    12 
    13 
    14 </body>
    15 </html>

    success.jsp:

     1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
     2 <html>
     3 <head>
     4     <title>Title</title>
     5 </head>
     6 <body>
     7 
     8 <h1>Success</h1>
     9 
    10 </body>
    11 </html>

    二.HttpServletRequest

    HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest,通过HttpServletRequest的方法,获得客户端的所有信息

    1.HttpServletRequest中的一些方法:

    2.主要应用

    1. 获取前端传递的参数(主要是两个方法)

      1.  public String getParameter(String name); 

      2.  public String[] getParameterValues(String name); 

    2. 请求转发

    请求转发案例:前端提交登录表单,Servlet处理并转发

    LoginServlet:

     1 public class LoginServlet extends HttpServlet {
     2 
     3     @Override
     4     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     5 
     6         req.setCharacterEncoding("utf-8");
     7         resp.setCharacterEncoding("utf-8");
     8 
     9         String username = req.getParameter("username");
    10 
    11         String password = req.getParameter("password");
    12 
    13         String[] hobbys = req.getParameterValues("hobbys");
    14 
    15         System.out.println(username);
    16         System.out.println(password);
    17         System.out.println(Arrays.toString(hobbys));
    18 
    19 
    20         //通过请求转发
    21         req.getRequestDispatcher("/success.jsp").forward(req, resp);
    22 
    23     }
    24 
    25     @Override
    26     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    27         doGet(req, resp);
    28     }
    29 }

    登录页面:index.jsp

     1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
     2 <html>
     3 <head>
     4     <title>登录</title>
     5 </head>
     6 <body>
     7 
     8 
     9 <h1>登录</h1>
    10 <div>
    11     <form action="${pageContext.request.contextPath}/login" method="post">
    12         用户名:<input type="text" name="username"> <br>
    13         密码:<input type="password" name="password"> <br>
    14         爱好:
    15         <input type="checkbox" name="hobbys" value="打篮球"> 打篮球
    16         <input type="checkbox" name="hobbys" value="写代码"> 写代码
    17         <input type="checkbox" name="hobbys" value="玩游戏"> 玩游戏
    18         <input type="checkbox" name="hobbys" value="看电影"> 看电影
    19         <br>
    20 
    21         <input type="submit">
    22     </form>
    23 </div>
    24 
    25 </body>
    26 </html>

    成功登录页面:success.jsp

     1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
     2 <html>
     3 <head>
     4     <title>Success</title>
     5 </head>
     6 <body>
     7 
     8 <h1>登录成功</h1>
     9 </body>
    10 </html>
  • 相关阅读:
    查看服务器被动手脚
    cordova安卓sdk
    Nginx 启动报错 “/var/run/nginx/nginx.pid" failed”
    家庭里如何搭建一个互联网可访问的服务器
    Mysql5.7基于事务转为基于日志
    021 基本数据类型小结
    018 字符串类型及操作
    022 程序的控制结构
    020 实例4-文本进度条
    017 示例3-天天向上的力量
  • 原文地址:https://www.cnblogs.com/zhihaospace/p/11950933.html
Copyright © 2011-2022 走看看