返回json格式数据
1. 新加入jar包
去官网下载
2. 编写目标方法,使其返回json对应的对象或集合
3. 在方法上加入@ResponseBody
@ResponseBody
@RequestMapping("/testJson")
public Collection testJson(){
return deptDao.getAll();
}
HttpMessageConverter
HttpMessageConverter的原理
@ResponseBody,@RequestBody的使用
Paste_Image.png <form action="testHttpMessageConverter" method="post" enctype="multipart/form-data">
File:<input type="file" name="file"/><br>
Desc:<input type="text" name="desc"/><br>
<input type="submit" value="Submit"/>
</form>
@ResponseBody
@RequestMapping("/testHttpMessageConverter")
public String testHttpMessageConverter(@RequestBody String body){
/* 参数类型为String
* 那么springmvc会使用StringHttpMessageConverter
* 把传入的参数的信息转换为String类型*/
System.out.println("参数为:"+body);
return "hello"+new Date();
/* 返回类型为String
* 那么springmvc会使用StringHttpMessageConverter
* 把返回的信息转换为String类型*/
}
后台打印:
参数为:------WebKitFormBoundaryyBSL9T1T2Yqc5tDY
Content-Disposition: form-data; name="file"; filename="dd.txt"
Content-Type: text/plain
I love china
------WebKitFormBoundaryyBSL9T1T2Yqc5tDY
Content-Disposition: form-data; name="desc"
abcd
------WebKitFormBoundaryyBSL9T1T2Yqc5tDY--
response.gif
@ResponseEntity的使用(文件下载)
<a href="testResponseEntity">testResponseEntity</a>
@RequestMapping("/testResponseEntity")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session){
byte[] body = null;
ServletContext servletContext = session.getServletContext();
InputStream in = servletContext.getResourceAsStream("WEB-INF/files/dd.txt");
try {
body = new byte[in.available()];
in.read(body);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpHeaders httpHeader = new HttpHeaders();
httpHeader.add("Content-Disposition", "attachment;filename=dd.txt");
HttpStatus httpStatus = HttpStatus.OK;
ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(body,httpHeader,httpStatus);
return responseEntity;
}
}
网友评论