Loading

response应用及问题

下载文件

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //1. 获取下载文件的路径
        String realPath = "D:\\IdeaProjects\\javaweb-project-maven\\servlet-response\\src\\main\\resources\\哈哈.jpg";
        //2. 下载的文件名是啥?
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        //3. 设置想办法让浏览器能都支持我们下载的东西 文件名是中文的时候,可以设置URLEncoder.encode(fileName, "UTF-8"),否则有可能乱码
        resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        //4. 获取下载文件的输入流
        FileInputStream in = new FileInputStream(realPath);

        //5. 创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        //6. 获取OutputStrem对象
        ServletOutputStream out = resp.getOutputStream();
        //7. 将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        out.flush();
        out.close();
        in.close();
    }

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

生成验证码图片

public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //如何让浏览器三秒自动刷新一次
        resp.setHeader("refresh", "3");
        //在内存中创建一个图片
        BufferedImage bufferedImage = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
        //得到图片
        Graphics2D bi = (Graphics2D) bufferedImage.getGraphics();
        //设置背景颜色为白色
        bi.setColor(Color.WHITE);
        bi.fillRect(0, 0, 80, 20);
        //给图片写数据
        bi.setColor(Color.BLUE);
        bi.setFont(new Font(null, Font.BOLD, 20));
        bi.drawString(makeNum(), 0, 20);
        //告诉浏览器用图片的方式打开
        resp.setContentType("image/jpeg");
        //网站存在缓存,不让浏览器缓存
        resp.setDateHeader("Expires",0);
        resp.addHeader("Cache-Control","no-cache");
        resp.setHeader("Pragma","no-cache");

        ImageIO.write(bufferedImage, "jpeg", resp.getOutputStream());

    }

    private String makeNum() {
        Random random = new Random();
        String num = random.nextInt(999999) + "";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6 - num.length(); i++) {
            sb.append("0");
        }
        return sb.toString() + num;

    }

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

重定向问题

public class RedirectServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //重定向
        resp.sendRedirect("/res/image");

        //相当于
//        resp.setHeader("Location", "/res/image");
//        resp.setStatus(302);
    }

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

面试题:重定向和转发的区别

  • 相同点
    • 页面都会实现跳转
  • 相同点
    • 请求转发,URL地址拦不会变; 307
    • 重定向,URL地址拦会发生变化。 302

模拟登录

java代码
public class RequestTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");
        System.out.println(username + ":" + pwd);

        //重定向的时候,一定要注意路径问题,否则可能会404
        resp.sendRedirect("/res/success.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
jsp代码
<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="pwd"/><br/>
    <input type="submit"/>
</form>
</body>
</html>
posted @ 2022-03-04 00:57  Cn_FallTime  阅读(25)  评论(0编辑  收藏  举报