获取 POST 请求中的参数(1)
- POST 请求中的 body 是采用form 表单的形式
创建类PostParameter
@WebServlet("/postparameter")
public class PostParameter extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//防止返回的结果乱码
resp.setContentType("text/html;charSet=utf-8");
//得到请求参数的值
String post = req.getParameter("s");
//返回结果
resp.getWriter().println("post传参结果:" + post);
}
}
创建post_text.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用post——get得参数</title>
</head>
<body>
<form action="postparameter" method="post">
<div style="margin-top:50px;margin-left:40%;">
<h1 style="padding-left:50px;">post传参</h1>
参数:<input type="text" name="s">
<input type="submit" value=" 提 交 ">
</div>
</form>
</body>
</html>
结果:可以看到传入的数据
获取 POST 请求中的参数(2)
- POST 请求中的 body 是按照 JSON 的格式来传递
创建类PostparameterJson
@WebServlet("/PostparameterJson")
public class PostparameterJson extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置返回值类型和编码
resp.setContentType("text/html;charSet=utf-8");
//1.得到数据流
ServletInputStream inputStream=req.getInputStream();
//2.找一个容器用来存储流
byte [] bytes=new byte[req.getContentLength()];
inputStream.read(bytes);
//3.将数组转换成字符串
String s=new String(bytes,"utf-8");
// 4.字符串转换成对象
ObjectMapper objectMapper = new ObjectMapper();
HashMap<String, String> map = objectMapper.readValue(s, HashMap.class);
//6.返回结果
resp.getWriter().println("用户名:" + map.get("username") +
" | 密码:" + map.get("password"));
}
}
创建login_ajax_json.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax_json用户登陆系统</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:"PostparameterJson", // 设置请求地址
type:"Post", // 设置请求方法类型
contentType:"application/json; charset=utf-8", // 请求类型
// 将对象转换成 JSON 字符串
data:JSON.stringify({"username":username.val(),"password":password.val()}), // 请求参数
success:function(data){
alert(data);
}
});
}
</script>
</body>
</html>
结果: