json前后台传值
谈到JSON,简单的说就是一种数据交换格式。近年来,其在服务器之间交换数据的应用越来越广,相比XML其格式更简单、编解码更容易、扩展性更好,所以深受开发人员的喜爱。
成都创新互联公司专业为企业提供攀枝花网站建设、攀枝花做网站、攀枝花网站设计、攀枝花网站制作等企业网站建设、网页设计与制作、攀枝花企业网站模板建站服务,10多年攀枝花做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。
下面简单的写一下在项目中前后台json传值的一个小例子,供大家参考、查阅。
一:前台传后台
1.前台jsp页面代码:
在index中将实体对象(自己创建即可)插入list中,再将list集合转化成json数组,利用post方式发送AJAX请求,将这个json数组发送至后台(servlet),再在后台进行解析即可。
index.jsp
<%@ page language="java" import="java.util.Date,com.badminton.utils.JsonDateValueProcessor,java.text.SimpleDateFormat,java.util.List,net.sf.json.JSONArray,net.sf.json.JSONObject,net.sf.json.JsonConfig,java.util.ArrayList,com.badminton.entity.Athlete,net.sf.json.JSONObject" pageEncoding="utf-8"%>My first json page <% SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); Athlete athlete1 = new Athlete(); athlete1.setAthlete_id(1003); athlete1.setAthlete_name("林丹"); athlete1.setAthlete_sex("男"); Date athlete_age1 = format1.parse("1983-10-14");//是java.util.date athlete1.setAthlete_age(athlete_age1); athlete1.setCoach_id(101); athlete1.setEvent_id(1); athlete1.setService_status("1"); athlete1.setExperience("2013年第12届全运会男单冠军。"); Athlete athlete2 = new Athlete();//记录2 athlete2.setAthlete_id(1004); athlete2.setAthlete_name("鲍春来"); athlete2.setAthlete_sex("男"); Date athlete_age2 = format1.parse("1988-10-14"); athlete2.setAthlete_age(athlete_age2); athlete2.setCoach_id(101); athlete2.setEvent_id(1); athlete2.setService_status("1"); athlete2.setExperience("2011年亚洲羽毛球锦标赛亚军。"); Listlist1 = new ArrayList (); list1.add(athlete1); list1.add(athlete2); JsonConfig jsonConfig = new JsonConfig();//解决date类型的传输问题 jsonConfig.registerJsonValueProcessor(Date.class , new JsonDateValueProcessor()); JSONArray jsonarray = JSONArray.fromObject(list1, jsonConfig); %>
2.后台解析代码:
后台接受前台传来的json对象,解析插入数据库中,且反给前台一个是否成功的消息。具体插入数据库的代码自己编写一个即可。
JsonServlet.java
package com.badminton.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.badminton.app.AthleteAction; import net.sf.json.JSONObject; import net.sf.json.JSONArray; public class JsonServlet extends HttpServlet { public JsonServlet() { super(); } public void destroy() { super.destroy(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); AthleteAction athleteaction=new AthleteAction(); try { String json1 = request.getParameter("athletehead");//接收athlete表的头数据 String json2 = request.getParameter("athlete");//接收athlete表数据 json1 = java.net.URLDecoder.decode(json1,"UTF-8"); json2 = java.net.URLDecoder.decode(json2, "UTF-8"); if ((json1 != "") && (json2 != "")) { //System.out.println("json1:"+json1); JSONObject jsonObject1 =JSONObject.fromObject(json1);//生成json对象 JSONArray jsonArray2 = JSONArray.fromObject(json2);//生成JSON数组 for(int i=0;i"); out.println(" " + result + " "); out.println(""); out.close(); } else{ String result = "传输过程出错,请重传!"; out.println(""); out.println(" "); out.close(); } } catch (Exception e) { System.out .println("JsonServlet doPost(HttpServletRequest request, HttpServletResponse response) 报错:" + e.getMessage()); } } public void init() throws ServletException { } }" + result + " "); out.println("
3.解决传递日期的一个工具类
若没有这个工具类,date型数据会被转化成json数组的格式,后台解析起来会很复杂。
JsonDateValueProcessor.java
package com.badminton.utils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import net.sf.json.JsonConfig; import net.sf.json.processors.JsonValueProcessor; public class JsonDateValueProcessor implements JsonValueProcessor{ /** * datePattern */ private String datePattern = "yyyy-MM-dd"; /** * JsonDateValueProcessor */ public JsonDateValueProcessor() { super(); } /** * @param format */ public JsonDateValueProcessor(String format) { super(); this.datePattern = format; } /** * @param value * @param jsonConfig * @return Object */ public Object processArrayValue(Object value, JsonConfig jsonConfig) { return process(value); } /** * @param key * @param value * @param jsonConfig * @return Object */ public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) { return process(value); } /** * process * @param value * @return */ private Object process(Object value) { try { if (value instanceof Date) { SimpleDateFormat sdf = new SimpleDateFormat(datePattern, Locale.UK); return sdf.format((Date) value); } return value == null ? "" : value.toString(); } catch (Exception e) { return ""; } } /** * @return the datePattern */ public String getDatePattern() { return datePattern; } /** * @param pDatePattern the datePattern to set */ public void setDatePattern(String pDatePattern) { datePattern = pDatePattern; } }
二:后台传前台
后台以list和map两种形式封装json,前台注意json数组和json对象解析时的差别即可。
1.TestJson.java
package com.badminton.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class TestJson extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String str= request.getParameter("name");//得到ajax传递过来的paramater System.out.println(str); PrintWriter out = response.getWriter(); List list = new ArrayList();//传递List //Map m=new HashMap();//传递Map User u1=new User(); u1.setUsername("zah"); u1.setPassword("123"); User u2=new User(); u2.setUsername("ztf"); u2.setPassword("456"); list.add(u1); //添加User对象 list.add(u2); //添加User对象 //m.put("u1", u1); //m.put("u2", u2); JSONArray jsonArray2 = JSONArray.fromObject( list );//转化成json对象 //JSONObject jo=JSONObject.fromObject(m);//转化Map对象 out.print(jsonArray2);//返给ajax请求 System.out.println(jsonArray2); //out.print(jo);//返给ajax请求 } }
2.showjson.jsp
利用Jquery、AJAX异步传输的方式接受后台的发送请求。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
附件:http://down.51cto.com/data/2364170
分享题目:json前后台传值
本文地址:http://pwwzsj.com/article/jshccd.html