获取POST请求中的参数

发布时间:2024-02-08 13:30

获取POST请求中的参数方法

1.application/x-www-form-urlencoded:类似query-String的格式

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

//POST请求的body的格式又有好几种:
//1.application/x-www-form-urlencoded:类似query-String的格式 a=10&b=20
//2.mutlipart/form-data:这种格式比较复杂,用于提交文件,生成一个分隔符
//3.application/json
//{
//  a:10;
//  b:20;
//}

//这是第一种方法
@WebServlet("/postParameter")
public class PostParameter extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
        res.setContentType("text/html;charset=utf-8");
        String aa=req.getParameter("aa");
        String bb=req.getParameter("bb");
        res.getWriter().write(String.format("aa: %s&bb: %s 
"
, aa,bb)); } }
DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Titletitle>
head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<body>
    
    <form action="postParameter" method="POST">
    <input type="text" name="aa">
    <input type="text" name="bb">
    <input type="submit" value="提交">
    form>
body>
html>

在这里插入图片描述

2.mutlipart/form-data

3.application/json

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.InputStream;


//利用 application/json方法获取Post请求的body格式
@WebServlet("/postParameterJson")
public class PostParameterJsonServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //先把body读取出来
        String body=readBody(req);
        //这里只是读取出来了,并没有解析
        resp.getWriter().write(body);
        //构造请求,需要写一个html来构造请求
    }
    private String readBody(HttpServletRequest req) throws IOException {
        //读取流对象,需要根据req getInputStream 得到一个流对象,从这个流对象中去获取
        InputStream inputStream=req.getInputStream();
        //利用 contentLength 拿到请求中的body的字节数
        int length=req.getContentLength();
        byte[] bytes=new byte[length];
        inputStream.read(bytes);
        return new String(bytes,"utf-8");
    }
}
DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Titletitle>
head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<body>
    
    <button onclick="sendJson()">发送请求button>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js">script>
    <script>
        function sendJson(){
            let body={
                aa:10,
                bb:20
            };
            $.ajax({
                url:"postParameterJson",
                type:"post",
                contentType:"application/json;charset=uft-8",
                data:JSON.stringify(body),
                success:function(body,status){
                    console.log(body);
                }
            })
        }
        script>

body>
html>

获取POST请求中的参数_第1张图片

4.引入JSON库,解析json

DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Titletitle>
head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<body>

<button onclick="sendJson()">发送请求button>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js">script>
<script>
    function sendJson(){
        let body={
            aa:10,
            bb:20
        };
        $.ajax({
            url:"Json2",
            type:"post",
            contentType:"application/json;charset=uft-8",
            data:JSON.stringify(body),
            success:function(body,status){
                console.log(body);
            }
        })
    }
script>
body>
html>
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

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.InputStream;

//通过这个类来表示解析后的结果
class JsonData{
    public int aa;
    public int bb;
}
@WebServlet("/Json2")
public class JSON2 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1.先把body读出来
        String body=readBody(req);
        //2.使用jackson,解析请求
        //首先创建一个jackson核心对象,ObjectMapper
        ObjectMapper objectMapper=new ObjectMapper();
        JsonData jsonData= null;
        try {
            jsonData = objectMapper.readValue(body,JsonData.class);
        } catch (JsonMappingException e) {
            e.printStackTrace();
        }
        resp.getWriter().write(String.format("aa:%d;bb:%d
"
,jsonData.aa,jsonData.bb)); } public static String readBody(HttpServletRequest req) throws IOException { //读取body需要根据 req getInputStream得到一个流对象,从这个流对象中读取 InputStream inputStream=req.getInputStream(); //通过contentLength拿到请求中body的长度 int length=req.getContentLength(); byte[] butter=new byte[length]; inputStream.read(butter); return new String(butter,"utf-8"); } }

获取POST请求中的参数_第2张图片

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号