当前位置:文档之家› SpringMVC 中整合JSON

SpringMVC 中整合JSON

SpringMVC 中整合JSON
SpringMVC 中整合JSON

SpringMVC 中整合JSON、XML视图二

上篇文章介绍了程序整合的准备工作、结合MarshallingView视图完成jaxb2转换XML、xStream转换XML工作,这次将介绍castor、jibx转换XML。

还有MappingJacksonView用Jackson转换JSON,自己拓展AbstractView定义Jsonlib 的视图完成JSON-lib转换JSON。

上一篇文章:https://www.doczj.com/doc/a06142816.html,/hoojo/archive/2011/04/29/2032571.html

四、用Castor转换XML

1、castor可以通过一个mapping.xml文件对即将转换的Java对象进行描述,然后可以将Java对象按照描述的情况输出XML内容。利用castor转换xml需要添加如下jar包:

如果你还不清楚castor,可以阅读:

for csblogs:https://www.doczj.com/doc/a06142816.html,/hoojo/archive/2011/04/25/2026819.html for csdn:https://www.doczj.com/doc/a06142816.html,/IBM_hoojo/archive/2011/04/25/6360916.aspx

2、你需要在dispatcher.xml中添加castor的相关视图,配置如下:

<--

继承MarshallingView,重写locateToBeMarshalled方法;

解决对象添加到ModelAndView中,转换后的xml是BindingResult信息的bug -->

class="com.hoo.veiw.xml.OverrideMarshallingView">

classpath:mapping.xml

mapping.xml配置

auto-naming="deriveByClass"/>

type="com.hoo.entity.Account">

type="com.hoo.entity.Account">

关于mapping.xml配置的介绍,你可以参考

https://www.doczj.com/doc/a06142816.html,/hoojo/archive/2011/04/25/2026819.html

这篇文章的第三栏目。

3、在使用Spring的MarshallingView的时候,转换的xml结果有时候会带有BindingResult 对象的信息。所以解决办法是重写MarshallingView里面的locateToBeMarshalled方法,这样就可以解决了。下面是重新MarshallingView的class代码:

package com.hoo.veiw.xml;

import java.util.Map;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeansException;

import org.springframework.oxm.Marshaller;

import org.springframework.validation.BindingResult;

import org.springframework.web.servlet.view.xml.MarshallingView;

/**

* function:继承MarshallingView,重写locateToBeMarshalled方法;

* 解决对象添加到ModelAndView中,转换后的xml是BindingResult信息的bug

* @author hoojo

* @createDate 2010-11-29 下午05:58:45

* @file OverrideMarshallingView.java

* @package com.hoo.veiw.xml

* @project Spring3

* @blog https://www.doczj.com/doc/a06142816.html,/IBM_hoojo

* @email hoojo_@https://www.doczj.com/doc/a06142816.html,

* @version 1.0

*/

public class OverrideMarshallingView extends MarshallingView { private Marshaller marshaller;

private String modelKey;

public OverrideMarshallingView() {

super();

}

public OverrideMarshallingView(Marshaller marshaller) {

super(marshaller);

this.marshaller = marshaller;

}

public void setMarshaller(Marshaller marshaller) {

super.setMarshaller(marshaller);

this.marshaller = marshaller;

}

public void setModelKey(String modelKey) {

super.setModelKey(modelKey);

this.modelKey = modelKey;

}

@Override

protected void initApplicationContext() throws BeansException { super.initApplicationContext();

}

@SuppressWarnings("unchecked")

@Override

protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)

throws Exception {

super.renderMergedOutputModel(model, request, response);

}

@SuppressWarnings("unchecked")

@Override

protected Object locateToBeMarshalled(Map model) throws ServletException {

if (modelKey != null) {

Object o = model.get(modelKey);

if (!this.marshaller.supports(o.getClass())) {

throw new ServletException("Model object [" + o + "] retrieved via key [" + modelKey

+ "] is not supported by the Marshaller");

}

return o;

}

for (Object o : model.values()) {

//解决对象添加到ModelAndView中,转换后的xml是BindingResult信息的bug

if (o instanceof BindingResult) {

continue;

}

if (this.marshaller.supports(o.getClass())) {

return o;

}

}

return null;

}

}

4、下面来看看Castor来转换普通JavaBean

package com.hoo.controller;

import java.util.ArrayList;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.servlet.ModelAndView;

import com.hoo.entity.Account;

import com.hoo.entity.Brithday;

import com.hoo.entity.ListBean;

import com.hoo.entity.MapBean;

import https://www.doczj.com/doc/a06142816.html,er;

/**

* function:利用MarshallingView视图,配置CastorMarshaller将Java 对象转换XML

* @author hoojo

* @createDate 2011-4-28 上午10:14:43

* @file CastorMarshallingViewController.java

* @package com.hoo.controller

* @project SpringMVC4View

* @blog https://www.doczj.com/doc/a06142816.html,/IBM_hoojo

* @email hoojo_@https://www.doczj.com/doc/a06142816.html,

* @version 1.0

*/

@Controller

@RequestMapping("/castor/view")

public class CastorMarshallingViewController {

@RequestMapping("/doBeanXMLCastorView")

public ModelAndView doBeanXMLCastorView() {

System.out.println("#################ViewController doBeanXMLCastorView##################");

ModelAndView mav = new ModelAndView("castorMarshallingView"); Account bean = new Account();

bean.setAddress("北京");

bean.setEmail("email");

bean.setId(1);

bean.setName("haha");

Brithday day = new Brithday();

day.setBrithday("2010-11-22");

bean.setBrithday(day);

Map map = new HashMap();

map.put("day", day);

map.put("account", bean);

mav.addObject(bean);//重写MarshallingView的

locateToBeMarshalled方法

//mav.addObject(BindingResult.MODEL_KEY_PREFIX, bean);

//mav.addObject(BindingResult.MODEL_KEY_PREFIX + "account", bean);

return mav;

}

}

Account在mapping配置文件中有进行配置描述。

在浏览器中请求

http://localhost:8080/SpringMVC4View/castor/view/doBeanXMLCastorView.do

就可以看到结果了,结果如下:

hahaemail

北京
<生日brithday="2010-11-22"/>

5、转换Map集合

@RequestMapping("/doMapXMLCastorView")

public ModelAndView doMapXMLCastorView() {

System.out.println("#################ViewController doMapXMLCastorView##################");

ModelAndView mav = new ModelAndView("castorMarshallingView"); Account bean = new Account();

bean.setAddress("北京");

bean.setEmail("email");

bean.setId(1);

bean.setName("haha");

Brithday day = new Brithday();

day.setBrithday("2010-11-22");

bean.setBrithday(day);

Map map = new HashMap();

map.put("day", day);

map.put("account", bean);

MapBean differ = new MapBean();

differ.setMap(map);

mav.addObject(differ);

return mav;

}

在浏览器中请求

http://localhost:8080/SpringMVC4View/castor/view/doMapXMLCastorView.do

结果如下:

id="1">hahaemail

北京
<生日brithday="2010-11-22"/>

6、转换List集合

@RequestMapping("/doListXMLCastorView")

public ModelAndView doListXMLCastorView() {

System.out.println("#################ViewController doListXMLCastorView##################");

ModelAndView mav = new ModelAndView("castorMarshallingView"); List beans = new ArrayList();

for (int i = 0; i < 3; i++) {

Account bean = new Account();

bean.setAddress("address#" + i);

bean.setEmail("email" + i + "@12" + i + ".com");

bean.setId(1 + i);

bean.setName("haha#" + i);

Brithday day = new Brithday();

day.setBrithday("2010-11-2" + i);

bean.setBrithday(day);

beans.add(bean);

User user = new User();

user.setAddress("china GuangZhou# " + i);

user.setAge(23 + i);

user.setBrithday(new Date());

user.setName("jack#" + i);

user.setSex(Boolean.parseBoolean(i + ""));

beans.add(user);

}

ListBean listBean = new ListBean();

listBean.setList(beans);

mav.addObject(listBean);

return mav;

}

在WebBrowser中请求

http://localhost:8080/SpringMVC4View/castor/view/doListXMLCastorView.do

id="1">haha#0email0@https://www.doczj.com/doc/a06142816.html,

address#0
<生日brithday="2010-11-20"/>

xmlns:java="https://www.doczj.com/doc/a06142816.html,"

age="23"sex="false"xsi:type="java:https://www.doczj.com/doc/a06142816.html,er">

china GuangZhou#

0

jack#02011-04-28T14:41:56.703+08:00

haha#1

email1@https://www.doczj.com/doc/a06142816.html,

address#1
<生日

brithday="2010-11-21"/>

xmlns:java="https://www.doczj.com/doc/a06142816.html,"

age="24"sex="false"xsi:type="java:https://www.doczj.com/doc/a06142816.html,er">

china GuangZhou#

1

jack#12011-04-28T14:41:56.703+08:00

haha#2email2@https://www.doczj.com/doc/a06142816.html,

address#2
<生日brithday="2010-11-22"/>

xmlns:java="https://www.doczj.com/doc/a06142816.html,"

age="25"sex="false"xsi:type="java:https://www.doczj.com/doc/a06142816.html,er">

china GuangZhou# 2
jack#2

2011-04-28T14:41:56.703+08:00 7、转换对象数组

@RequestMapping("/doArrayXMLCastorView")

public ModelAndView doArrayXMLCastorView() {

System.out.println("#################ViewController doArrayXMLCastorView##################");

ModelAndView mav = new ModelAndView("castorMarshallingView");

Object[] beans = new Object[3];

for (int i = 0; i < 2; i++) {

Account bean = new Account();

bean.setAddress("address#" + i);

bean.setEmail("email" + i + "@12" + i + ".com");

bean.setId(1 + i);

bean.setName("haha#" + i);

Brithday day = new Brithday();

day.setBrithday("2010-11-2" + i);

bean.setBrithday(day);

beans[i] = bean;

}

User user = new User();

user.setAddress("china GuangZhou# ");

user.setAge(23);

user.setBrithday(new Date());

user.setName("jack#");

user.setSex(true);

beans[2] = user;

mav.addObject(beans);

return mav;

}

在WebBrowser中请求

http://localhost:8080/SpringMVC4View/castor/view/doArrayXMLCastorView.do

结果输出:

haha#0email0@https://www.doczj.com/doc/a06142816.html,

address#0<生日brithday="2010-11-20"/>

haha#1

email1@https://www.doczj.com/doc/a06142816.html,

address#1
<生日

brithday="2010-11-21"/>

xsi:type="java:https://www.doczj.com/doc/a06142816.html,er">

china GuangZhou#
jack#

2011-04-28T14:43:43.593+08:00

结果和List集合有点类似。

总结,使用castor可以转换普通不经过封装的Java类型,但是Map对象则需要进行简单对象封装,然后在mapping中进行描述才行。Castor和其他的框架不同的是,可以在xml配置中进行转换对象的描述规则。

五、用Jibx转换XML

1、jibx可以完成Java对象到xml的转换,但是它需要bind.xml的配置以及多个工具类生成Jibx_BindList信息。稍微有那么点复杂,如果在Spring中利用Jibx的话,需要添加如下jar包:

如果你还不少很了解jibx转换xml这方面的知识,可以阅读:

For cnblogs:https://www.doczj.com/doc/a06142816.html,/hoojo/archive/2011/04/27/2030205.html For csdn:https://www.doczj.com/doc/a06142816.html,/IBM_hoojo/archive/2011/04/27/6366333.aspx

2、下面你需要在dispatcher.xml中添加如下内容

<--需要先编译生成bind.xml,然后再进行绑定编译生成jibx_bandList和运行所需的class-->

class="org.springframework.web.servlet.view.xml.MarshallingView">

value="com.hoo.entity.Account"/>

注意targetClass目标对象不能为空,必须配置。这个class就是你的对象从xml转换到Java 对象的那个对象类型。这里不需要从xml转换到Java,暂时就这样配置就可以了。

3、下面需要用到Account、User、ListBean、MapBean,除了User对象的代码没有提供,其他的都提供了。下面看看User对象的代码:

package com.hoo.entity;

import java.io.Serializable;

import java.util.Date;

public class User implements Serializable {

private static final long serialVersionUID = 8606788203814942679L;

private String name;

private int age;

private boolean sex;

private String address;

private Date brithday;

@Override

public String toString() {

return https://www.doczj.com/doc/a06142816.html, + "#" + this.sex + "#" + this.address + "#" + this.brithday;

}

}

4、下面需要用rg.jibx.binding.BindingGenerator工具类为我们生成bind.xml内容,命令如下:

首先在dos命令控制台进入到当前工程的WEB-INF目录,然后输入命令:

E:\Study\SpringMVC4View\WebRoot\WEB-INF>java -cp

classes;lib/jibx-tools.jar;lib/log4j-1.2.16.jar

org.jibx.binding.BindingGenerator -f bind.xml

com.hoo.entity.Account https://www.doczj.com/doc/a06142816.html,er com.hoo.entity.ListBean com.hoo.entity.MapBean

用空格分开要转换到bind.xml中的JavaBean,运行上面的命令你可以看到如下结果:

Running binding generator version 0.4

Warning: field list requires mapped implementation of item classes Warning: reference to interface or abstract class java.util.Map requires mapped implementation

生成bind.xml内容如下:

usage="optional"/>

usage="optional"/>

usage="optional"/>

factory="org.jibx.runtime.Utility.arrayListFactory"/>

这样还没有完,Map要经过特殊出来。我们要修改下MapBean的配置,修改后如下:

marshaller="com.hoo.util.HashMapper"

unmarshaller="com.hoo.util.HashMapper"/>

HashMapper代码如下:

package com.hoo.util;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import org.jibx.runtime.IAliasable;

import org.jibx.runtime.IMarshallable;

import org.jibx.runtime.IMarshaller;

import org.jibx.runtime.IMarshallingContext;

import org.jibx.runtime.IUnmarshaller;

import org.jibx.runtime.IUnmarshallingContext;

import org.jibx.runtime.JiBXException;

import org.jibx.runtime.impl.MarshallingContext;

import org.jibx.runtime.impl.UnmarshallingContext;

/**

*

function:https://www.doczj.com/doc/a06142816.html,/Open-Source/Java/XML/JiBX/tutor ial/example21/HashMapper.java.htm

* @file HashMapper.java

* @package com.hoo.util

* @project WebHttpUtils

* @blog https://www.doczj.com/doc/a06142816.html,/IBM_hoojo

* @email hoojo_@https://www.doczj.com/doc/a06142816.html,

* @version 1.0

*/

public class HashMapper implements IMarshaller, IUnmarshaller, IAliasable

{

private static final String SIZE_ATTRIBUTE_NAME = "size";

private static final String ENTRY_ELEMENT_NAME = "entry";

private static final String KEY_ATTRIBUTE_NAME = "key";

private static final int DEFAULT_SIZE = 10;

private String m_uri;

private int m_index;

private String m_name;

public HashMapper() {

m_uri = null;

m_index = 0;

m_name = "hashmap";

}

public HashMapper(String uri, int index, String name) {

m_uri = uri;

m_index = index;

m_name = name;

}

/* (non-Javadoc)

* @see org.jibx.runtime.IMarshaller#isExtension(int)

*/

public boolean isExtension(int index) {

return false;

}

/* (non-Javadoc)

* @see org.jibx.runtime.IMarshaller#marshal(https://www.doczj.com/doc/a06142816.html,ng.Object,

* org.jibx.runtime.IMarshallingContext)

*/

@SuppressWarnings("unchecked")

public void marshal(Object obj, IMarshallingContext ictx) throws JiBXException {

// make sure the parameters are as expected

if (!(obj instanceof HashMap)) {

throw new JiBXException("Invalid object type for marshaller"); } else if (!(ictx instanceof MarshallingContext)) {

throw new JiBXException("Invalid object type for marshaller"); } else {

// start by generating start tag for container

MarshallingContext ctx = (MarshallingContext)ictx;

HashMap map = (HashMap)obj;

ctx.startTagAttributes(m_index, m_name).

attribute(m_index, SIZE_ATTRIBUTE_NAME, map.size()).

closeStartContent();

// loop through all entries in hashmap

Iterator iter = map.entrySet().iterator();

while (iter.hasNext()) {

Map.Entry entry = (Map.Entry)iter.next();

ctx.startTagAttributes(m_index, ENTRY_ELEMENT_NAME);

if (entry.getKey() != null) {

ctx.attribute(m_index, KEY_ATTRIBUTE_NAME,

entry.getKey().toString());

}

ctx.closeStartContent();

if (entry.getValue() instanceof IMarshallable) {

((IMarshallable)entry.getValue()).marshal(ctx);

ctx.endTag(m_index, ENTRY_ELEMENT_NAME);

} else {

throw new JiBXException("Mapped value is not marshallable");

}

}

// finish with end tag for container element

ctx.endTag(m_index, m_name);

}

}

/* (non-Javadoc)

* @see

org.jibx.runtime.IUnmarshaller#isPresent(org.jibx.runtime.IUnmarshall ingContext)

*/

public boolean isPresent(IUnmarshallingContext ctx) throws JiBXException {

return ctx.isAt(m_uri, m_name);

}

/* (non-Javadoc)

* @see org.jibx.runtime.IUnmarshaller#unmarshal(https://www.doczj.com/doc/a06142816.html,ng.Object, * org.jibx.runtime.IUnmarshallingContext)

*/

@SuppressWarnings("unchecked")

public Object unmarshal(Object obj, IUnmarshallingContext ictx) throws JiBXException {

// make sure we're at the appropriate start tag

UnmarshallingContext ctx = (UnmarshallingContext)ictx;

if (!ctx.isAt(m_uri, m_name)) {

ctx.throwStartTagNameError(m_uri, m_name);

}

// create new hashmap if needed

int size = ctx.attributeInt(m_uri, SIZE_ATTRIBUTE_NAME, DEFAULT_SIZE);

HashMap map = (HashMap)obj;

if (map == null) {

map = new HashMap(size);

}

// process all entries present in document

ctx.parsePastStartTag(m_uri, m_name);

while (ctx.isAt(m_uri, ENTRY_ELEMENT_NAME)) {

Object key = ctx.attributeText(m_uri, KEY_ATTRIBUTE_NAME, null);

ctx.parsePastStartTag(m_uri, ENTRY_ELEMENT_NAME);

Object value = ctx.unmarshalElement();

map.put(key, value);

ctx.parsePastEndTag(m_uri, ENTRY_ELEMENT_NAME);

}

ctx.parsePastEndTag(m_uri, m_name);

return map;

}

public boolean isExtension(String arg0) {

return false;

}

}

然后,再编译下就可以了。命令如下:

E:\Study\SpringMVC4View\WebRoot\WEB-INF>java -cp

classes;lib/jibx-bind.jar https://www.doczj.com/doc/a06142816.html,pile -v bind.xml

这样你就可以启动tomcat服务器,没有错误就ok了。

5、转换JavaBean到XML

package com.hoo.controller;

import java.util.ArrayList;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView;

import com.hoo.entity.Account;

import com.hoo.entity.Brithday;

import com.hoo.entity.ListBean;

import com.hoo.entity.MapBean;

import https://www.doczj.com/doc/a06142816.html,er;

/**

* function:利用Jibx和JibxMarshaller转换Java对象到XML

* @author hoojo

* @createDate 2011-4-28 下午03:05:11

* @file JibxMarshallingViewController.java

* @package com.hoo.controller

* @project SpringMVC4View

* @blog https://www.doczj.com/doc/a06142816.html,/IBM_hoojo

* @email hoojo_@https://www.doczj.com/doc/a06142816.html,

* @version 1.0

*/

@Controller

@RequestMapping("/jibx/view")

public class JibxMarshallingViewController {

@RequestMapping("/doXMLJibxView")

public ModelAndView doXMLJibxView() {

System.out.println("#################ViewController doXMLJibxView##################");

ModelAndView mav = new ModelAndView("jibxMarshallingView"); Account bean = new Account();

bean.setAddress("北京");

bean.setEmail("email");

bean.setId(1);

bean.setName("haha");

Brithday day = new Brithday();

day.setBrithday("2010-11-22");

bean.setBrithday(day);

mav.addObject("中国");

mav.addObject(bean);

return mav;

}

}

上面的ModelAndView配置的视图就是我们在dispatcher中配置过的视图

在WebBrowser中请求

http://localhost:8080/SpringMVC4View/jibx/view/doXMLJibxView.do

结果如下:

id="1">hahaemail

北京
2010-11-22

6、转换List到XML

/**

* function:转换带有List属性的JavaBean

* @author hoojo

* @return

*/

@RequestMapping("/doListXMLJibx")

public ModelAndView doListXMLJibxView() {

System.out.println("#################ViewController doListXMLJibxView##################");

ModelAndView mav = new ModelAndView("jibxMarshallingView");

List beans = new ArrayList();

for (int i = 0; i < 3; i++) {

Account bean = new Account();

bean.setAddress("address#" + i);

bean.setEmail("email" + i + "@12" + i + ".com");

bean.setId(1 + i);

bean.setName("haha#" + i);

Brithday day = new Brithday();

day.setBrithday("2010-11-2" + i);

bean.setBrithday(day);

beans.add(bean);

User user = new User();

user.setAddress("china GuangZhou# " + i);

user.setAge(23 + i);

user.setBrithday(new Date());

user.setName("jack#" + i);

user.setSex(Boolean.parseBoolean(i + ""));

beans.add(user);

}

ListBean list = new ListBean();

list.setList(beans);

mav.addObject(list);

return mav;

}

在浏览器中请求http://localhost:8080/SpringMVC4View/jibx/view/doListXMLJibx.do 结果如下:

id="1">haha#0email0@https://www.doczj.com/doc/a06142816.html,

addre ss#0

2010-11-20

brithday="2011-04-28T08:27:23.046Z">jack#0

china GuangZhou# 0

id="2">haha#1email1@https://www.doczj.com/doc/a06142816.html,

addre ss#1

2010-11-21

sex="false"brithday="2011-04-28T08:27:23.046Z">

jack#1

china GuangZhou# 1

id="3">haha#2email2@https://www.doczj.com/doc/a06142816.html,

addre ss#2

2010-11-22

brithday="2011-04-28T08:27:23.046Z">jack#2

china GuangZhou# 2

7、转换Map到XML

/**

* function:转换带有Map属性的JavaBean

* @author hoojo

* @return

*/

@RequestMapping("/doMapXMLJibx")

public ModelAndView doMapXMLJibxView() {

System.out.println("#################ViewController doMapXMLJibxView##################");

ModelAndView mav = new ModelAndView("jibxMarshallingView");

MapBean mapBean = new MapBean();

Map map = new HashMap();

Account bean = new Account();

bean.setAddress("北京");

bean.setEmail("email");

bean.setId(1);

bean.setName("jack");

Brithday day = new Brithday();

day.setBrithday("2010-11-22");

bean.setBrithday(day);

map.put("NO1", bean);

bean = new Account();

bean.setAddress("china");

bean.setEmail("tom@https://www.doczj.com/doc/a06142816.html,");

bean.setId(2);

bean.setName("tom");

day = new Brithday("2011-11-22");

bean.setBrithday(day);

map.put("NO2", bean);

mapBean.setMap(map);

mav.addObject(mapBean);

return mav;

}

在浏览器中请求:

http://localhost:8080/SpringMVC4View/jibx/view/doMapXMLJibx.do

结果如下:

id="2">tomtom@https://www.doczj.com/doc/a06142816.html,

china

2011-11-22

id="1">jackemail

北京

2010-11-22

总结,jibx应用比较广,在WebService中都有使用jibx。Jibx速度比较快,就是在开始部署使用的时候需要写bind.xml文件。不过官方提供了工具类,这个也不麻烦。

六、 Jackson转换Java对象

jQuery+AJAX+JSON

jQuery 1. 什么是jQuery?? jQuery是一个优秀的JavaScript框架,一个轻量级的JavaScript类库。 jQuery的核心理念是Write less,Do more。 使用jQuery可以兼容各种浏览器,方便的处理HTML、Events、动画效果等,并且方便的为网站提供AJAX交互。 2.jQuery的特点: 利用选择器来查找要操作的节点,然后将这些节点封装成一个jQuery对象,通过调用jQuery对象的方法或者属性来实现对底层被封装的节点的操作。 好处:a、兼容性更好;b、代码更简洁 3.编程步骤: step1、使用选择器查找节点 step2、调用jQuery的属性和方法 4.jQuery对象与DOM对象之间的转换 1. 什么是jQuery对象?? jQuery对象是jQuery对底层对象的一个封装,只有创建了这个对象,才能使用类库中提供的方法。 2. DOM对象 ----> jQuery对象 DOM对象向jQuery对象的转变很容易,外面追加$和圆括号即可。 function f( ){ var obj = document.getElementById(‘d1’); //DOM -> jQuery对象

var $obj = $(obj); $obj.html(‘hello jQuery’); } 3. jQuery对象 ----> DOM对象 jQuery对象向DOM对象转化,通过调用get方法加参数值0即可$obj.get(0)。 function f( ){ var $obj = $(‘#d1’); //jQuery对象 -> DOM var obj = $(obj).get (0); obj.innerHTML = ‘hello jQuery’; } 5. jQuery选择器 1. 什么是jQuery选择器?? jQuery选择器是一种类似CSS选择器的特殊说明符号,能够帮助jQuery 定位到要操作的元素上,使用了选择器可以帮助HTML实现内容与行为的分离。只需要在元素上加上Id属性。 2. 选择器的种类 a、基本选择器 #id根据指定的ID匹配一个元素 .class根据指定的类匹配一个元素 element根据的指定的元素名匹配所有的元素

后台转换JSON数据类型,前台解析JSON数据等等例子总结

后台转换JSON数据类型,前台解析JSON数据等等例子总结 JSON对象: JSONObject obj = new JSONObject(); obj.put("result", 0); obj.put("message", message); return obj.toJSONString(); 前台解析: Success:function(data){ var result = data.result; var message = data.message; } json对象中有json对象的写法: Objstr为一个JSONObject obj的String转换 private String getsuccess(String objstr,int number){ JSONObject obj = new JSONObject(); obj.put("result", 1); obj.put("obj", objstr); obj.put("number", number); return obj.toJSONString(); }

前台解析: Picjson为success返回的data var result = picjson.result; if (result==1) { var objdata = picjson.obj; var data = eval('(' + objdata + ')'); var num = picjson.number; picurl = null; showpiclist(data, num); } else{ alert(picjson.message); picurl = null; } list转成json对象 需要的包: https://www.doczj.com/doc/a06142816.html,mons-lang.jar https://www.doczj.com/doc/a06142816.html,mons-beanutils.jar https://www.doczj.com/doc/a06142816.html,mons-collections.jar https://www.doczj.com/doc/a06142816.html,mons-logging.jar

Java获取http和https协议返回的json数据

Java获取http和https协议返回的json数据 现在很多公司都是将数据返回一个json,而且很多第三方接口都是返回json数据,而且还需要使用到http协议,http协议是属于为加密的协议,而https协议需要SSL证书,https是将用户返回的信息加密处理,然而我们要获取这些数据,就需要引入SSL证书。现在我提供两个方法,帮助各位如何获取http和https返回的数据。 获取http协议的数据的方法,如下: public static JSONObject httpRequest(String requestUrl, String requestMethod) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { URL url = new URL(requestUrl); // http协议传输 HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); // 设置请求方式(GET/POST)

httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); // 将返回的输入流转换成字符串 InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); // 释放资源 inputStream.close(); inputStream = null; httpUrlConn.disconnect(); jsonObject =

Jquery Ajax 异步处理Json数据

啥叫异步,啥叫Ajax.咱不谈啥XMLHTTPRequest.通俗讲异步就是前台页面javascript能调用后台方法.这样就达到了无刷新.所谓的Ajax.这里我们讲二种方法 方法一:(微软有自带Ajax框架) 在https://www.doczj.com/doc/a06142816.html,里微软有自己的Ajax框架.就是在页面后台.cs文件里引入 using System.Web.Services 空间然后定义静态方法(方法前加上 [WebMethod]) [WebMethod] public static string ABC(string ABC) { return ABC; } 好了,现在我们谈谈前台Js怎么处理后台返回的数据吧,可利用Jquery处理返回的纯html,json,Xml等数据.这里我们演示返回返回的数据有string、集合(List<>)、类. 但都返回Json格式(Json轻量级比XML处理起来简单).看看前台是怎么解析这些数据的. 代码如下: 前台页面: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> 无标题页