IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> Request和Response -> 正文阅读

[Java知识库]Request和Response

Request(请求)和Response(响应)

在这里插入图片描述
(记得把之前的xml配置的删掉)

package com.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/demo6")
public class servletDemo6 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        //使用request对象 获取请求数据
        String name=req.getParameter("name");//url?name=zhangsan

        //使用response对象 设置响应数据
        res.setHeader("content-type","text/html;charset=utf-8");
        res.getWriter().write("<h1>"+name+",你好!<h1>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("get....");
    }
}

网址改为

http://localhost:8080/javaweb/demo6?name=zhangsan

Request

一、继承体系

在这里插入图片描述

二、Request请求数据

在这里插入图片描述

1、请求行

package com.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/req1")
public class RequestDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //String getmethod():获取请求方式:GET
        String method = req.getMethod();
        System.out.println(method);

        //String getContextPath():获取虚拟目录(项目访问路径):/javaweb
        String contextPath = req.getContextPath();
        System.out.println(contextPath);

        //StringBuffer getRequestURL():获取URL(统一资源定位符):http://localhost:8080/javaweb3/req1
        StringBuffer url = req.getRequestURL();
        System.out.println(url.toString());

        //String getRequestURI():获取URI(统一资源标识符):/javaweb/req1
        String uri = req.getRequestURI();
        System.out.println(uri);

        //String getQueryString():获取请求参数(GET方式):username=zhangsan
        String queryString = req.getQueryString();
        System.out.println(queryString);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("get...");
    }
}

网址输入

http://localhost:8080/javaweb/req1?username=zhangsan

在这里插入图片描述

2、请求头

package com.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/req1")
public class RequestDemo1 extends HttpServlet {
    //请求行
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //String getmethod():获取请求方式:GET
        String method = req.getMethod();
        System.out.println(method);

        //String getContextPath():获取虚拟目录(项目访问路径):/javaweb
        String contextPath = req.getContextPath();
        System.out.println(contextPath);

        //StringBuffer getRequestURL():获取URL(统一资源定位符):http://localhost:8080/javaweb3/req1
        StringBuffer url = req.getRequestURL();
        System.out.println(url.toString());

        //String getRequestURI():获取URI(统一资源标识符):/javaweb/req1
        String uri = req.getRequestURI();
        System.out.println(uri);

        //String getQueryString():获取请求参数(GET方式):username=zhangsan
        String queryString = req.getQueryString();
        System.out.println(queryString);


        //-------------------
        //获取请求头:user-agent:浏览器的版本信息
        System.out.println("-------------------");
        String header = req.getHeader("user-agent");
        System.out.println(header);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("get...");
    }
}

在这里插入图片描述

3、请求头

现在webapp包下创建文件req.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="/javaweb/req1" method="post">
    <input type="text" name="username"><br>
    <input type="password" name="password"><br>
    <input type="submit">
</form>
</body>
</html>
package com.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/req1")
public class RequestDemo1 extends HttpServlet {
    //请求行
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //String getmethod():获取请求方式:GET
        String method = req.getMethod();
        System.out.println(method);

        //String getContextPath():获取虚拟目录(项目访问路径):/javaweb
        String contextPath = req.getContextPath();
        System.out.println(contextPath);

        //StringBuffer getRequestURL():获取URL(统一资源定位符):http://localhost:8080/javaweb3/req1
        StringBuffer url = req.getRequestURL();
        System.out.println(url.toString());

        //String getRequestURI():获取URI(统一资源标识符):/javaweb/req1
        String uri = req.getRequestURI();
        System.out.println(uri);

        //String getQueryString():获取请求参数(GET方式):username=zhangsan
        String queryString = req.getQueryString();
        System.out.println(queryString);


        //-------------------
        //获取请求头:user-agent:浏览器的版本信息
        System.out.println("-------------------");
        String header = req.getHeader("user-agent");
        System.out.println(header);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //获取post请求体:请求参数
        //1.获取字符输入流
        System.out.println("-----------------------");
        BufferedReader br = req.getReader();
        //2.读取数据
        String Line = br.readLine();
        System.out.println(Line);
    }
}

在这里插入图片描述

Request通用方式请求参数

在这里插入图片描述

在这里插入图片描述

package com.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/req2")
public class RequestDemo2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //GET请求逻辑
        System.out.println("get....");

        //1.获取所有参数map的集合
        Map<String, String[]> map = req.getParameterMap();
        for(String key:map.keySet()){
            //username:zhangsan
            System.out.print(key+":");

            String[] values=map.get(key);
            for (String value:values){
                System.out.print(value+" ");
            }
            System.out.println();
        }
        System.out.println("----------------");
        //2.根据key获取参数值,数组
        String[] hobbies = req.getParameterValues("hobby");
        for (String hobby:hobbies){
            System.out.println(hobby);
        }
        //3.根据key 获取单个参数值
        String username = req.getParameter("username");
        String password = req.getParameter("username");

        System.out.println(username);
        System.out.println(password);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //POST请求方式
        System.out.println("POST....");

        //1.获取所有参数map的集合
        Map<String, String[]> map = req.getParameterMap();
        for(String key:map.keySet()){
            //username:zhangsan
            System.out.print(key+":");

            String[] values=map.get(key);
            for (String value:values){
                System.out.print(value+" ");
            }
            System.out.println();
        }
        System.out.println("----------------");
        //2.根据key获取参数值,数组
        String[] hobbies = req.getParameterValues("hobby");
        for (String hobby:hobbies){
            System.out.println(hobby);
        }
        //3.根据key 获取单个参数值
        String username = req.getParameter("username");
        String password = req.getParameter("username");

        System.out.println(username);
        System.out.println(password);
    }
}

请求参数中文乱码–POST解决方案

package com.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/req3")
public class RequestDemo3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.解决乱码:POST,getReader()
        req.setCharacterEncoding("UTF-8");//设置字符输入流的编码

        //2.获取username
        String username = req.getParameter("username");
        System.out.println(username);
    }

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

Request请求转发

在这里插入图片描述

package com.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/req4")
public class RequestDemo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("demo4...");

        //提供数据
        req.setAttribute("msg","Hello");

        //请求转发
        req.getRequestDispatcher("/req5").forward(req,resp);
    }

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

package com.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
请求转发
 */
@WebServlet("/req5")
public class RequestDemo5 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("demo5..");

        //获取数据
        Object msg = req.getAttribute("msg");
        System.out.println(msg);

    }

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

Response设置响应数据&重定向

PS:面试题:转发和重定向什么区别?
在这里插入图片描述
重定向
在这里插入图片描述

package com.web.Response;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/res1")
public class ResponseDemo1 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("res1....");

        //重定向
        //1.设置响应状态码:302
        //resp.setStatus(302);
        //2.设置响应头:location
        //resp.setHeader("Location","/javaweb/res2");

        resp.sendRedirect("/javaweb/res2");
    }

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

    }
}

package com.web.Response;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/res2")
public class ResponseDemo2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("res2....");
    }

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

PS:可以重定向任意资源,比如我把resp.sendRedirect("/javaweb/res2")括号内的内容改为https://www.baidu.com
在这里插入图片描述

package com.web.Response;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/res1")
public class ResponseDemo1 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("res1....");

        //重定向
        //1.设置响应状态码:302
        //resp.setStatus(302);
        //2.设置响应头:location
        //resp.setHeader("Location","/javaweb/res2");

        //简化方式完成重定向
        //动态获取虚拟目录
        String contextPath = req.getContextPath();
        
        resp.sendRedirect(contextPath+"/res2");
    }

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

    }
}

Response响应字符数据

在这里插入图片描述

package com.web.Response;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//响应字符数据:设置字符数据的响应体
@WebServlet("/res3")
public class ResponseDemo3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //1.获取字符输出流
        PrintWriter writer = resp.getWriter();
        writer.write("你好");
        //如果不声明,则单纯打印<h1>aaa</h1>
        //context-type:告诉浏览器h1标签
        //resp.setHeader("content-type","text/html");
        writer.write("<h1>aaa</h1>");

        //细节:流不需要关闭
    }

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

Response响应字节数据

在这里插入图片描述

package com.web.Response;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

//响应字节数据:设置字节数据响应体
@WebServlet("/res4")
public class ResponseDemo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //1.读取文件
        FileInputStream fileInputStream = new FileInputStream("D://a.jpg");

        //2.获取response字节输出流
        ServletOutputStream outputStream = resp.getOutputStream();

        //3.完成流的copy
        byte[] buff=new byte[1024];
        int len=0;
        //太复杂,所以在pom.xml文件配置工具类
        /*while((len=fileInputStream.read(buff))!=-1){
            outputStream.write(buff,0,len);
        }
         */
        IOUtils.copy(fileInputStream,outputStream);

        fileInputStream.close();
    }

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

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-03-08 22:14:58  更:2022-03-08 22:15:20 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 11:56:49-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码