获取POST请求中的参数

获取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 <br>" ,
                aa,bb));
    }
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
</head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<body>
    <!--使用ajax/form表单的方法来构造POST请求-->
    <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>Title</title>
</head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<body>
    <!--构造body为json格式的数据,就只能用ajax格式,不能用form表单的格式-->
    <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>

在这里插入图片描述

4.引入JSON库,解析json

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
</head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<body>
<!--构造body为json格式的数据,就只能用ajax格式,不能用form表单的格式-->
<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<br>",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");
    }
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值