HttpServletResponse(响应)& HttpServletRequest(请求)

HttpServletResponse(响应)

web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象和一个代表响应的HttpServletResponse对象:

  • 如果要获取客户端请求过来的参数:需要HttpServletRequest(Requset中大多都是get类型的方法)
  • 如果要给客户端响应一些信息:需要HttpServletResponse(Response中大多都是set类型的方法)

简单分类

HttpServletResponse 继承了 ServletResponse ,servletResponse中有以下种类的方法
  1. 负责向浏览器发送数据的方法

    • PrintWriter getWriter() throws IOException;
      
    • ServletOutputStream getOutputStream() throws IOException;
      
  2. 负责向浏览器发送一些响应头的方法

    • //在servletResponse中的方法:
      void setCharacterEncoding(String var1);
      
      void setContentLength(int var1);
      
      void setContentLengthLong(long var1);
      
      void setContentType(String var1);
      
    • //HttpServletResponse中的方法
      void setDateHeader(String var1, long var2);
      
      void addDateHeader(String var1, long var2);
      
      void setHeader(String var1, String var2);
      
      void addHeader(String var1, String var2);
      
      void setIntHeader(String var1, int var2);
      
      void addIntHeader(String var1, int var2);
      
  3. HttpServletResponse中还定义了一些常量作为状态码:

  4. int SC_CONTINUE = 100;
    int SC_SWITCHING_PROTOCOLS = 101;
    int SC_OK = 200;
    int SC_CREATED = 201;
    int SC_ACCEPTED = 202;
    int SC_NON_AUTHORITATIVE_INFORMATION = 203;
    int SC_NO_CONTENT = 204;
    int SC_RESET_CONTENT = 205;
    int SC_PARTIAL_CONTENT = 206;
    int SC_MULTIPLE_CHOICES = 300;
    int SC_MOVED_PERMANENTLY = 301;
    int SC_MOVED_TEMPORARILY = 302;
    int SC_FOUND = 302;
    int SC_SEE_OTHER = 303;
    int SC_NOT_MODIFIED = 304;
    int SC_USE_PROXY = 305;
    int SC_TEMPORARY_REDIRECT = 307;
    int SC_BAD_REQUEST = 400;
    int SC_UNAUTHORIZED = 401;
    int SC_PAYMENT_REQUIRED = 402;
    int SC_FORBIDDEN = 403;
    int SC_NOT_FOUND = 404;
    int SC_METHOD_NOT_ALLOWED = 405;
    int SC_NOT_ACCEPTABLE = 406;
    int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
    int SC_REQUEST_TIMEOUT = 408;
    int SC_CONFLICT = 409;
    int SC_GONE = 410;
    int SC_LENGTH_REQUIRED = 411;
    int SC_PRECONDITION_FAILED = 412;
    int SC_REQUEST_ENTITY_TOO_LARGE = 413;
    int SC_REQUEST_URI_TOO_LONG = 414;
    int SC_UNSUPPORTED_MEDIA_TYPE = 415;
    int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    int SC_EXPECTATION_FAILED = 417;
    int SC_INTERNAL_SERVER_ERROR = 500;
    int SC_NOT_IMPLEMENTED = 501;
    int SC_BAD_GATEWAY = 502;
    int SC_SERVICE_UNAVAILABLE = 503;
    int SC_GATEWAY_TIMEOUT = 504;
    int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
    

常见应用

向浏览器输出消息

下载文件

  1. 要获取下载文件的路径
  2. 下载的文件名
  3. 设置想办法让浏览器能够支持下载我们需要的东西
  4. 获取下载文件的输入流
  5. 创建缓冲区
  6. 获取OutputStream对象
  7. 将FileOutputSteam流写入到buffer缓冲区
  8. 使用OutputStream将缓冲区中的数据输出到客户端
public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 要获取下载文件的路径
        String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/666.png");
        System.out.println("下载文件的路径:" + realPath);
        //2. 下载的文件名
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        //3. 设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西
        resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        //4. 获取下载文件的输入流
        FileInputStream inputStream = new FileInputStream(realPath);
        //5. 创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        //6. 获取OutputStream对象
        ServletOutputStream out = resp.getOutputStream();
        //7. 将FileOutputSteam流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端
        while ((len = inputStream.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        inputStream.close();
        out.close();

    }

验证码功能

验证码怎么来的

  • 前端实现

  • 后端实现:需要用到Java的图片类,生成一个图片

    public class ImageServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //如何让浏览器五秒刷新一次
            resp.setHeader("refresh","5");
            //在内春中创建一个图片
            BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
            //得到图片
            Graphics2D g = (Graphics2D) image.getGraphics();//笔
            //设置图片背景颜色
            g.setColor(Color.WHITE);
            g.fillRect(0,0,80,20);
            //给图片写数据
            g.setColor(Color.BLUE);
            g.setFont(new Font(null,Font.BOLD,20));
            g.drawString(makeNum(),20,20);
            //告诉浏览器,这个请求用图片的方式打开
            resp.setContentType("image/jpeg");
            //网站存在缓存,不让浏览器缓存
            resp.setDateHeader("expires",-1);
            resp.setHeader("Cache-Control","no-cache");
            resp.setHeader("Pragma","no-cache");
            //把图片写给浏览器
            ImageIO.write(image,"jpg",resp.getOutputStream());
        }
        private String makeNum(){
            Random random = new Random();
            String num = random.nextInt(9999) + "";
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < 4-num.length(); i++) {
                sb.append("0");
            }
            num=sb.toString()+num;
            return num;
    
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    

实现重定向

重定向是指:一个web(A)资源收到客户端(B)的请求后,通知该客户端(B)去访问另一个web资源(C),这个过程就叫做重定向。

使用的方法为:

 void sendRedirect(String var1) throws IOException;

问题:重定向和请求转发的相同和不同:

  • 相同:页面都会发生跳转

  • 不同:

    1. 请求转发的时候,url不会发生变化
    2. 重定向的时候,url会发生变化
  • 重定向:

  • protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*
        * 重定向原理拆分
        *resp.setHeader("Lcation","resp01/img");
        resp.setStatus(302);
        * */
        resp.sendRedirect("/resp01/img");
    }
    
  • 转发:

  • protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html");
        ServletContext context = this.getServletContext();
        RequestDispatcher dispatcher = context.getRequestDispatcher("/yyds");//转发的请求路径
        dispatcher.forward(req,resp);//调用forward实现请求转发
        System.out.println("servlet启动完毕");
    }
    

常见场景:

  • 用户登录

    自定义一个用户登录的测试:

    先定义一个用于客户端提交账号密码后进行重定向的servlet,以及重定向的jsp页面:

    1. public class RequestTest extends HttpServlet {
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      
              System.out.println("进入这个请求了");
              String username = req.getParameter("username");
              String password = req.getParameter("password");
              System.out.println(username+"/"+password);
              resp.sendRedirect("/resp01/success.jsp");
          }
      
          @Override
          protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              doGet(req, resp);
          }
      }
      
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
          <title>Title</title>
      </head>
      <body>
      <h1>Success</h1>
      
      </body>
      </html>
      
    2. 在web.xml中注册这个servlet:

    3. <servlet>
          <servlet-name>request</servlet-name>
          <servlet-class>com.yue.servlet.RequestTest</servlet-class>
      </servlet>
      <servlet-mapping>
          <servlet-name>request</servlet-name>
          <url-pattern>/login</url-pattern>
      </servlet-mapping>
      
    4. 修改index.jsp页面,设置一个form表单来存储用户名和密码,表单提交后跳转到/login:

    <html>
    <body>
    <h2>Hello World!</h2>
    
    <%--这里提交的路径,需要寻找到项目的路径--%>
    <form action="${pageContext.request.contextPath}/login" method="get">
        用户名:<input type="text" name="username"> <br>
        密码:<input type="password" name="password"> <br>
        <input type="submit">
    </form>
    </body>
    </html>
    
    1. 再从/login重定向到定义好的success.jsp页面

HttpServletRequest(请求)

HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,Http请求中的所有信息会被封装到HttpServletRequest中,通过这个HttpServletRequest中的方法,获得客户点的所有信息。(所以多为get方法)

1. 请求转发

2. 获取前端传递的参数

req.getParameter();//获取单个参数
req.getParameterValues()//获取多个参数

例子:

设计一个简易的模拟登陆页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登陆</title>
</head>
<body>
<h1>登陆</h1>
<div style="text-align: center">
    <%--以post方式提交表单,提交到login请求--%>
    <form action="${pageContext.request.contextPath}/login" method="post">
        用户名:<input type="text" name="username" required><br>
        密码 :<input type="password" name="password" required><br>
        爱好:
        <input type="checkbox" name="hobbies" value="女">女
        <input type="checkbox" name="hobbies" value="游戏">游戏
        <input type="checkbox" name="hobbies" value="手冲">手冲
        <input type="checkbox" name="hobbies" value="代码">代码
        <br>
        <input type="submit">
    </form>
</div>
</body>
</html>

自定义一个LoginServlet接收登录页面的前端传递过来的各种参数:

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] hobbies = req.getParameterValues("hobbies");
        System.out.println("===========================");
        System.out.println(username);
        System.out.println(password);
        System.out.println(Arrays.toString(hobbies));
        System.out.println("===========================");
        //通过请求转发,转发到success.jsp页面,
        // 这里的/代表当前项目
        req.getRequestDispatcher("/success.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

在web.xml中注册LoginServlet:

<servlet>
    <servlet-name>loginServlet</servlet-name>
    <servlet-class>com.yue.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>loginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>

自定义一个success.jsp页面作为登陆成功页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>
    登陆成功
</h1>
</body>
</html>

重定向和请求转发的区别和相同处

相同点:

  • 页面都会实现跳转

不同点:

  • 重定向时,url地址栏会发生变化,状态码是302
  • 请求转发时,url地址栏不会发生变化,状态码是307
posted @   阿飞bean  阅读(114)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示