(二)SpringMVC使用之@ResponseBody

 

一、SpringMVC前端返回后台的参数

(1)@RequestParam  从请求参数中获取参数,相当于request.getParameter(" ")

@RequestMapping(value = "/student2")
public String parseParams(@RequestParam(value = "nameVal", required = true) String name){

  XXX;

}

(2)@PathVariable    地址占位符

(3)@RequestBody   取request这个消息体(可以组装json对象)

 

二、注解@ResponseBody的作用

   作用:后端给前端的返回类型不是String或者ModelAndView格式的数据

   前台json数据  --->  后端解析(@RequestBody注解、@PathVariable注解、@ RequestParam注解、request.getParameter 等方式   ) ---> 返回数据到前端(常见4种返回类型:类对象、列表、键值对、字符串)

三、四种常见的@ResponseBody返回类型及处理方式

其中,实体类Student有3个属性:

public class Student
{
private Integer age;
private String name;
private Integer id;

}

前端AJAX请求 后端处理后,返回数据格式 前端处理方式
通常以json传递 类对象,Student data.name
同上 列表, List<Student>


for(var i=0;i<data.length;i++){
alert( lst[i].name);
}

同上 键值对,Map<"mapStu",Student> data.mapStu.name
同上 字符串,"strStu" data == "strStu"

 

 

四、前端AJAX的使用

type:   请求方式(post或get)默认为get。 put和delete也可以使用,但仅部分浏览器支持。

cache:   要求为Boolean类型的参数,默认为true(当dataType为script时,默认为false),设置为false将不会从浏览器缓存中加载请求信息。

dataType:要求为String类型的参数,预先返回服务器的数据类型。如不指定,JQuery将自动根据http包mime信息返回responseXML或者responseText,并作为回调函数参数传递,可用类型如下:

xml返回XML文档,可用JQuery处理;

json返回JSON数据;

script返回纯文本JavaScript代码,不会自动缓存结果,除非设置了cache参数;

html返回纯HTML信息,包含的script会在插入DOM时执行;

text返回纯文本符号

 

data:

要求为Object或者String类型的参数,发送到服务器,如果不是则自动转换成字符串格式。

 

 

示例:

前端AJAX请求:

function testAjax(){
var urls = "${pageContext.servletContext.contextPath}/th/student5";
var params = JSON.stringify( [ { name : "zhangWen", age : "16", id : 4 },
{ name : "zhangWe2", age : "23", id : 5 } ] );

$.ajax({
type : 'POST',
url:urls,
data: params,
dataType:"json",
cache : false,
contentType : "application/json; charset=utf-8",
error : function(text,errorThrown){
alert("错误请求信息: " + text);
},
success : function(data,text){
alert("请求成功==》姓名 " +data.name+ " ; "+data.age+" ; "+data.id);
}
});
}

 

后端代码:

实体类Student

public class Student
{
private Integer age;
private String name;
private Integer id;

}

@RequestMapping(value = "/student5", method = { RequestMethod.POST }, produces = "application/json;charset=utf-8")
@ResponseBody
public Student jsonDataReq(@RequestBody Student[] stu)
{
Student st = new Student();
for (Student item : stu)
{
st.setName(item.getName());
st.setId(item.getId());
st.setAge(item.getAge());

String jsonObj = JSON.toJSONString(item);
System.out.println(jsonObj);
}
// 将数据返回前端
return st;
}

 

posted @ 2018-11-29 15:39  Vtianhu  阅读(563)  评论(3编辑  收藏  举报