`

JAVA与JS交互

阅读更多
问题:JAVA与JS交互,将数据封装成JSON形式传递到页面中

一.JSON的概念

参考文献:http://www.w3school.com.cn/json/index.asp

总结:
  • JSON:JavaScript 对象表示法(JavaScript Object Notation)
  • 数据在名称/值对中
  • 数据由逗号分隔
  • 花括号保存对象
  • 方括号保存数组

JSON格式举例:
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}


注意:
1.若web层中的方法使用数据流的方式传递JSON数据,
  action中不使用return SUCCESS ;方式跳转页面,应该写成返回值为return null,
  否则,报错unable to find resource "该action名称"
2.传递po(persistent object 持久类),字符串等
二、交互方法

1.数据流的方式
1.1.HttpServletResponse
设置key与value的形式,即JS需要通过key接收value

下面是具体实现方式:
public void output(JSONObject json) {
try {
HttpServletResponse response = getResponse();
response.setContentType("text/json;charset=UTF-8");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.getWriter().write(json.toString());
response.getWriter().flush();
} catch (IOException e) {
e.printStackTrace();
}
}


说明:
(1)第4行,设置Response的编码方式为UTF-8
(2)第5、6行,no-cache 用于指示请示或响应消息不能缓存
(3)第7行,Expires实体报头域给出响应过期的日期和时间。为了让代理服务器或浏览器在一段时间以后更新缓存中(再次访问曾访问过的页面时,直接从缓存中加载,缩短响应时间和降低服务器负载)的页面,使用Expires实体报头域指定页面过期时间。例:Expires:Thu,15 Sep 2006 16:23:12 GMT,HTTP1.1的客户端和缓存必须将其他非法的日期格式(包括0)看作已经过期。如:为了让浏览器不要缓存页面,也可以利用Expires实体报关域,设置为0
(4)第8行,功能:向前台页面显示一段信息,当在普通的url方式中,会生成一个新的页面来显示内容。当在ajax的方式中,会在alert中显示内容。
(5)第9行,容器的实现会认为你要输出的内容无法确定大小

参考文献:
(1)http://zhidao.baidu.com/link?url=snuVaBckoUyMxyu2v9QT3gJBBx3PLwPY0MiYTI3b2cNvDystM-0jaFL-2QkM1DYQ2t_3jaiJC0yZcozaS6B7Hq
(2)http://zhidao.baidu.com/link?url=-oCv-j5KoBvnd1-aRyn1S3QvUdKN_6m93cfu8YYJOMVjqXflKR5c1g_eRyCd3j9K1TGBn4oRGe5554-jT6SW7CzbwT6EZsh5tQJ2HDajeQu

应用举例:
public void sendJsonMessage(String key ,String value){
JSONObject json = new JSONObject();
json.put(key, value);
output(json);
}

说明:
(1)key是JS中接收数据的属性名名称
(2)value是JAVA要传到JS中的数据

1.2.PrintWriter
直接向JS传递JSON,JS需要通过key接收value

public class PrintUtil {	
//向response中输出Json
public static void printJson(HttpServletResponse response,String json){
if(json == null || "".equals(json)){
return;
}
PrintWriter writer = null;
try {
//向浏览器发送一个响应头,设置浏览器的解码方式为UTF-8
response.setContentType("application/json; charset=UTF-8");
writer = response.getWriter();
writer.print(json);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.flush();
writer.close();
}
}
}
}


应用举例:
PrintUtil.printJson(this.response, "0");

说明:通过response向页面中输出Json,即respose是将处理结果反馈给页面

@Action(value = "orderDeleteForever")
public void orderDeleteForever() throws Exception{		
String orderId = request.getParameter("orderId");		
if(StringUtils.isBlank(orderId)){
return;
}
JSONObject jsonObject = new JSONObject();
try{
orderService.orderDeleteForever(Long.parseLong(orderId));
}catch(Exception e){
jsonObject.accumulate("msg", "err");//封装key与value
}
jsonObject.accumulate("msg", "ok");
PrintUtil.printJson(this.response,jsonObject.toString());
}


JSONArray jsonObjectFromMap = JSONArray.fromObject(permissions);
PrintUtil.print(response ,jsonObjectFromMap.toString());
PrintUtil.print(response ,jsonObjectFromMap.toString()); 

JSONObject jsonObjectFromMap = JSONObject.fromObject(cartTotalByInventory);
request.setAttribute("jsonMap", jsonObjectFromMap);


2.类属性添加set get 方法,action 返回值为JSON

private String message;

public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Action(value = "delMerchantMessage", results = { @Result(name = SUCCESS, type = ResultTypeConstants.JSON) })
public String delMerchantMessage() {
int result = ServiceUtil.businessInfoService.delBusinessInfoHistoryByMId(merchant.getId());
message = "删除成功!";
return SUCCESS;
}


返回值类型为JSON,会将类中所有成员属性以JSON串的方式传到页面上
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics