HttpServletResponse

HttpServletResponse

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

    • 如果要获取客户端请求过来的参数:找HttpServletRequest
    • 如果要给客户端响应一些信息:找HttpServletResponse
  • 负责向浏览器发送数据的方法↓

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

        public void setCharacterEncoding(String charset);
        public void setContentLength(int len);
        public void setContentLengthLong(long len);
        public void setContentType(String type);
        public void setDateHeader(String name, long date);
        public void addDateHeader(String name, long date);
        public void setHeader(String name, String value);
        public void addHeader(String name, String value);
        public void setIntHeader(String name, int value);
        public void addIntHeader(String name, int value);
    
  • 响应的状态码↓

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

    常见应用

    向浏览器输出消息
    下载文件

    ①获取下载文件的路径

    ②命名下载文件名

    ③设置浏览器能够支持下载

    ④获取下载文件的输入流

    ⑤创建缓冲区

    ⑥获取OutputStream对象

    ⑦将FileOutputStream流写入Buffer缓冲区

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

@WebServlet("/file")
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/a.jpg");// ‘/‘表示web根目录
        System.out.println("下载的文件路径:" + realPath);
        //2.获取要下载的文件名
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        //3.设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西,中文文件名URLEncoder.encode编码,否则有可能乱码
        resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
        //4.获取下载文件的输入流
        FileInputStream in = new FileInputStream(new File(realPath));
        //5.创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        //6.获取OutputStream对象
        ServletOutputStream out = resp.getOutputStream();
        //7. 将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端!
        while ((len=in.read(buffer)) != -1) {
            out.write(buffer,0,len);
        }
        in.close();
        out.close();
    }
}

验证码功能

  • 前端实现
  • 后端实现,需要用到Java的图片类,生产一个图片
@WebServlet("/yzm")
public class yzmServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //如何让浏览器3秒自动刷新一次;
        // resp.setHeader("refresh","3");
        //在内存中创建一个图片
        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(),0,20);
        //告诉浏览器,这个请求用图片的方式打开
        resp.setContentType("image/jpg");
        //网站存在缓存,不让浏览器缓存
        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(9999999) + "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 7-num.length() ; i++) {
            sb.append("0");
        }
        num = sb.toString() + num;
        return num;
    }
}

实现重定向

HttpServletResponse

B一个web资源收到客户端A请求后,B会通知A去访问另外一个web资源C,这个过程叫重定向。

@WebServlet("/redir")
public class RedirectServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         /*
        resp.setHeader("Location","/r/img");
        resp.setStatus(302);  /重定向
        responseDemo_war:项目名
         */
        resp.sendRedirect("/responseDemo_war/yzm");
    }
}

常见场景:

  • 用户登录

重定向和转发的区别?

  • 请求转发url不会产生变化,重定向会发生变化
  • 请求转发可以携带参数,重定向不能携带参数
  • 请求转发只能发送一个请求,重定向至少发送两次请求

简单实现登录重定向

  • @WebServlet("/login")
    public class LoginServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //处理请求
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            System.out.println(username+":"+password);
            //重定向时候一定要注意,路径问题,否则404;
            resp.sendRedirect("/responseDemo_war/success.jsp");
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req,resp);
        }
    }
    
  • index.jsp

  • <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <body>
    <h2>Hello World!</h2>
    <%--这里提交的路径,需要寻找到项目的路径--%>
    <%--${pageContext.request.contextPath}代表当前的项目--%>
    <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>
    
  • success.jsp

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

HttpServletResponse

上一篇:.NET平台系列8 .NET Core 各版本新功能


下一篇:postcss-pxtorem插件相关配置