【Spring MVC篇】返回响应
在Spring MVC中,你可以通过控制器方法返回不同类型的响应。以下是一些示例:
- 返回字符串作为视图名称:
@Controller
public class MyController {
@RequestMapping("/home")
public String home() {
return "homePage";
}
}
- 返回ModelAndView对象:
@Controller
public class MyController {
@RequestMapping("/about")
public ModelAndView about() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("aboutPage");
modelAndView.addObject("message", "About Us");
return modelAndView;
}
}
- 返回ResponseEntity进行更细粒度的控制:
@Controller
public class MyController {
@RequestMapping("/download")
public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
File file = new File(request.getRealPath("/") + "/static/image.jpg");
byte[] fileContent = Files.readAllBytes(file.toPath());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
headers.setContentDispositionFormData("attachment", "image.jpg");
return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
}
}
- 返回ResponseEntity进行重定向:
@Controller
public class MyController {
@RequestMapping("/redirect")
public ResponseEntity<String> redirect() {
return ResponseEntity.status(HttpStatus.FOUND)
.location(URI.create("/new-path"))
.build();
}
}
- 返回数据作为JSON:
@RestController
public class MyRestController {
@RequestMapping("/data")
public MyDataObject data() {
return new MyDataObject();
}
}
class MyDataObject {
// ...
}
这些是Spring MVC中返回响应的一些常见方式。根据你的具体需求,你可以选择最合适的方法来返回响应。
评论已关闭