java - 如何将 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<?> ?
请建议我的代码,以便我可以解决这些问题并提前致谢。
解决方案
你有没有尝试过:
return new ResponseEntity<>(newCartService.order(carts), HttpStatus.OK);
或按照评论中的建议:
return ResponseEntity.ok(newCartService.order(carts));
推荐阅读
- javascript - 如何允许实现 css 上的自动完成以显示对该字段中键入的任何关键字的建议?
- html - Navbar - 将元素定位在中心并修复导航栏
- python - 没有时间戳模块名称的 Python absl 日志记录
- google-api - 用于 Google 集合的 API(不是 Java 集合,而是 www.google.com/save)
- c++ - 有一个构造函数,但有两个析构函数
- raku - 如何将参数传递给变量引用的令牌?
- recursion - 尾递归函数的用户友好包装
- angular - 在新窗口中打开的延迟加载模块中使用 NgRX 根状态
- python - 将数据框列转换为数据框标题
- c# - 使用 JSON.NET 解析 JSON 的最简洁方法,无需