无返回值void
对于处理器 方法 返回 void 的应用场景, AJAX 响应若处理器对请求处理后,无需跳转到其它任何资源,此时可以让处理器方法返回 void 。例如,对于 AJAX 的异步请求的响应。
json介绍:
JSON JavaScript Object Notation )(官网 http://www.json.org/ org/)是 一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。JSON 采用完全独立于语言的文本格式,这些特性使 JSON 成为理想的数据交换语言。
JSON 的两种结构
"名称/值"对的集合。例如{ name:"张三", age : 23 }
值的有序列表,它被理解为数组。例如::[{ naem: "张三" , age : 23 } , { name: "李力" , age :28 }]
在 JSON Lib 中 名称 值 对的集合用 JSONObject 对象表示,数组用 JSONArray 对象表示
常用的的 json 库:json lib , Jackson , google 公司的 gson 和 阿里巴巴的 fastjson
这里使用Jackson
在pom文件中添加坐标
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.0</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.9.0</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.9.0</version></dependency>
页面发送ajax,需要借助Query,所以工程中引入jQuery库

index2.jsp
<script>$(function () {$("button").click(function () {$.ajax({url:"test01/test_void_ajax.do",data :{name:"langlihuge",age : 12},type : "post",dataType:"json",success :function (request) {alert(request + " " + request.name + " " + request.age);}})})})</script><body><button>发起ajax</button></body>
controller
@RequestMapping(value = "test_void_ajax")public void test_void_ajax(String name, Integer age, HttpServletResponse response) throws Exception {//接收参数,调用业务层方法,将结果返回Student student = new Student();student.setName(name);student.setAge(age);//把student转换为json,使用Jackson工具库ObjectMapper objectMapper = new ObjectMapper();//通过应答对象输出给浏览器OutputStream out = response.getOutputStream();objectMapper.writeValue(out,student);}
测试:

如果把 dataType:"json",去掉

如果需要转发和重定向需要使用request和response.原生的servlet中的方式一样
喜欢,转发
明天见

SpringMVC 10 处理器方法的返回值(ModelAndView和String))
SpringMVC 07 @RequestMapping说明
文章转载自敲代码的人,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




