在服务器端取得客户端传递过来的JSON字符串,转成JSON对象并取值

1.     配置web.xml 配置字符编码过滤器

<filter>

   <filter-name>encodingFilter</filter-name>

  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

   <init-param>

  <param-name>encoding</param-name>

  <param-value>UTF-8</param-value>  

   </init-param> 

   </filter>

  <filter-mapping>

 <filter-name>encodingFilter</filter-name>

 <url-pattern>/*</url-pattern> 

  </filter-mapping>   

 

  <servlet>

  <servlet-name>springMVC</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

  <load-on-startup>1</load-on-startup>

  </servlet>

  <servlet-mapping>

  <servlet-name>springMVC</servlet-name>

  <url-pattern>*.spring</url-pattern>

  </servlet-mapping>

 

2.     新建sendAjax.jsp

 

<script src="jquery-1.8.3.js"></script>
<script type="text/javascript">
function userinfo(username,password){
	this.username=username;
	this.password=password;
}
function sendAjax(){
	var userinfoRef=new userinfo("王淑雅","wsy");
	var jsonStringRef=JSON.stringify(userinfoRef);
	$.post("getJSONString.spring?t="+new Date().getTime(),{jsonString:jsonStringRef});
}
</script>
<title>sendAjax.jsp</title>
</head>
<body>
<input type="button" οnclick="sendAjax()" value="onclick">
</body>

3.创建控制层GetJSONString.java

 

@Controller

public class GetJSONString{

@RequestMapping(value="getJSONString")

public StringgetJSONString(@RequestParam("jsonString")StringjsonString){

   JSONObject object =JSONObject.fromObject(jsonString);

   System.out.println(object.get("username"));

   System.out.println(object.get("password"));

      return "test.jsp";       }

}

posted @ 2019-10-24 13:34  邵德强  阅读(560)  评论(0编辑  收藏  举报