POST 请求的参数⼀般通过 body 传递给服务器, body 中的数据格式有很多种, 如果是采⽤ form 表单的形式, 可以通过getParameter() 获取参数的值,但是,使⽤getParameter() 的⽅式是获取不了 JSON 格式的数据的。获取方式如下:
后端代码:
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
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.HashMap;
@WebServlet("/postjson")
public class JsonPostServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 设置返回类型和编码
resp.setContentType("text/html; charset=utf-8");
// 1.得到数据流
ServletInputStream inputStream = req.getInputStream();
// 2.使用数组接收流信息
int length = req.getContentLength();
byte[] bytes = new byte[length];
inputStream.read(bytes);
// 3.将数组转换成字符串(或对象)
String result = new String(bytes, "utf-8");
System.out.println(result);
// 4.字符串转换成对象(或字典)
ObjectMapper objectMapper = new ObjectMapper();
HashMap<String, String> map = objectMapper.readValue(result, HashMap.class);
System.out.println("用户名:" + map.get("username"));
System.out.println("密码:" + map.get("password"));
resp.getWriter().println("用户名:" + map.get("username") +
" | 密码:" + map.get("password"));
}
}
前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户登录系统</title>
<script src="js/jquery-1.9.1.min.js"></script>
</head>
<body>
<div style="margin-top:50px;margin-left:40%;">
<h1 style="padding-left:50px;">用户登录</h1>
姓名:<input id="username" type="text" >
<p>
密码:<input id="password" type="password" >
<p>
<div style="padding-left:50px;">
<input type="button" value=" 提 交 " onclick="mySubmit()">
<input type="reset" value=" 重 置 ">
</div>
</div>
<script>
// ajax 请求登录
function mySubmit(){
// 非空效验
var username = jQuery("#username");
var password = jQuery("#password");
if(""==jQuery.trim(username.val())){
alert("请先输入用户名!");
username.focus();
return;
}
if(""==jQuery.trim(password.val())){
alert("请先输入密码!");
password.focus();
return;
}
jQuery.ajax({
url:"postjson", // 设置请求地址
type:"POST", // 设置请求方法类型
contentType:"application/json; charset=utf-8", // 请求类型
// dataType:"", // 响应的类型
// 将对象转换成 JSON 字符串
data:JSON.stringify({"username":username.val(),"password":password.val()}), // 请求参数
success:function(data){
alert(data);
}
});
}
</script>
</body>
</html>
使用Fiddler抓包结果:
运行结果: