使用JSON格式提交数据到服务端的实例代码
(编辑:jimmy 日期: 2025/12/20 浏览:3 次 )
准备Hero.java
public class Hero {
private String name;
private int hp;
public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
@Override
public String toString() {
return "Hero [name=" + name + ", hp=" + hp + "]";
}
}
public class Hero {
private String name;
private int hp;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
@Override
public String toString() {
return "Hero [name=" + name + ", hp=" + hp + "]";
}
}submit.html文件
[html] view plain copy print"Content-Type" content="text/html; charset=utf-8">
<title>用AJAX以JSON方式提交数据</title>
<script type="text/javascript" src="/UploadFiles/2021-04-02/jquery.min.js">
JSON.stringify函数的作用是将一个javascript对象,转换为JSON格式的字符串。
准备SubmitServlet用来接收数据
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
public class SubmitServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data =request.getParameter("data");
System.out.println("服务端接收到的数据是:" +data);
JSONObject json=JSONObject.fromObject(data);
System.out.println("转换为JSON对象之后是:"+ json);
Hero hero = (Hero)JSONObject.toBean(json,Hero.class);
System.out.println("转换为Hero对象之后是:"+hero);
}
}
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
public class SubmitServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data =request.getParameter("data");
System.out.println("服务端接收到的数据是:" +data);
JSONObject json=JSONObject.fromObject(data);
System.out.println("转换为JSON对象之后是:"+ json);
Hero hero = (Hero)JSONObject.toBean(json,Hero.class);
System.out.println("转换为Hero对象之后是:"+hero);
}
}
1. 获取浏览器提交的字符串
2. 把字符串转换为JSON对象
3. 把JSON对象转换为Hero对象
最后配置web.xml
下一篇:Vue.js进阶知识点总结
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。

