准备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
最新资源
- 赞多《序章》[FLAC/分轨][129.13MB]
- 群星《完美的她 影视原声带》[320K/MP3][51.98M
- 群星《完美的她 影视原声带》[FLAC/分轨][141.0
- 山风点伙.1997-深藏不露【立得】【WAV+CUE】
- 李幸倪.2018-First.Of.All.Live.Concert.3CD(20
- 李恕权.2003-回·20年全精选2CD【SONY】【WAV+CU
- 群星《你就在我身边 电影原声专辑》[320K/MP3][
- 群星《你就在我身边 电影原声专辑》[FLAC/分轨]
- 班得瑞原装进口《20周年精选集》1CD[APE/CUE分轨
- 群星.2009-NOON.D.广东.2CD【新世纪】【WAV+CUE