java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringMVC接收页面Post提交的json字符串

SpringMVC接收页面Post提交的json字符串并解析过程

作者:要争气

本文介绍了在SpringMVC中,利用@RequestBody String param接收页面POST提交的JSON字符串,并通过fastjson进行解析的方法,为开发者提供了实用参考

SpringMVC接收页面Post提交的json字符串

json使用的是ali的fastjson

页面提交的是json字符串,后台使用@RequestBody String param接收数据,通过json解析param;

页面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
	function testSpringParam(){ 
		var name=$("#name").val();
		var email=$("#email").val();	
		
		$.ajax({
		    type: 'POST',
		    url: 'paramurl/paramTest.do' ,		   
		    dataType: 'text',
		    contentType:'application/json;charset=UTF-8',
		    data:JSON.stringify([{'name':name,'email':email}]),  //提交json字符串数组,如果提交json字符串去掉[] 
			success:function(data){
				alert(data);
			},
			error:function(textStatus, errorThrown){
				console.log(textStatus);
				alert(textStatus);
			}
		});
	}
</script>
</head>
<body>
<form action="" id="f1" name="f1">
	<input name="name" id="name"  type="text"  value="zhangsan1">

	<input name="email" id="email" type="text" value="zhangsan@163.com">


	<a href="#" rel="external nofollow"  onclick="testSpringParam();">测试</a>
</form>
</body>
</html>
package com.pb.web.controller;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping("/paramurl")
public class ParamController {
	
	@RequestMapping(value="/paramTest.do",method=RequestMethod.POST)
	@ResponseBody
	public String paramTest(@RequestBody String param){		
		System.out.println(param);
		JSONObject jo=new JSONObject();
		
		//如果页面传的是json字符串,用下列方式解析
//		Map<String, Object> m=(Map<String, Object> )jo.parse(param); //string转map
//		System.out.println(m);//		
//		JSONObject parseObject = jo.parseObject(param); //string转json
//		System.out.println(parseObject);
		
		//如果页面传的是json数组字符串,用下列方式解析
		List<Map> parseArray = jo.parseArray(param, Map.class);
		System.out.println(parseArray); //string转list
		
		JSONArray parseArray2 = jo.parseArray(param);
		System.out.println(parseArray2);
		return "ok";
	}
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

阅读全文