首页 > 解决方案 > 如何将 MessageResponse 类型转换为 ResponseEntity返回类型

问题描述

我有一个具有以下方法的服务类

NewCartService.java:

@Service
public class NewCartService {

    @Autowired
    private LoginRepository loginRepository;
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private CartRepository cartRepository;
    @Autowired
    private CartDao cartDao;
    @Autowired
    private Mailer mailService;

    public MessageResponse order(List<Cart> cart) throws MessagingException {

        for (Cart cart1 : cart) {
            String userName = cart1.getUserName();
            String password = cart1.getPassword();
            String productName = cart1.getProductName();
            String price = cart1.getPrice();
            String discription = cart1.getDiscription();

            if (!cartRepository.existsAllByUserNameAndPasswordAndProductNameAndPriceAndDiscription(userName, password, productName, price, discription)) {
                throw new ResourceNotFoundException("not found");
            }
            MustacheFactory mf = new DefaultMustacheFactory();
            Mustache m = mf.compile("cart.mustache");

            StringWriter writer = new StringWriter();
            String messageText = "";

            List<Cart> carts = cartDao.getCart(cart);

            Map<String, Object> params = new HashMap<>();
            params.put("carts", carts);
            Writer m1 = m.execute(writer, params);
            System.out.println(m1);
            messageText = m1.toString();

            mailService.sendMail("/*email address*/", "/*email address*/", messageText, "demo", true);
            cartRepository.deleteByUserNameAndPasswordAndProductNameAndPriceAndDiscription(userName, password, productName, price, discription);

            return new MessageResponse("product Successfully ordered from cart");
        }
        throw new BadArgumentsException("bad arguments");
    }

}

我有控制器

CartController.java:

@RestController
public class CartController {

    @Autowired
    public CartService cartService;

    @GetMapping("/orders")
    public ResponseEntity<?> orders(@Valid @RequestBody List<Cart> carts) throws MessagingException {
        return newCartService.order(carts);// it gives error because i need to convert MessageResponse into the ResponseEntity<?>
    }
}

现在我的问题是如何将这些 MessageResponse 转换为 ResponseEntity<?> ?

请建议我的代码,以便我可以解决这些问题并提前致谢。

标签: javaspring-boot

解决方案


你有没有尝试过:

return new ResponseEntity<>(newCartService.order(carts), HttpStatus.OK);

或按照评论中的建议:

return ResponseEntity.ok(newCartService.order(carts));

推荐阅读