Project directory:
Show. jsp:
<% @ Page contenttype = "text/html; charset = UTF-8 "pageencoding =" UTF-8 "%> <HTML>
Share. Java:
public class Share {private String shareName;private double sharePrice;private Date date;public Date getDate() {return date;}public void setDate(Date date) {this.date = date;}public String getShareName() {return shareName;}public void setShareName(String shareName) {this.shareName = shareName;}public double getSharePrice() {return sharePrice;}public void setSharePrice(double sharePrice) {this.sharePrice = sharePrice;}public Share() {super();}public Share(String shareName, double sharePrice, Date date) {super();this.shareName = shareName;this.sharePrice = sharePrice;this.date = date;}}
Dateprocessor. Java:
public class DateProcessor implements JsonValueProcessor {private String pattern="yyyy-MM-dd HH:mm:ss";public void setPattern(String pattern) {this.pattern = pattern;}@Overridepublic Object processArrayValue(Object arg0, JsonConfig arg1) {Date date=(Date)arg0;SimpleDateFormat sdf=new SimpleDateFormat(pattern);return sdf.format(date);}@Overridepublic Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {Date date=(Date)arg1;SimpleDateFormat sdf=new SimpleDateFormat(pattern);return sdf.format(date);}}
Showservlet. Java:
public class ShowServlet extends HttpServlet {public void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {Random random=new Random();String shareName="share"+random.nextInt(99999);double sharePrice=Math.ceil(random.nextDouble()*10);Share share=new Share(shareName,sharePrice,new Date());DateProcessor processor=new DateProcessor();JsonConfig config=new JsonConfig();config.registerJsonValueProcessor(Date.class,processor);JSONObject json=JSONObject.fromObject(share,config);response.setContentType("text/html;charset=UTF-8");PrintWriter pw=response.getWriter();pw.println(json.toString());pw.close();}}
The URL mapped to showservlet is show.
Data conversion involves two processes:
① The server converts the Java object share to a JSON-compliant string and sends it to the client.
② The browser receives a string conforming to the JSON syntax, converts the string to a JavaScript Object using the evaljson () function, and updates the page data in time.
Of course, the above program is meaningless in practice, just to demonstrate how JSON performs data exchange.