spring接受和发送json对象(原始,非原始)

<%@ 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>响应的结果视图</title>
</head>
<body>

	<!-- 6发送ajax异步请求,响应json数据 -->
	<!-- <a href="springmvc/testResponseJson">测试响应json数据</a> -->
	<input type="button" value="测试json异步数据" id="testAjax"/>
</body>
</html>

index.jsp测试页面

 

package com.itheima.web.controller;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.itheima.domain.Account;


@Controller("jsonController")
@RequestMapping("/springmvc")
public class JsonController {
	
	/**原始方法
	 * 测试响应json数据
	 * 应用场景
	 * 	一般都是异步请求,不希望浏览器刷新
	 * @return
	 * @throws Exception 
	 * @throws IllegalArgumentException 
	 */
	@RequestMapping("/testResponseJson")
	public void testResponseJson(HttpServletResponse response) throws Exception {
		//1.接收到用户提交的账户id,根据id查询账户信息
		Account account = findAccountById(1);
		
		Field[] fs = Account.class.getDeclaredFields();
		StringBuffer ss = new StringBuffer();
		
		for(Field field:fs) {
			field.setAccessible(true);
			ss.append("{");
			ss.append("\"").append(field.getName()).append("\":\"").append(field.get(account)).append("\",");;
		}
		
		ss.delete(ss.length()-1,ss.length());
		ss.append("}");
		System.out.println(ss.toString());
		//2.把账户信息转换成json格式响应给浏览器
		response.setContentType("text/json;charset=UTF-8");
		response.getWriter().write(ss.toString());
		
	}	
	
	
	/**
     *springmvc方式
     *使用@ResponseBody注解实现响应json数据
	 * 使用@ReuqestBody封装json格式数据到Account实体类中
	 * @return
	 * @throws Exception 
	 * @throws IllegalArgumentException 
	 */
	@RequestMapping("/testResponseJson2")
	public @ResponseBody Account testResponseJson2(@RequestBody Account account) {
		//1.接收到用户提交的账户id,根据id查询账户信息
		System.out.println(account);
		return account;
		
	}	
	
	
	
	/**
	 * 根据id查询账户信息
	 */
	private Account findAccountById(Integer id) {
		
		Account account = new Account();
		account.setName("test");
		account.setMoney(1234f);
		account.setId(1);
		
		return account;
		
	}
}

 Jsoncontroller控制器对象

 

package com.itheima.domain;

import java.io.Serializable;
/**
 * 账户的实体类
 * @author ChonZ
 *
 */
public class Account implements Serializable {
	private Integer id;
	private String name;
	private Float money;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Float getMoney() {
		return money;
	}
	public void setMoney(Float money) {
		this.money = money;
	}
	
}

 Account类,用于当过json容器

 

<%@ 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>响应的结果视图</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.min.js"> </script>
<script type="text/javascript">
	$function(){
		$("#testAjax").click(function(){
			$.ajax({
				type:"post",//请求方式
				url:"springmvc/testResponseJson",//请求的地址
				dataType:"json",//响应的数据
				
				success:function(data){//执行成功后的回调函数
					alert(data)
				}
			});
		});
	}


</script>
</head>
<body>

	<!-- 6发送ajax异步请求,响应json数据 -->
	<a href="springmvc/testResponseJson">测试响应json数据</a>
	<input type="button" value="测试json异步数据" id="testAjax"/>
</body>
</html>

发送json到服务器,和接收服务器发送的json

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx.xsd">
		<!-- 告知spring创建容器时要扫描的包 -->
		<context:component-scan base-package="com.itheima"></context:component-scan>
		
		<!-- 配置springmvc的视图解析器,用于找到响应的jsp -->
		<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
			<property name="prefix" value="/WEB-INF/pages/"></property>
			<property name="suffix" value=".jsp"></property>
		</bean>
		
		<!-- 开启springmvc的注解  -->
		<mvc:annotation-driven></mvc:annotation-driven>
		
		<!-- 设置静态资源不参与springmvc编码的过滤 -->
		<mvc:resources location="/css/" mapping="/css/**"/>
		<mvc:resources location="/images/" mapping="/images/**"/>
		<mvc:resources location="/js/" mapping="/js/**"/>
</beans>

 springmvc.xml配置文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值