如何返回 org.springframework.http.ResponseEntity 包含数据和文件



我有带有getUser方法的Restful spring控制器,我希望此方法返回用户数据:姓名,年龄,城市等和用户图像。

如何在一个响应中返回 java 对象和文件?

    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity getUser(@RequestBody UserRequest req) 
    {
        User user=userProfileService.getUserProfileByEmail(req.getEmail());
        Resource resourceImg1 = new ServletContextResource(servletContext, "D:/images/userImg1.jpg");
        Resource resourceImg2 = new ServletContextResource(servletContext, "D:/images/userImg2.jpg");
        List<Resource> resourcesList = new ArrayList<Resource>();
        resourcesList.add(resourceImg1);
        resourcesList.add(resourceImg2);
        return new ResponseEntity(user, resourcesList, new HttpHeaders(), HttpStatus.OK);
    }

我想返回图像和用户

响应正文必须是单个对象。最好的办法是创建一个对象,例如

public class UserWithResources() {
    private User user;
    private List<Resources> resources;
    ...etc
}

然后在响应中返回用户与资源

您可以使用 map 来包装数据,

    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity getUser(@RequestBody UserRequest req) 
    {
        User user=userProfileService.getUserProfileByEmail(req.getEmail());
        Resource resourceImg1 = new ServletContextResource(servletContext, "D:/images/userImg1.jpg");
        Resource resourceImg2 = new ServletContextResource(servletContext, "D:/images/userImg2.jpg");
        List<Resource> resourcesList = new ArrayList<Resource>();
        resourcesList.add(resourceImg1);
        resourcesList.add(resourceImg2);
        Map<String,Object> dataMap=new HashMap<String,Object>();
        dataMap.put("user",user);
        dataMap.put("resourcesList",resourcesList);
        return new ResponseEntity(dataMap,new HttpHeaders(), HttpStatus.OK);
    }

相关内容

  • 没有找到相关文章

最新更新