SpringMVC之@RequestBody, @ResponseBody

@ResponseBody返回json的几种方式

<span style="font-size:14px;">@RequestMapping(value="/getCourseInJson/{id}",method=RequestMethod.GET)
	public @ResponseBody TableStudent getCourseInJson(@PathVariable Integer id){
		TableStudent student=studentService.queryStuById(id);
		DEGUB_LOG.debug(ReflectionToStringBuilder.toString(student));
		return student;
	}
	
	@RequestMapping(value="getStuJSONById",method=RequestMethod.GET)
	public ResponseEntity<TableStudent> getStuJSONById(@RequestParam("id")int id){
		TableStudent student=studentService.queryStuById(id);
		DEGUB_LOG.debug(ReflectionToStringBuilder.toString(student));
		return new ResponseEntity<TableStudent>(student, HttpStatus.OK);
	}
	
	
	@RequestMapping("/listAll")  
	@ResponseBody  
	public Map<String, Object> listAll() {  
		Map<String, Object> result = new HashMap<String, Object>();  
	    result.put("total",100);  
	    result.put("rows", 10);  
	    return result;   
	}</span>

视图分配器

<span style="font-size:14px;"><!-- 配置ViewResolver。 可以用多个ViewResolver。 使用order属性排序。 InternalResourceViewResolver放在最后。 -->
	<bean
		class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
		<property name="order" value="1" />
		<property name="mediaTypes">
			<map>
				<entry key="json" value="application/json" />
				<entry key="xml" value="application/xml" />
				<entry key="htm" value="text/html" />
			</map>
		</property>

		<property name="defaultViews">
			<list>
				<!-- JSON View -->
				<bean
					class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
				</bean>
			</list>
		</property>
		<property name="ignoreAcceptHeader" value="true" />
	</bean>

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/page/" />
		<property name="suffix" value=".jsp" />
	</bean></span>


@RequestBody获取ajax的json数据

@RequestBody接收的是一个Json对象的字符串,而不是一个Json对象。然而在ajax请求往往传的都是Json对象,后来发现用 JSON.stringify(data)的方式就能将对象变成字符串。同时ajax请求的时候也要指定dataType: "json",contentType:"application/json" 这样就可以轻易的将一个对象或者List传到Java端,使用@RequestBody即可绑定对象或者List.


jsp请求页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
	request.setAttribute("path", path);
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'TestRequestBody.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript" src="${path}/javascript/jquery.js"></script>
	<script type="text/javascript" src="${path}/javascript/jquery-json-2.4.js"></script>
	<script type="text/javascript">  
	    $(document).ready(function(){  
	        var saveDataAry=[];  
	        var data1={"name":"test","sex":1,"age":22};  
	        var data2={"name":"ququ","sex":2,"age":33};  
	        saveDataAry.push(data1);  
	        saveDataAry.push(data2);    
	        console.log(saveDataAry);
	        $.ajax({ 
	            type:"POST", 
	            url:"${path}/stu/showStudent.action", 
	            dataType:"json",      
	            contentType:"application/json",               
	            data:JSON.stringify(saveDataAry), 
	            success:function(data){ 
	                                       
	            } 
	         }); 
	    });  
	</script> 
  </head>
  
  <body>
    This is my JSP page. <br>
  </body>
</html>

跳转和处理json

@RequestMapping(value = "showStudent", method = {RequestMethod.POST }) 
    @ResponseBody  
    public void showStudent(@RequestBody List<TableStudent> stus) { 
         for(int i=0;i<stus.size();i++){
        	 DEGUB_LOG.debug(ReflectionToStringBuilder.toString(stus.get(i)));
         }
    }
	
	@RequestMapping(value="forwardShowStudent",method = {RequestMethod.GET })
	public String forwardShowStudent(){
		return "TestRequestBody";
	}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值