您的位置:首页 > 编程语言 > Java开发

SpringMVC——返回JSON数据&&文件上传下载

2015-07-16 13:07 573 查看
--------------------------------------------返回JSON数据------------------------------------------------------------------
@Controller
public class PersonHandler {

@ResponseBody
@RequestMapping("/getPerson")
public List<Person> getPersons() {
List<Person> list = new ArrayList<Person>();
list.add(new Person(1, "a", "aa", 1, new Date()));
list.add(new Person(2, "b", "ba", 2, new Date()));
list.add(new Person(3, "c", "ca", 3, new Date()));
list.add(new Person(4, "d", "da", 4, new Date()));
list.add(new Person(5, "e", "ea", 5, new Date()));

return list;
}
}
----------------------------------------------------------文件上传下载--------------------------------------------------



/**
* 文件下载
*/
@RequestMapping("testResponseEntity")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {

byte[] body = null;
ServletContext servletContext = session.getServletContext();
InputStream in = servletContext.getResourceAsStream("/file/test.txt");
body = new byte[in.available()];
in.read(body);

HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disponsition", "attachment;filename=chao.txt");

HttpStatus statusCode = HttpStatus.OK;

ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
return response;
}

/**
* 文件上传
*/
@ResponseBody
@RequestMapping("/testHttpMessageConverter")
public String testHttpMessageConverter(@RequestBody String body) {
System.out.println(body);
return "***********************" + new Date();
}

---------------------------------------------------------index.jsp---------------------------------------------------------------------------

<body>
<a href="getPerson">getPerson</a>
<a href="testResponseEntity">test ResponseEntity</a>
<br><br>
<form action="testHttpMessageConverter" method="post" enctype="multipart/form-data">

file:<input type="file" name="file"/>
Desc:<input type="text" name="desc"/>
<input type="submit" value="submit"/>
</form>
</body>



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: