簡述
json格式的數據應用越來越廣泛,結合ajax技術,經常作爲前後臺數據交互的一種格式。前臺會將json格式的數據發送給後臺,後臺也會將json格式的數據返回給前臺。後臺處理json格式的數據使用的是java等語言,而前臺處理json數據使用的是js腳本語言。下面的小案例是在Spring 4mvc框架下,後臺處理前臺發送的json格式的數據。
方法一
- 首先在web.xml中配置編碼過濾器,可以使用Spring自帶的字符編碼過濾器,也可以自定義。
- 新建jsp文件,這這個jsp文件中向後臺發送json格式的數據
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="jquery.js" ></script>
<script type="text/javascript" src="json2.js" ></script>
</head>
<body>
<script>
function userinfo(username,password) {
this.username = username;
this.password = password;
}
function sendAjax(){
var userinforef = new userinfo('張三','1234');
var jsonStringRef = JSON.stringfy(userinforef);
$.post("getJSONString.spring?t="+new Date().getTime(),{
jsonString:jsonStringRef
});
}
</script>
<input type="button" οnclick="sendAjax()" value="提交" />
</body>
這裏要引入json2.js可以將javascript對象轉換爲json格式的字符串
- 編寫後臺,這裏需要引入jsonlib.jar包,使用包中的類進行處理
package b;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import net.sf.json.JSONObject;
/**
* 獲取JSON字符串
* @author acer
*
*/
public class GetJSONString {
@RequestMapping("getJSONString.spring")
public String getJSONString(@RequestParam("jsonString") String jsonString){
//將jsonString轉換爲JSONObject
JSONObject object = JSONObject.fromObject(jsonString);
System.out.println(object.get("username"));
System.out.println(object.get("password"));
return "login.jsp";
}
}
方法二
Spring 4MVC中提供了一種從JSON字符串自動轉換成實體的技術。首先也是最爲·重要的就是添加jar包【jackson-all-1.9.8.jar】
- 建立實體【javabean】
public class UserInfo {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
- 新建控制層
@Controller
public class GetJSONStringToObject {
@RequestMapping(value="createJSONObjectURL",method=RequestMethod.POST)
public String createJSON(@RequestBody UserInfo userinfo){
System.out.println(userinfo.getUsername());
System.out.println(userinfo.getPassword());
return "login.jsp";
}
}
使用@RequestBody註解,前臺需要向Controller提交一段符合JSON格式的數據,Spring 4MVC會自動將其拼裝成javabean。javabean中如果有有參數的構造函數,那必須定義一個無參構造函數,因爲該方法需要調用的是一個無參數的構造方法,然後使用set方法向對象中添加值。
- 修改SpringMVC-servlet.xml配置文件
添加被標註的內容,beans中添加的那三項很重要,否則會報錯。通過<mvc:annotation-driven />註解可以使JSON字符串自動轉換爲實體類,在Spring 4MVC中,DefaultAnnotationHandlerMapping對象負責處理類級別的@RequestMapping註解,而AnnotationMethodHandlerAdapter負責處理方法級別的@RequestMapping註解,如果使用了<mvc:annotation-driven />註解,就會自動註冊DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter倆個bean。
這樣就完成後服務器端解析json字符串的功能的實現。