Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Building a Smart Unmanned Warehouse Management System with Spring Boot, Vue, and UniApp

Tech 2

System Architecture Overview

The warehouse management system leverages a modern three-tier architecture combining Spring Boot for backend services, Vue.js for web interfaces, and UniApp for mobile access. This architectural approach ensures seamless data synchronization across desktop and mobile platforms while maintaining robust business logic processing capabilities.

Backend Implementation with Spring Boot

Spring Boot provides an embedded server environment with automatic configuration capabilities. The framework reduces boilerplate code through convention-over-configuration principles, enabling rapid development of RESTful APIs.

Authentication and Session Management

The authentication mechanism utilizes token-based session handling. Upon successful credential validation, the system generates a unique token with configurable expiration time.

@IgnoreAuth
@PostMapping(value = "/login")
public R login(String username, String password, String captcha, HttpServletRequest request) {
   UsersEntity user = userService.selectOne(new EntityWrapper<UsersEntity>().eq("username", username));
   if(user==null || !user.getPassword().equals(password)) {
      return R.error("账号或密码不正确");
   }
   String token = tokenService.generateToken(user.getId(), username, "users", user.getRole());
   return R.ok().put("token", token);
}

The token generation service creates a random 32-character string and associates it with user credentials:

@Override
public String generateToken(Long userId, String username, String tableName, String role) {
    TokenEntity existingToken = this.selectOne(
        new EntityWrapper<TokenEntity>().eq("userid", userId).eq("role", role)
    );
    String tokenValue = CommonUtil.getRandomString(32);
    Calendar expiration = Calendar.getInstance();
    expiration.setTime(new Date());
    expiration.add(Calendar.HOUR_OF_DAY, 1);
    
    if(existingToken != null) {
        existingToken.setToken(tokenValue);
        existingToken.setExpiratedtime(expiration.getTime());
        this.updateById(existingToken);
    } else {
        this.insert(new TokenEntity(userId, username, tableName, role, tokenValue, expiration.getTime()));
    }
    return tokenValue;
}

Authorization Interceptor

Request interception validates tokens before allowing access to protected endpoints:

@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    public static final String LOGIN_TOKEN_KEY = "Token";
    @Autowired
    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,Token, Origin,imgType, Content-Type, cache-control,postman-token,Cookie, Accept,authorization");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        
        if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
            response.setStatus(HttpStatus.OK.value());
            return false;
        }
        
        IgnoreAuth annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
        } else {
            return true;
        }

        String token = request.getHeader(LOGIN_TOKEN_KEY);
        
        if(annotation != null) {
            return true;
        }
        
        TokenEntity tokenEntity = null;
        if(StringUtils.isNotBlank(token)) {
            tokenEntity = tokenService.getTokenEntity(token);
        }
        
        if(tokenEntity != null) {
            request.getSession().setAttribute("userId", tokenEntity.getUserid());
            request.getSession().setAttribute("role", tokenEntity.getRole());
            request.getSession().setAttribute("tableName", tokenEntity.getTablename());
            request.getSession().setAttribute("username", tokenEntity.getUsername());
            return true;
        }
        
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(JSONObject.toJSONString(R.error(401, "请先登录")));
        writer.close();
        return false;
    }
}

Data Persistence Layer

MyBatis-Plus simplifies database operations through its ORM capabilities, providing automatic SQL generation for CRUD operations. The framework supports pagination, dynamic query construction, and optimistic locking mechanisms.

Database Schema

-- Token storage table
DROP TABLE IF EXISTS `token`;
CREATE TABLE `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 'Username',
  `tablename` varchar(100) DEFAULT NULL COMMENT 'Related table name',
  `role` varchar(100) DEFAULT NULL COMMENT 'User role',
  `token` varchar(200) NOT NULL COMMENT 'Session token',
  `addtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Creation timestamp',
  `expiratedtime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Expiration timestamp',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT='Session token table';

-- Sample token records
INSERT INTO `token` VALUES 
('9', '23', 'cd01', 'xuesheng', '学生', 'al6svx5qkei1wljry5o1npswhdpqcpcg', '2023-02-23 21:46:45', '2023-03-15 14:01:36'),
('12', '1', 'admin', 'users', '管理员', 'h1pqzsb9bldh93m92j9m2sljy9bt1wdh', '2023-02-27 19:37:01', '2023-03-17 18:23:02');

Frontend Architecture with Vue

Vue.js implements virtual DOM technology for efficient DOM manipulation. The framework employs reactive data binding, allowing automatic UI updates when underlying data changes. This component-based architecture facilitates modular development and code reusability.

System Testing Strategy

Comprehensive testing ensures system reliability and user satisfaction. Testing activities focus on validating functional requirements and identifying defects before production deployment.

Test Objectives

System testing serves as the final quality assurance checkpoint in the development lifecycle. The primary goals include:

  1. Defect Detection: Identifying inconsistencies between implemented functionality and documented requirements through systematic test case execution.
  2. User Experience Validation: Ensuring smooth interactions without errors or unexpected behaviors that could frustrate users.
  3. Quality Assessment: Evaluating whether system components function correctly both independently and as an integrated whole.

Functional Testing Approach

Black-box testing techniques verify system behavior from the user's perspective. Test scenarios simulate real-world usage patterns to validate expected outcomes.

Login Module Test Cases

Test Input Expected Result Actual Result Analysis
Username: guanliyuan, Password: 123456, Valid captcha System login successful Login successful Matches expectation
Username: guanliyuan, Password: 111111, Valid captcha Password error message displayed Password error message displayed Matches expectation
Username: guanliyuan, Password: 123456, Invalid captcha Captcha validation error Captcha validation error Matches expectation
Username: empty, Password: 123456, Valid captcha Username required validation Username required validation Matches expectation
Username: guanliyuan, Password: empty, Valid captcha Password error message displayed Password error message displayed Matches expectation

User Management Test Cases

Test Input Expected Result Actual Result Analysis
Complete user information form submission User added and visible in list User appears in user list Matches expectation
Modifying existing user information Changes persisted successfully User information updated Matches expectation
Selecting user for deletion Confirmation prompt, user removed Confirmation shown, user deleted Matches expectation
Form submission without username Validation error displayed Username cannot be empty message Matches expectation
Adding duplicate username Duplicate username error Username already exists message Matches expectation

Test Results Summary

The testing phase validates that all functional modules operate according to design specifications. Test execution confirms correct system behavior across authentication flows, user management operations, and data persistence scenarios. The results demonstrate that the implemented system meets quality standards and provides reliable functionality for end users.

Tags: Spring Boot

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.