servlet部分
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*ServletInputStream inputStream = req.getInputStream();
System.out.println(inputStream);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));*/
/*用到io流的方式来获取body中的内容*/
BufferedReader reader = req.getReader();
/*读取内容*/
StringBuffer buffer = new StringBuffer();
String string;
while ((string = reader.readLine())!=null) {
buffer.append(string);
}
System.out.println("post请求body中的内容:"+buffer);
/*内容转换*/
JSONObject parseObject = JSONObject.parseObject(buffer.toString());
User user = JSONObject.toJavaObject(parseObject, User.class);
String jsonString = JSONObject.toJSONString(user);
/*返回json*/
resp.setContentType("application/json;charset=utf-8");//不加的话,前端识别不出来
resp.getWriter().println(jsonString);
}
ajax部分
<script type="text/javascript">
function requestByJson(){
alert('可以')
/* JSON.stringify将 JavaScript 对象转换为 JSON 字符串 */
var params = JSON.stringify({"username":"wei", "password":"toor"})
$.ajax({
type:'post',
url:'${pageContext.request.contextPath }/login',
contentType:'application/json;charset=utf-8',
data:params,
dataType:'json',//后台返回数据
success:function(data){
alert(data.username)
alert(data.password)
},
error:function(textStatus,errorThrown){
alert(textStatus)
}
})
}
</script>