其他分享
首页 > 其他分享> > HttpServletResponse(响应)& HttpServletRequest(请求)

HttpServletResponse(响应)& HttpServletRequest(请求)

作者:互联网

HttpServletResponse(响应)

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

简单分类

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();

    }

验证码功能

验证码怎么来的

实现重定向

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

使用的方法为:

 void sendRedirect(String var1) throws IOException;

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

常见场景:

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>

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

相同点:

不同点:

标签:HttpServletRequest,String,int,resp,req,HttpServletResponse,响应,SC,void
来源: https://www.cnblogs.com/afro/p/16277394.html