7-Request和Response

web服务器收到客户端的http请求时,如果是servlet,会让servlet容器创建代表请求和响应的HttpServletRequest和HttpServletResponse
如果要获取请求时的参数,找HttpServletRequest
如果要给客户端响应消息,找HttpServletResponse

HttpServletResponse

HttpServletResponse继承了ServletResponse,定义了一些状态码,一些get和set响应头信息的方法以及向浏览器写东西的方法

常见应用是
1、向浏览器输出东西

ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;

2、下载文件

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1、获取下载文件的路径
        String path = "C:\\Users\\Bi\\Desktop\\java\\mymaven\\javaweb-01-servlet\\response\\src\\main\\resources\\原.png";
//        2、下载的文件名
        String name = path.substring(path.lastIndexOf("\\") + 1);
//        3、让浏览器支持我们下载东西
        resp.setHeader("content-Disposition","attachment;filename="+ URLEncoder.encode(name,"utf-8"));
//        4、获取要被下载的文件的输入流
        InputStream inputStream = new FileInputStream(path);
//        5、创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
//        6、获取OutStream对象
        ServletOutputStream outputStream = resp.getOutputStream();
//        7、读与写
        while((len=inputStream.read(buffer))>0){
            outputStream.write(buffer);
        }
        outputStream.close();
        inputStream.close();
    }

3、重定向
进行页面跳转,地址栏会变(与请求转发不同)

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("/r/draw");   //跳转时不会带上项目名,因此要把/r加上
    }
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        重定向拆分就是两步:
        resp.setHeader("location","/r/draw");
        resp.setStatus(302);
    }

重定向时,输入参数是访问时的项目名 加 要跳转的网页。这里 /r 就是我设置的虚拟的项目名,/draw是我要访问的网页的地址(我这里是servlet虚拟映射)

在这里插入图片描述
一个简单的登录页面,成功后进行跳转
index.jsp,启动后默认打开

<html>
<body>
<h2>Hello World!</h2>
<form action="${pageContext.request.contextPath}/login" method="get">
    用户名: <input type="text" name="username">
    密码: <input type="password" name="password">
    <input type="submit">
</form>
</body>
</html>

HttpServlet虚拟映射地址是/login,处理登陆页面信息的,并进行重定向,跳转到success.jsp页面。

    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:"+username);
        System.out.println("password:"+password);
        resp.sendRedirect("/r/success.jsp");
    }

4、一个简单的图形验证码

public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //每三秒刷新一下网页
        resp.setHeader("refresh","3");

        //内存中创建图片
        BufferedImage image = new BufferedImage(60,20,BufferedImage.TYPE_INT_RGB);
        //获得画笔
        Graphics2D graphics = (Graphics2D) image.getGraphics();
        //画矩形
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0,0,60,20);
        //画String
        graphics.setColor(Color.BLUE);
        graphics.setFont(new Font(null,Font.BOLD,20));
        graphics.drawString(randomnum(),0,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 randomnum(){
        Random random = new Random();
        String num = random.nextInt(99999)+"";
        StringBuffer stringBuffer = new StringBuffer();
        //不够五位的用0补
        for (int i = 0; i < 5-num.length(); i++) {
            stringBuffer.append("0");
        }
        num = stringBuffer.toString()+ num;
        return num;
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

HttpServletRequest

HttpServletRequest代表客户端的请求。用户通过Http协议访问服务器,HTTP请求中的所有信息都会被封装在HttpServletRequest里面。通过HttpServletRequest可以获得客户端的所有信息

最常用的功能是获取前端传来的参数、请求转发

前端页面

<html>
<head>
    <title>登录</title>
</head>
<body>
    <h1>登录</h1>
    <div>
        <form action="${pageContext.request.contextPath}/login" method="post">
            用户名:<input type="text" name="username"><br>
            密码:<input type="password" name="password"><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>

HttpServlet,实现获取前端参数,并请求转发

    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("username:" + username);
        System.out.println("password:" + password);
        System.out.println(Arrays.toString(hobbies));
        System.out.println("=======================");

        //请求转发是项目内部流转,不用再加项目名
        req.getRequestDispatcher("/success.jsp").forward(req,resp);
        //下面是通过context实现请求转发功能
//        this.getServletContext().getRequestDispatcher("/success.jsp");
    }

请求转发在实现时,不用加虚拟项目名,会将 / 自动转为项目名。跟重定向不同,重定向需要加项目名。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值