帮我改写以下代码,不要用servlet.代码为:@Controller public class CartController { @Autowired private UserService userService; @Autowired private CommodityService commodityService; @Autowired private CartService cartService; @GetMapping("/cart") public String cart(Model model, HttpServletRequest request) { HttpSession session = request.getSession(); User user = (User)session.getAttribute("user"); if (user == null) { return "redirect:/login"; } List<Cart> cartList = cartService.findByUid(user.getUid()); model.addAttribute("cartList", cartList); return "cart"; } @PostMapping("/cart/add") public String addCart(Integer cid, Integer cnum, HttpServletRequest request) { HttpSession session = request.getSession(); User user = (User)session.getAttribute("user"); if (user == null) { return "redirect:/login"; } Commodity commodity = commodityService.findById(cid); if (commodity == null) { return "redirect:/commodity"; } Cart cart = new Cart(); cart.setUid(user.getUid()); cart.setCid(cid); cart.setCnum(cnum); cartService.save(cart); return "redirect:/cart"; } @PostMapping("/cart/delete") public String deleteCart(Integer cartid) { cartService.deleteById(cartid); return "redirect:/cart"; }
时间: 2024-02-14 15:12:45 浏览: 68
详解Spring关于@Resource注入为null解决办法
以下是改写后的代码,使用了Spring Boot的@RestController注解和@ResponseBody注解来实现API风格的接口:
@RestController
public class CartController {
@Autowired
private UserService userService;
@Autowired
private CommodityService commodityService;
@Autowired
private CartService cartService;
@GetMapping("/cart")
public List<Cart> getCart(HttpServletRequest request) {
HttpSession session = request.getSession();
User user = (User)session.getAttribute("user");
if (user == null) {
return null;
}
List<Cart> cartList = cartService.findByUid(user.getUid());
return cartList;
}
@PostMapping("/cart/add")
public String addCart(Integer cid, Integer cnum, HttpServletRequest request) {
HttpSession session = request.getSession();
User user = (User)session.getAttribute("user");
if (user == null) {
return "redirect:/login";
}
Commodity commodity = commodityService.findById(cid);
if (commodity == null) {
return "redirect:/commodity";
}
Cart cart = new Cart();
cart.setUid(user.getUid());
cart.setCid(cid);
cart.setCnum(cnum);
cartService.save(cart);
return "success";
}
@PostMapping("/cart/delete")
public String deleteCart(Integer cartid) {
cartService.deleteById(cartid);
return "success";
}
}
这里将原来的@Controller注解改为@RestController注解,表示这是一个API控制器,不需要返回视图,而是直接返回数据。同时,将原来的Model和视图名称改为了List<Cart>,表示返回一个购物车列表。为了让返回的数据能够被前端页面接收到,我们使用@ResponseBody注解将返回值转为JSON格式。最后,将原来的重定向操作改为返回字符串"success",表示操作成功。
阅读全文