demo
配置:
<!-- 在这个demo中缺少此配置提交表单后会出现415的错误 --> <mvc:annotation-driven /> <!-- 配置json --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> </list> </property> </bean> <!-- 配置响应类型 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> </list> </property> </bean>
获取提交的内容:
页面:
<form action="home/request" method="POST" enctype="multipart/form-data"> File: <input type="file" name="file"/> <br/> Desc: <input type="text" name="name" value="aabbcc"/> <br/> <input type="submit" value="获取request的信息"/> </form>
控制器:
/** * 获取request的信息 */ @ResponseBody @RequestMapping("/request") public String request(@RequestBody String body){ System.out.println("请求的内容\n" + body); return body; }
响应:
读取文件并响应到浏览器:
控制器:
/** * 读取文件并响应到浏览器(下载) */ @RequestMapping("/responseEntity") public ResponseEntity<byte[]> responseEntity(HttpSession session) throws IOException{ byte [] body = null; ServletContext servletContext = session.getServletContext(); InputStream in = servletContext.getResourceAsStream("/tmp/tmp.txt"); body = new byte[in.available()]; in.read(body); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment;filename=abc.txt"); HttpStatus statusCode = HttpStatus.OK; ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode); return response; }
响应: