ITPub博客

首页 > 应用开发 > Java > Java Web网上商城系统设计与实现:全栈开发实战

Java Web网上商城系统设计与实现:全栈开发实战

Java 作者:bhluo 时间:2025-11-19 15:39:43 0 删除 编辑

# Java Web网上商城系统设计与实现:全栈开发实战


电子商务平台的开发涉及复杂的技术架构和业务逻辑,基于Java Web的网上购物商城系统以其稳定性、安全性和可扩展性成为企业级应用的首选。本文将详细探讨一个完整的网上购物商城系统的设计与实现。


## 系统架构设计


### 技术栈选型


**后端技术栈:**

- Spring Boot 2.7.x

- Spring MVC

- Spring Data JPA

- Spring Security

- MySQL 8.0

- Redis

- Maven


**前端技术栈:**

- Thymeleaf模板引擎

- Bootstrap 5.x

- jQuery

- HTML5/CSS3


### 系统架构图


```

表现层:用户界面 (Thymeleaf + Bootstrap)

    ↓

控制层:Spring MVC控制器

    ↓

业务层:Service业务逻辑

    ↓

数据层:Repository数据访问

    ↓

数据库:MySQL + Redis缓存

```


## 数据库设计


### 核心表结构


```sql

-- 用户表

CREATE TABLE users (

    id BIGINT AUTO_INCREMENT PRIMARY KEY,

    username VARCHAR(50) UNIQUE NOT NULL,

    email VARCHAR(100) UNIQUE NOT NULL,

    password VARCHAR(100) NOT NULL,

    phone VARCHAR(20),

    avatar VARCHAR(200),

<"nzmu.nbazhib.com">

<"ytmc.nbazhib.com">

<"ucao.nbazhib.com">

    user_type ENUM('CUSTOMER', 'ADMIN') DEFAULT 'CUSTOMER',

    status ENUM('ACTIVE', 'INACTIVE') DEFAULT 'ACTIVE',

    created_time DATETIME DEFAULT CURRENT_TIMESTAMP,

    updated_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

);


-- 商品分类表

CREATE TABLE categories (

    id BIGINT AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(100) NOT NULL,

    description TEXT,

    parent_id BIGINT,

    sort_order INT DEFAULT 0,

    status ENUM('ACTIVE', 'INACTIVE') DEFAULT 'ACTIVE',

    created_time DATETIME DEFAULT CURRENT_TIMESTAMP,

    FOREIGN KEY (parent_id) REFERENCES categories(id)

);


-- 商品表

CREATE TABLE products (

    id BIGINT AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(200) NOT NULL,

    description TEXT,

    category_id BIGINT NOT NULL,

    price DECIMAL(10,2) NOT NULL,

    stock_quantity INT DEFAULT 0,

    image_url VARCHAR(200),

    status ENUM('ON_SALE', 'OFF_SALE', 'DELETED') DEFAULT 'ON_SALE',

    created_time DATETIME DEFAULT CURRENT_TIMESTAMP,

    updated_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

    FOREIGN KEY (category_id) REFERENCES categories(id)

);


-- 购物车表

CREATE TABLE cart_items (

    id BIGINT AUTO_INCREMENT PRIMARY KEY,

    user_id BIGINT NOT NULL,

    product_id BIGINT NOT NULL,

    quantity INT NOT NULL,

    selected BOOLEAN DEFAULT TRUE,

    created_time DATETIME DEFAULT CURRENT_TIMESTAMP,

    updated_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

    FOREIGN KEY (user_id) REFERENCES users(id),

    FOREIGN KEY (product_id) REFERENCES products(id),

    UNIQUE KEY uk_user_product (user_id, product_id)

<"gobg.nbazhib.com">

<"twmv.nbazhib.com">

<"kyon.nbazhib.com">

);


-- 订单表

CREATE TABLE orders (

    id BIGINT AUTO_INCREMENT PRIMARY KEY,

    order_no VARCHAR(50) UNIQUE NOT NULL,

    user_id BIGINT NOT NULL,

    total_amount DECIMAL(10,2) NOT NULL,

    payment_amount DECIMAL(10,2) NOT NULL,

    payment_method ENUM('ALIPAY', 'WECHAT', 'BANK') DEFAULT 'ALIPAY',

    payment_status ENUM('PENDING', 'PAID', 'FAILED') DEFAULT 'PENDING',

    order_status ENUM('PENDING', 'PROCESSING', 'SHIPPED', 'DELIVERED', 'CANCELLED') DEFAULT 'PENDING',

    shipping_address TEXT,

    receiver_name VARCHAR(100),

    receiver_phone VARCHAR(20),

    created_time DATETIME DEFAULT CURRENT_TIMESTAMP,

    updated_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

    FOREIGN KEY (user_id) REFERENCES users(id)

);


-- 订单项表

CREATE TABLE order_items (

    id BIGINT AUTO_INCREMENT PRIMARY KEY,

    order_id BIGINT NOT NULL,

    product_id BIGINT NOT NULL,

    product_name VARCHAR(200) NOT NULL,

    product_image VARCHAR(200),

    product_price DECIMAL(10,2) NOT NULL,

    quantity INT NOT NULL,

    total_price DECIMAL(10,2) NOT NULL,

    created_time DATETIME DEFAULT CURRENT_TIMESTAMP,

    FOREIGN KEY (order_id) REFERENCES orders(id),

    FOREIGN KEY (product_id) REFERENCES products(id)

);

```


## 核心功能实现


### 1. 用户管理模块


```java

@Entity

@Table(name = "users")

@Data

<"nopc.nbazhib.com">

<"otai.nbazhib.com">

<"ixse.nbazhib.com">

public class User {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;

    

    @Column(unique = true, nullable = false)

    private String username;

    

    @Column(unique = true, nullable = false)

    private String email;

    

    @JsonIgnore

    private String password;

    

    private String phone;

    private String avatar;

    

    @Enumerated(EnumType.STRING)

    @Column(name = "user_type")

    private UserType userType = UserType.CUSTOMER;

    

    @Enumerated(EnumType.STRING)

    private UserStatus status = UserStatus.ACTIVE;

    

    @CreationTimestamp

    private LocalDateTime createdTime;

    

    @UpdateTimestamp

    private LocalDateTime updatedTime;

    

    public enum UserType {

        CUSTOMER, ADMIN

    }

    

    public enum UserStatus {

        ACTIVE, INACTIVE

    }

}


@Service

@Transactional

<"tfjo.nbazhib.com">

<"jrsw.nbazhib.com">

<"zaxv.nbazhib.com">

public class UserService {

    

    @Autowired

    private UserRepository userRepository;

    

    @Autowired

    private PasswordEncoder passwordEncoder;

    

    public User register(UserRegistrationDto registrationDto) {

        // 检查用户名和邮箱是否已存在

        if (userRepository.existsByUsername(registrationDto.getUsername())) {

            throw new BusinessException("用户名已存在");

        }

        if (userRepository.existsByEmail(registrationDto.getEmail())) {

            throw new BusinessException("邮箱已被注册");

        }

        

        // 创建新用户

        User user = new User();

        user.setUsername(registrationDto.getUsername());

        user.setEmail(registrationDto.getEmail());

        user.setPassword(passwordEncoder.encode(registrationDto.getPassword()));

        user.setPhone(registrationDto.getPhone());

        user.setUserType(User.UserType.CUSTOMER);

        user.setStatus(User.UserStatus.ACTIVE);

        

        return userRepository.save(user);

    }

    

    public User login(String username, String password) {

        User user = userRepository.findByUsername(username)

            .orElseThrow(() -> new BusinessException("用户不存在"));

        

        if (!passwordEncoder.matches(password, user.getPassword())) {

            throw new BusinessException("密码错误");

        }

        

        if (user.getStatus() != User.UserStatus.ACTIVE) {

            throw new BusinessException("账户已被禁用");

        }

        

        return user;

    }

    

    public void updateProfile(Long userId, UserProfileDto profileDto) {

        User user = getUserById(userId);

        user.setPhone(profileDto.getPhone());

        user.setAvatar(profileDto.getAvatar());

        userRepository.save(user);

    }

    

    public User getUserById(Long userId) {

        return userRepository.findById(userId)

            .orElseThrow(() -> new BusinessException("用户不存在"));

    }

}

```


### 2. 商品管理模块


```java

@Entity

@Table(name = "products")

@Data

<"mkam.nbazhib.com">

<"asbw.nbazhib.com">

<"urun.nbazhib.com">

public class Product {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;

    

    @Column(nullable = false)

    private String name;

    

    @Column(columnDefinition = "TEXT")

    private String description;

    

    @ManyToOne

    @JoinColumn(name = "category_id", nullable = false)

    private Category category;

    

    @Column(nullable = false)

    private BigDecimal price;

    

    @Column(name = "stock_quantity")

    private Integer stockQuantity = 0;

    

    @Column(name = "image_url")

    private String imageUrl;

    

    @Enumerated(EnumType.STRING)

    private ProductStatus status = ProductStatus.ON_SALE;

    

    @CreationTimestamp

    private LocalDateTime createdTime;

    

    @UpdateTimestamp

    private LocalDateTime updatedTime;

    

    public enum ProductStatus {

        ON_SALE, OFF_SALE, DELETED

    }

}


@Service

@Transactional

public class ProductService {

    

    @Autowired

    private ProductRepository productRepository;

    

    @Autowired

    private CategoryRepository categoryRepository;

    

    @Cacheable(value = "products", key = "#id")

    public Product getProductById(Long id) {

        return productRepository.findById(id)

            .orElseThrow(() -> new BusinessException("商品不存在"));

    }

    

    public Page<Product> getProductsByCategory(Long categoryId, Pageable pageable) {

        Category category = categoryRepository.findById(categoryId)

            .orElseThrow(() -> new BusinessException("分类不存在"));

        

        return productRepository.findByCategoryAndStatus(

            category, Product.ProductStatus.ON_SALE, pageable);

    }

    

    public Page<Product> searchProducts(String keyword, Pageable pageable) {

        return productRepository.findByNameContainingAndStatus(

            keyword, Product.ProductStatus.ON_SALE, pageable);

    }

    

    @CacheEvict(value = "products", key = "#product.id")

<"ungl.nbazhib.com">

<"hujx.nbazhib.com">

<"jywm.nbazhib.com">

    public Product updateProduct(Product product) {

        return productRepository.save(product);

    }

    

    public void reduceStock(Long productId, Integer quantity) {

        Product product = getProductById(productId);

        

        if (product.getStockQuantity() < quantity) {

            throw new BusinessException("库存不足");

        }

        

        product.setStockQuantity(product.getStockQuantity() - quantity);

        productRepository.save(product);

    }

    

    public void increaseStock(Long productId, Integer quantity) {

        Product product = getProductById(productId);

        product.setStockQuantity(product.getStockQuantity() + quantity);

        productRepository.save(product);

    }

}

```


### 3. 购物车模块


```java

@Entity

@Table(name = "cart_items")

@Data

public class CartItem {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;

    

    @ManyToOne

    @JoinColumn(name = "user_id", nullable = false)

    private User user;

    

    @ManyToOne

    @JoinColumn(name = "product_id", nullable = false)

    private Product product;

    

    @Column(nullable = false)

    private Integer quantity = 1;

    

    private Boolean selected = true;

    

    @CreationTimestamp

    private LocalDateTime createdTime;

    

    @UpdateTimestamp

    private LocalDateTime updatedTime;

    

    // 计算单项总价

    public BigDecimal getTotalPrice() {

        return product.getPrice().multiply(BigDecimal.valueOf(quantity));

    }

}


@Service

@Transactional

public class CartService {

<"zppn.nbazhib.com">

<"zckr.nbazhib.com">

<"moil.nbazhib.com">

    

    @Autowired

    private CartItemRepository cartItemRepository;

    

    @Autowired

    private ProductService productService;

    

    public CartItem addToCart(Long userId, Long productId, Integer quantity) {

        // 检查商品是否存在且有足够库存

        Product product = productService.getProductById(productId);

        if (product.getStockQuantity() < quantity) {

            throw new BusinessException("商品库存不足");

        }

        

        // 检查是否已在购物车中

        Optional<CartItem> existingItem = cartItemRepository.findByUserIdAndProductId(userId, productId);

        

        if (existingItem.isPresent()) {

            // 更新数量

            CartItem cartItem = existingItem.get();

            cartItem.setQuantity(cartItem.getQuantity() + quantity);

            return cartItemRepository.save(cartItem);

        } else {

            // 新增购物车项

            CartItem cartItem = new CartItem();

            cartItem.setUser(new User(userId));

            cartItem.setProduct(product);

            cartItem.setQuantity(quantity);

            return cartItemRepository.save(cartItem);

        }

    }

    

    public List<CartItem> getCartItems(Long userId) {

        return cartItemRepository.findByUserId(userId);

    }

    

    public CartSummary getCartSummary(Long userId) {

        List<CartItem> cartItems = getCartItems(userId);

        

        CartSummary summary = new CartSummary();

        summary.setTotalItems(cartItems.size());

        

        BigDecimal totalAmount = cartItems.stream()

            .filter(CartItem::getSelected)

            .map(CartItem::getTotalPrice)

            .reduce(BigDecimal.ZERO, BigDecimal::add);

        

        summary.setTotalAmount(totalAmount);

        summary.setSelectedCount((int) cartItems.stream()

            .filter(CartItem::getSelected).count());

        

        return summary;

    }

    

    public void updateQuantity(Long cartItemId, Integer quantity) {

        CartItem cartItem = cartItemRepository.findById(cartItemId)

            .orElseThrow(() -> new BusinessException("购物车项不存在"));

        

        if (quantity <= 0) {

            cartItemRepository.delete(cartItem);

            return;

        }

        

        // 检查库存

        if (cartItem.getProduct().getStockQuantity() < quantity) {

            throw new BusinessException("库存不足");

        }

        

        cartItem.setQuantity(quantity);

        cartItemRepository.save(cartItem);

    }

    

    public void removeFromCart(Long cartItemId) {

        CartItem cartItem = cartItemRepository.findById(cartItemId)

            .orElseThrow(() -> new BusinessException("购物车项不存在"));

        cartItemRepository.delete(cartItem);

    }

    

    public void clearCart(Long userId) {

        cartItemRepository.deleteByUserId(userId);

    }

    

    @Data

    public static class CartSummary {

        private Integer totalItems;

        private Integer selectedCount;

        private BigDecimal totalAmount;

    }

}

```


### 4. 订单 管理模块


```java

@Entity

@Table(name = "orders")

@Data

<"muvo.nbazhib.com">

<"hrid.nbazhib.com">

<"xdgh.nbazhib.com">

public class Order {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;

    

    @Column(name = "order_no", unique = true, nullable = false)

    private String orderNo;

    

    @ManyToOne

    @JoinColumn(name = "user_id", nullable = false)

    private User user;

    

    @Column(name = "total_amount", nullable = false)

    private BigDecimal totalAmount;

    

    @Column(name = "payment_amount", nullable = false)

    private BigDecimal paymentAmount;

    

    @Enumerated(EnumType.STRING)

    @Column(name = "payment_method")

    private PaymentMethod paymentMethod = PaymentMethod.ALIPAY;

    

    @Enumerated(EnumType.STRING)

    @Column(name = "payment_status")

    private PaymentStatus paymentStatus = PaymentStatus.PENDING;

    

    @Enumerated(EnumType.STRING)

    @Column(name = "order_status")

    private OrderStatus orderStatus = OrderStatus.PENDING;

    

    @Column(name = "shipping_address", columnDefinition = "TEXT")

    private String shippingAddress;

    

    @Column(name = "receiver_name")

    private String receiverName;

    

    @Column(name = "receiver_phone")

    private String receiverPhone;

    

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, fetch = FetchType.LAZY)

    private List<OrderItem> orderItems = new ArrayList<>();

    

    @CreationTimestamp

    private LocalDateTime createdTime;

    

    @UpdateTimestamp

    private LocalDateTime updatedTime;

    

    public enum PaymentMethod {

        ALIPAY, WECHAT, BANK

    }

    

    public enum PaymentStatus {

        PENDING, PAID, FAILED

    }

    

    public enum OrderStatus {

        PENDING, PROCESSING, SHIPPED, DELIVERED, CANCELLED

    }

    

    // 生成订单号

    @PrePersist

    public void generateOrderNo() {

        if (this.orderNo == null) {

            this.orderNo = "ORD" + System.currentTimeMillis() + 

                          String.format("%04d", ThreadLocalRandom.current().nextInt(1000));

        }

    }

}


@Service

@Transactional

public class OrderService {

    

    @Autowired

    private OrderRepository orderRepository;

    

    @Autowired

    private OrderItemRepository orderItemRepository;

    

    @Autowired

    private CartService cartService;

    

    @Autowired

    private ProductService productService;

    

    public Order createOrder(Long userId, OrderCreateDto orderDto) {

        // 获取选中的购物车项

        List<CartItem> cartItems = cartService.getCartItems(userId).stream()

            .filter(CartItem::getSelected)

            .collect(Collectors.toList());

        

        if (cartItems.isEmpty()) {

            throw new BusinessException("请选择要购买的商品");

        }

        

        // 检查库存

        for (CartItem cartItem : cartItems) {

            if (cartItem.getProduct().getStockQuantity() < cartItem.getQuantity()) {

                throw new BusinessException(

                    String.format("商品【%s】库存不足", cartItem.getProduct().getName()));

            }

        }

        

        // 创建订单

        Order order = new Order();

        order.setUser(new User(userId));

        order.setShippingAddress(orderDto.getShippingAddress());

        order.setReceiverName(orderDto.getReceiverName());

        order.setReceiverPhone(orderDto.getReceiverPhone());

        order.setPaymentMethod(orderDto.getPaymentMethod());

        

        // 计算总金额

        BigDecimal totalAmount = cartItems.stream()

            .map(CartItem::getTotalPrice)

            .reduce(BigDecimal.ZERO, BigDecimal::add);

        

        order.setTotalAmount(totalAmount);

        order.setPaymentAmount(totalAmount); // 实际支付金额,可加入优惠计算

        

        // 保存订单

        Order savedOrder = orderRepository.save(order);

        

        // 创建订单项并扣减库存

        List<OrderItem> orderItems = new ArrayList<>();

        for (CartItem cartItem : cartItems) {

            OrderItem orderItem = new OrderItem();

            orderItem.setOrder(savedOrder);

            orderItem.setProduct(cartItem.getProduct());

            orderItem.setProductName(cartItem.getProduct().getName());

            orderItem.setProductImage(cartItem.getProduct().getImageUrl());

            orderItem.setProductPrice(cartItem.getProduct().getPrice());

            orderItem.setQuantity(cartItem.getQuantity());

            orderItem.setTotalPrice(cartItem.getTotalPrice());

            

            orderItems.add(orderItem);

            

            // 扣减库存

            productService.reduceStock(cartItem.getProduct().getId(), cartItem.getQuantity());

        }

        

        orderItemRepository.saveAll(orderItems);

        savedOrder.setOrderItems(orderItems);

        

        // 清空购物车中的已购买项

        cartService.clearCart(userId);

        

        return savedOrder;

    }

    

    public Page<Order> getUserOrders(Long userId, Pageable pageable) {

        return orderRepository.findByUserIdOrderByCreatedTimeDesc(userId, pageable);

    }

    

    public Order getOrderDetail(Long orderId, Long userId) {

        return orderRepository.findByIdAndUserId(orderId, userId)

            .orElseThrow(() -> new BusinessException("订单不存在"));

    }

    

    public void cancelOrder(Long orderId, Long userId) {

        Order order = getOrderDetail(orderId, userId);

        

        if (order.getOrderStatus() != Order.OrderStatus.PENDING) {

            throw new BusinessException("当前状态无法取消订单");

        }

        

        // 恢复库存

        for (OrderItem item : order.getOrderItems()) {

            productService.increaseStock(item.getProduct().getId(), item.getQuantity());

        }

        

        order.setOrderStatus(Order.OrderStatus.CANCELLED);

        orderRepository.save(order);

    }

    

    public void updateOrderStatus(Long orderId, Order.OrderStatus status) {

        Order order = orderRepository.findById(orderId)

            .orElseThrow(() -> new BusinessException("订单不存在"));

        order.setOrderStatus(status);

        orderRepository.save(order);

    }

}

```


### 5. 控制器层实现


```java

@Controller

@RequestMapping("/user")

@SessionAttributes("currentUser")

public class UserController {

<"vvco.nbazhib.com">

<"mavn.nbazhib.com">

<"jaub.nbazhib.com">

    

    @Autowired

    private UserService userService;

    

    @PostMapping("/register")

    public String register(@Valid UserRegistrationDto registrationDto, 

                          BindingResult result, 

                          Model model) {

        if (result.hasErrors()) {

            model.addAttribute("error", "请检查输入信息");

            return "register";

        }

        

        try {

            userService.register(registrationDto);

            model.addAttribute("success", "注册成功,请登录");

            return "login";

        } catch (BusinessException e) {

            model.addAttribute("error", e.getMessage());

            return "register";

        }

    }

    

    @PostMapping("/login")

    public String login(@RequestParam String username,

                       @RequestParam String password,

                       HttpSession session,

                       Model model) {

        try {

            User user = userService.login(username, password);

            session.setAttribute("currentUser", user);

            return "redirect:/";

        } catch (BusinessException e) {

            model.addAttribute("error", e.getMessage());

            return "login";

        }

    }

}


@RestController

@RequestMapping("/api/cart")

public class CartApiController {

    

    @Autowired

    private CartService cartService;

    

    @PostMapping("/add")

    public ResponseEntity<?> addToCart(@RequestParam Long productId,

                                      @RequestParam Integer quantity,

                                      @AuthenticationPrincipal User user) {

        try {

            CartItem cartItem = cartService.addToCart(user.getId(), productId, quantity);

            return ResponseEntity.ok(Map.of("success", true, "message", "添加成功"));

        } catch (BusinessException e) {

            return ResponseEntity.badRequest()

                .body(Map.of("success", false, "message", e.getMessage()));

        }

    }

    

    @GetMapping("/items")

    public ResponseEntity<List<CartItem>> getCartItems(@AuthenticationPrincipal User user) {

        List<CartItem> cartItems = cartService.getCartItems(user.getId());

        return ResponseEntity.ok(cartItems);

    }

    

    @GetMapping("/summary")

    public ResponseEntity<CartService.CartSummary> getCartSummary(@AuthenticationPrincipal User user) {

        CartService.CartSummary summary = cartService.getCartSummary(user.getId());

        return ResponseEntity.ok(summary);

    }

}


@Controller

@RequestMapping("/order")

public class OrderController {

    

    @Autowired

    private OrderService orderService;

    

    @PostMapping("/create")

    public String createOrder(@Valid OrderCreateDto orderDto,

                             @AuthenticationPrincipal User user,

                             Model model) {

        try {

            Order order = orderService.createOrder(user.getId(), orderDto);

            model.addAttribute("order", order);

            return "order/success";

        } catch (BusinessException e) {

            model.addAttribute("error", e.getMessage());

            return "cart";

        }

    }

    

    @GetMapping("/list")

    public String orderList(@AuthenticationPrincipal User user,

                           @RequestParam(defaultValue = "0") int page,

                           Model model) {

        Pageable pageable = PageRequest.of(page, 10, Sort.by("createdTime").descending());

        Page<Order> orders = orderService.getUserOrders(user.getId(), pageable);

        model.addAttribute("orders", orders);

        return "order/list";

    }

    

    @GetMapping("/detail/{orderId}")

    public String orderDetail(@PathVariable Long orderId,

                             @AuthenticationPrincipal User user,

                             Model model) {

        try {

            Order order = orderService.getOrderDetail(orderId, user.getId());

            model.addAttribute("order", order);

            return "order/detail";

        } catch (BusinessException e) {

            model.addAttribute("error", e.getMessage());

            return "redirect:/order/list";

        }

    }

}

```


## 安全配置


```java

@Configuration

@EnableWebSecurity

public class SecurityConfig {

<"zjhb.nbazhib.com">

<"kmcu.nbazhib.com">

<"djgo.nbazhib.com">

    

    @Autowired

    private UserDetailsService userDetailsService;

    

    @Bean

    public BCryptPasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();

    }

    

    @Bean

    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http

            .authorizeRequests()

                .antMatchers("/", "/products/**", "/css/**", "/js/**", "/images/**").permitAll()

                .antMatchers("/user/register", "/user/login").anonymous()

                .antMatchers("/admin/**").hasRole("ADMIN")

                .anyRequest().authenticated()

                .and()

            .formLogin()

                .loginPage("/user/login")

                .loginProcessingUrl("/user/login")

                .defaultSuccessUrl("/")

                .failureUrl("/user/login?error=true")

                .permitAll()

                .and()

            .logout()

                .logoutUrl("/user/logout")

                .logoutSuccessUrl("/")

                .permitAll()

                .and()

            .sessionManagement()

                .maximumSessions(1)

                .expiredUrl("/user/login?expired=true");

        

        return http.build();

    }

    

    @Bean

    public AuthenticationManager authenticationManager(

            AuthenticationConfiguration authConfig) throws Exception {

        return authConfig.getAuthenticationManager();

    }

}

```


## 系统特色与优化


### 1. 性能优化


```java

@Service

public class CacheService {

    

    @Autowired

    private RedisTemplate<String, Object> redisTemplate;

    

    // 商品详情缓存

    public Product getCachedProduct(Long productId) {

        String key = "product:" + productId;

        Product product = (Product) redisTemplate.opsForValue().get(key);

        if (product == null) {

            product = productService.getProductById(productId);

            redisTemplate.opsForValue().set(key, product, Duration.ofHours(1));

        }

        return product;

    }

    

    // 热门商品缓存

    public List<Product> getHotProducts() {

        String key = "hot_products";

        List<Product> products = (List<Product>) redisTemplate.opsForValue().get(key);

        if (products == null) {

            products = productService.findHotProducts();

            redisTemplate.opsForValue().set(key, products, Duration.ofMinutes(30));

        }

        return products;

    }

}

```


### 2. 异常处理


```java

@ControllerAdvice

public class GlobalExceptionHandler {

    

    @ExceptionHandler(BusinessException.class)

    public ResponseEntity<?> handleBusinessException(BusinessException e) {

        Map<String, Object> response = new HashMap<>();

        response.put("success", false);

        response.put("message", e.getMessage());

        response.put("timestamp", LocalDateTime.now());

        return ResponseEntity.badRequest().body(response);

    }

    

    @ExceptionHandler(Exception.class)

    public String handleException(Exception e, Model model) {

        model.addAttribute("error", "系统繁忙,请稍后重试");

        log.error("系统异常", e);

        return "error";

    }

}

```


## 总结


基于Java Web的网上购物商城系统通过模块化设计和分层架构,实现了完整的电商业务流程。系统具备以下特点:


1. **完整的电商功能**:用户管理、商品展示、购物车、订单处理等核心功能

2. **良好的用户体验**:响应式设计、购物车实时更新、订单状态跟踪

3. **可靠的数据安全**:密码加密、SQL注入防护、XSS攻击防范

4. **优秀的性能表现**:数据库优化、缓存策略、连接池管理

5. **易于扩展维护**:清晰的代码结构、模块化设计、标准化接口


该系统为企业级电商平台开发提供了可靠的技术方案,可以根据业务需求进一步扩展支付集成、物流跟踪、会员体系等功能。


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/19545/viewspace-3102412/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2015-11-01

  • 博文量
    895
  • 访问量
    933695