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

--------------------------------------------返回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>


















版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/blogs-chao/p/4764895.html