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

Spring MVC注解之@ResponseBody

2016-11-14 14:45 316 查看
今天做了一个文件上传的试验,后端代码是这样的
@RequestMapping("/file/up")
@ResponseBody
public String fileLoad(@RequestParam("file") MultipartFile file) {
String tempPath =  System.getProperty("user.dir")+"\\"+"temp"+"\\";
File newFile = new File(tempPath+file.getOriginalFilename());
if (!file.isEmpty()) {
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(newFile));
out.write(file.getBytes());
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
return "上传失败" + e.getMessage();
}
return "上传成功";
} else {
return "文件为空,上传失败";
}
}

刚刚开始的时候我没有加@ResponseBody这个注解,文件是能上传到项目中指定的文件夹,但是前台会报错,报错的内容:

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Nov 14 14:45:52 CST 2016
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'POST' not supported


显示POST方法不支持,找了半天错误,发现加上@ResponseBody之后错误消失,所以去看了Spring MVC官方的文档中关于@ResponseBody注解的解释

Mapping the response body with the @ResponseBody annotation

The @ResponseBody annotation is similar to @RequestBody. This annotation can be put on a method

and indicates that the return type should be written straight to the HTTP response body (and not placed

in a Model, or interpreted as a view name). For example:

@RequestMapping(value = "/something", method = RequestMethod.PUT)

@ResponseBody

public String helloWorld() {

return "Hello World";

}

The above example will result in the text Hello World being written to the HTTP response stream.

As with @RequestBody, Spring converts the returned object to a response body by using an

HttpMessageConverter. For more information on these converters, see the previous section and

Message Converters.


说明@ResponseBody注解的作用是一个消息的转换器,后端方法返回的数据要给到前端显示必须要先转换为HTTP协议的返回格式,使用@ResponseBody注解就可以减少自己去写这个转换的方法了,简而言之,注解起到了一个@ResponseBody消息转换器的作用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: