springboot+thymeleaf+Mybatisplus+mysql实现获取系统当前登录用户的购物车信息并显示到对应的表格中
时间: 2024-02-01 18:02:40 浏览: 178
springboot+layui+mybatis商城后台管理系统(带数据库完整可用)
5星 · 资源好评率100%
首先,我们需要实现用户登录和购物车功能。用户登录可以使用Spring Security框架,购物车可以使用Session来存储用户的购物车信息。
接下来,我们可以使用Mybatisplus来实现数据库操作,使用Thymeleaf来渲染页面。
1. 配置pom.xml文件,添加Spring Security、Mybatisplus和Thymeleaf依赖。
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.7.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
```
2. 配置Spring Security,实现用户登录功能。
在Spring Boot的启动类中添加以下代码:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
这段代码实现了基本的用户认证和授权功能,需要实现UserDetailsService接口来获取用户信息,使用BCryptPasswordEncoder来加密密码。
3. 实现购物车功能,存储在Session中。
创建一个Cart类来表示购物车,包含商品的id和数量。
```java
public class CartItem {
private Long productId;
private Integer quantity;
// getters and setters
}
public class Cart {
private Map<Long, CartItem> items = new HashMap<>();
public void addItem(Long productId, Integer quantity) {
CartItem item = items.get(productId);
if (item == null) {
item = new CartItem();
item.setProductId(productId);
item.setQuantity(quantity);
items.put(productId, item);
} else {
item.setQuantity(item.getQuantity() + quantity);
}
}
public void removeItem(Long productId) {
items.remove(productId);
}
public Map<Long, CartItem> getItems() {
return items;
}
public void setItems(Map<Long, CartItem> items) {
this.items = items;
}
public BigDecimal getTotalPrice() {
BigDecimal totalPrice = BigDecimal.ZERO;
for (CartItem item : items.values()) {
BigDecimal price = getProductById(item.getProductId()).getPrice();
totalPrice = totalPrice.add(price.multiply(new BigDecimal(item.getQuantity())));
}
return totalPrice;
}
private Product getProductById(Long productId) {
// TODO: query product from database
return null;
}
}
```
在Controller中使用Session来存储购物车信息。
```java
@Controller
public class CartController {
@GetMapping("/cart")
public String getCart(Model model, HttpSession session) {
Cart cart = (Cart) session.getAttribute("cart");
if (cart == null) {
cart = new Cart();
session.setAttribute("cart", cart);
}
model.addAttribute("cart", cart);
return "cart";
}
@PostMapping("/cart/addItem")
public String addItem(@RequestParam Long productId, @RequestParam Integer quantity, HttpSession session) {
Cart cart = (Cart) session.getAttribute("cart");
if (cart == null) {
cart = new Cart();
session.setAttribute("cart", cart);
}
cart.addItem(productId, quantity);
return "redirect:/cart";
}
@PostMapping("/cart/removeItem")
public String removeItem(@RequestParam Long productId, HttpSession session) {
Cart cart = (Cart) session.getAttribute("cart");
if (cart != null) {
cart.removeItem(productId);
}
return "redirect:/cart";
}
}
```
4. 使用Thymeleaf来渲染页面。
在cart.html文件中使用Thymeleaf来显示购物车信息。
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Cart</title>
</head>
<body>
<h1>Cart</h1>
<table>
<thead>
<tr>
<th>Product Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Price</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr th:each="item : ${cart.items}">
<td th:text="${item.value.product.name}"></td>
<td th:text="${item.value.quantity}"></td>
<td th:text="${item.value.product.price}"></td>
<td th:text="${item.value.product.price * item.value.quantity}"></td>
<td>
<form th:action="@{/cart/removeItem}" method="post">
<input type="hidden" name="productId" th:value="${item.value.product.id}">
<button type="submit">Remove</button>
</form>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total Price:</td>
<td></td>
<td></td>
<td th:text="${cart.totalPrice}"></td>
<td></td>
</tr>
</tfoot>
</table>
<form th:action="@{/cart/addItem}" method="post">
<label for="productId">Product:</label>
<select name="productId" id="productId">
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
</select>
<label for="quantity">Quantity:</label>
<input type="number" name="quantity" id="quantity" value="1">
<button type="submit">Add to Cart</button>
</form>
</body>
</html>
```
这样就完成了获取系统当前登录用户的购物车信息并显示到对应的表格中的功能。
阅读全文