Full-Stack E-Commerce Platform for Agricultural Products Using SSM and Vue.js

Introduction

In modern agricultural commerce, digital platforms play a crucial role in connecting farmers directly with consumers. This article presents the design and implementation of a comprehensive agricultural product sales system, featuring a robust backend architecture and a responsive frontend interface. The system addresses common challenges in agricultural e-commerce, including product management, order processing, and user authentication.

System Architecture

Backend Framework: Spring Boot

Spring Boot provides an embedded server environment with built-in support for Tomcat, Jetty, and Undertow, eliminating the need for manual server configuration. The framework's auto-configuration mechanism automatically sets up application components based on project dependencies, significantly reducing development overhead.

Key features include out-of-the-box functionality through Spring Data, Spring Security, and Spring Cloud integrations. These built-in capabilities enable rapid application development while maintaining scalability and seamless integration with external technologies.

Frontend Framework: Vue.js

Vue.js leverages virtual DOM technology to optimize DOM manipulation performance. The framework implements reactive data binding, which automatically updates the user interface when underlying data changes, allowing developers to focus on business logic rather than manual UI updates.

Vue's component-based architecture promotes code reusability and maintainability, making it ideal for building complex single-page applications with dynamic data requirements.

Persistence Layer: MyBatis-Plus

MyBatis-Plus serves as an enhanced wrapper around MyBatis, streamlining database operations across multiple database systems including MySQL, Oracle, SQL Server, and PostgreSQL. The framework provides comprehensive ORM capabilities through intuitive APIs and annotations, reducing the need for manual SQL writing.

Additional features include automatic code generation for entity classes, mapper interfaces, and XML mapping files. Built-in support for pagination, dynamic queries, optimistic locking, and performance profiling enibles efficient data access layer development.

System Testing

Comprehensive testing identifies defects and ensures system reliability. The testing strategy validates functional requirements while maintaining a user-centered approach throughout the development lifecycle.

Testing Objectives

System testing represents a critical phase in the development process, serving as the final quality checkpoint before deployment. The primary objectives include preventing user-facing issues, enhancing user experience, and validating system quality through multiple scenarios and simulation conditions.

Testing scenarios simulate real-world usage patterns to discover potential defects. Each identified issue undergoes documentation and resolution to improve overall system reliability and usability.

Functional Module Testing

Black-box testing methods validate each functional module through input boundary analysis, required field verification, and interaction testing. Test cases define expected behaviors for various input combinations.

Authentication module test scenarios:

Input Data Expected Result Actual Result Analysis
Username: admin, Password: secure123, Captcha: correct Login successful System access granted Matches expectation
Username: admin, Password: wrongpass, Captcha: correct Authentication failure Invalid credentials message displayed Matches expectation
Username: admin, Password: secure123, Captcha: invalid Validation failure Verification code error message shown Matches expectation
Username: empty, Password: secure123, Captcha: correct Validation error Username field required message Matches expectation
Username: admin, Password: empty, Captcha: correct Authentication failure Password field required message Matches expectation

User management module test scenarios:

Input Data Expected Result Actual Result Analysis
Complete user profile information User created and displayed in list User appears in management list Matches expectation
Updated user profile data Changes saved and reflected User information updated correctly Matches expectation
Delete selected user record System confirmation, user removed Confirmation dialog shown, user deleted Matches expectation
Create user with empty username Validation error displayed Username field validation message shown Matches expectation
Create user with duplicate username Creation blocked with error Username conflict error displayed Matches expectation

Testing Conclusion

The system undergoes comprehensive black-box testing to verify functional correctness. Test scenarios simulate actual user workflows to ensure proper system behavior.

Validation confirms that all functional modules meet initial design specifications. Module logic demonstrates accuracy across various scenarios. The system emphasizes straightforward operational patterns suitable for diverse user backgrounds.

Testing outcomes confirm that implemented functionality and performance align with design requirements. All identified defects undergo resolution during the testing phase.

Technical Implementation

Authentication Controller

@SkipAuthentication
@PostMapping("/authenticate")
public ResponseEntity<Object> authenticate(String account, String secret, String verifyCode, HttpServletRequest request) {
    UserEntity authenticatedUser = userService.findByCondition(
        new EntityWrapper<UserEntity>().eq("account", account)
    );
    
    if (authenticatedUser == null || !authenticatedUser.getSecret().equals(secret)) {
        return ResponseEntity.badRequest().body(
            ResultResponse.error("Invalid credentials provided")
        );
    }
    
    String sessionToken = tokenService.createToken(
        authenticatedUser.getId(),
        account, 
        "users", 
        authenticatedUser.getRole()
    );
    
    return ResponseEntity.ok().body(
        ResultResponse.success().put("sessionToken", sessionToken)
    );
}

Token Management Service

@Override
public String createToken(Long userIdentifier, String username, String tableReference, String roleType) {
    TokenEntity existingToken = this.findByCondition(
        new EntityWrapper<TokenEntity>()
            .eq("userid", userIdentifier)
            .eq("role", roleType)
    );
    
    String generatedToken = RandomStringGenerator.generate(32);
    Calendar expiration = Calendar.getInstance();
    expiration.setTime(new Date());
    expiration.add(Calendar.HOUR_OF_DAY, 1);
    
    if (existingToken != null) {
        existingToken.setToken(generatedToken);
        existingToken.setExpirationTime(expiration.getTime());
        this.modifyById(existingToken);
    } else {
        this.insert(new TokenEntity(
            userIdentifier,
            username, 
            tableReference, 
            roleType, 
            generatedToken, 
            expiration.getTime()
        ));
    }
    
    return generatedToken;
}

Security Interceptor

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    
    public static final String SESSION_KEY = "Authorization";
    
    @Inject
    private TokenService tokenService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", 
            "x-requested-with,request-source,Authorization, Origin,imgType, " +
            "Content-Type, cache-control,postman-token,Cookie, Accept,authorization");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        
        if (RequestMethod.OPTIONS.name().equals(request.getMethod())) {
            response.setStatus(HttpStatus.OK.value());
            return false;
        }
        
        SkipAuthentication skipAuth;
        if (handler instanceof HandlerMethod) {
            skipAuth = ((HandlerMethod) handler).getMethodAnnotation(SkipAuthentication.class);
        } else {
            return true;
        }
        
        String requestToken = request.getHeader(SESSION_KEY);
        
        if (skipAuth != null) {
            return true;
        }
        
        TokenEntity tokenRecord = null;
        if (StringUtils.hasText(requestToken)) {
            tokenRecord = tokenService.retrieveTokenEntity(requestToken);
        }
        
        if (tokenRecord != null) {
            request.getSession().setAttribute("userId", tokenRecord.getUserid());
            request.getSession().setAttribute("role", tokenRecord.getRole());
            request.getSession().setAttribute("tableName", tokenRecord.getTablename());
            request.getSession().setAttribute("username", tokenRecord.getUsername());
            return true;
        }
        
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter output = response.getWriter();
        output.print(JSONObject.toJSONString(ResultResponse.error(401, "Authentication required")));
        output.close();
        return false;
    }
}

Database Schema

CREATE TABLE `auth_token` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'Primary key',
  `userid` bigint(20) NOT NULL COMMENT 'User identifier',
  `username` varchar(100) NOT NULL COMMENT 'Account name',
  `tablename` varchar(100) DEFAULT NULL COMMENT 'Table reference',
  `role` varchar(100) DEFAULT NULL COMMENT 'Access level',
  `token` varchar(200) NOT NULL COMMENT 'Session token',
  `addtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Creation timestamp',
  `expiration` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Token expiration time',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT='Authentication tokens';

System Features Summary

The platform provides comprehensive functionality for agricultural product sales, including product catalog management, shopping cart operations, order processing, and user administration. The architecture supports scalable deployment and maintains clean separation between presentation and business logic layers.

Tags: spring-boot Vue.js mybatis-plus java web-development

Posted on Sat, 22 Aug 2026 16:26:01 +0000 by metalenchantment