Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Design and Implementation of a Java-based Online Coffee Sales System

Tech 3

Technical Architecture

Backend: Spring Boot Framework

Spring Boot is an open-source framework designed for rapid development of applications based on the Spring framework. It adheres to the principle of "convention over configuration," offering a set of default settings that allow developers to concentrate more on business logic rather than configuration files. By utilizing automated configuration and this convention-over-configuration approach, Spring Boot significantly simplifies application setup. Developers are no longer required to manulaly configure extensive XML files or complex annotations; the framework provides sensible defaults that are automatically applied based on project dependencies and established conventions. Spring Boot projects are built using Maven or Gradle, which handle dependency management automatically. The framework also includes numerous plugins to streamline the build process. Developers can use Spring Initializr to generate a foundational project structure and select necessary dependencies.

Frontend: Vue.js Framework

A primary design goal of Vue.js is to be as simple, understandable, and easy to learn as possible. Vue provides an intuitive API that enables developers to build interactive user interfaces with ease. The framework features a straightforward yet powerful data-binding mechanism. Using directives like v-model, two-way data binding between the view and the data model can be achieved. When data changes, the view updates automatically, and vice versa, freeing developers from manual DOM manipulation. Vue.js offers a set of lifecycle hook functions, allowing developers to execute custom logic at different stages of a component's life, such as creation, mounting, updating, and destruction, thereby providing greater flexibility.

Feasibility Analysis

Feasibility analysis is a critcial component of any project development. It can directly influence the viability of a system. This analysis examines the development's purpose, whether the system can address the shortcomings of traditional manual methods, and if it can effectively solve the problems present in existing coffee sales management. The development of this online coffee sales system aims not only to gradually reduce staff workload but also to enable efficient operation and management. Therefore, the system's implementation holds significant value. Post-development, it is essential to analyze whether the benefits outweigh the costs and if the expected outcomes are achievable. Based on this analysis, a decision to proceed with development can be made. For this coffee sales system, the following feasibility aspects were considered:

  • Technical Feasibility: The use of Java technology, given its maturity, makes the development of this system technically viable.
  • Economic Feasibility: An assessment of whether the post-development benefits justify the development costs.
  • Operational Feasibility: The system's design prioritizes user-friendliness and practicality.

System Testing

The primary goal of system testing is to identify potential issues from multiple perspectives. Functional testing is conducted to discover and rectify system defects, ensuring a robust final product. The testing process verifies that the system meets client requirements, with any identified shortcomings promptly addressed. A test conclusion is drawn upon completion.

Purpose of System Testing

System testing is an essential and meticulous process. Its importance lies in being the final checkpoint for guaranteeing system quality and reliability, representing the last review in the entire development lifecycle. The core purpose is to prevent user-facing issues and enhance the user experience. To avoid disruptions during use, potential system problems must be considered from various angles and scenarios. Simulating different use cases helps uncover and resolve defects. Testing also provides insights into the system's overall quality, functional completeness, and logical coherence. A thorough testing process significantly improves both system quality and user satisfaction. The objective is to validate the system against the requirements specification and identify any discrepancies.

Functional Testing

Functional modules are tested using methods such as clicking, inputting boundary values, and validating required/optional fields—essentially black-box testing. Test cases are written and executed, leading to a final test verdict.

Login Function Test Scenario: This test validates user access via account and password credentials. The system checks user input against stored database records. An error is prompted if any input is incorrect. The interface also validates role permissions; for instance, a user account attempting to log in with an administrator role will result in an error. Sample login test cases are shown below.

Input Data Expected Result Actual Result Analysis
Username: admin, Password: 123456, Captcha: Correct Login successful Login successful As expected
Username: admin, Password: 111111, Captcha: Correct Password error "Password error, please re-enter" As expected
Username: admin, Password: 123456, Captcha: Incorrect Captcha error "Captcha information error" As expected
Username: (empty), Password: 123456, Captcha: Correct Username required "Please enter username" As expected
Username: admin, Password: (empty), Captcha: Correct Password error "Password error, please re-enter" As expected

User Management Function Test Scenario: User management primarily involves adding, editing, deleting, and searching for users. Tests include: attempting to add a user without filling required fields to check for validation; adding a user with an existing username to check for duplicate detection; deleting a user to confirm the deletion prompt and action; and editing user information to verify the update is reflected. Sample user management test cases are shown below.

Input Data Expected Result Actual Result Analysis
Fill in basic user info Add successful, user appears in list User appears in list As expected
Modify user information Edit successful, information updated User information updated As expected
Select and delete user System prompts for confirmation, user deleted after confirm System prompts, user not found after confirmation As expected
Add user without username Prompt: "Username cannot be empty" Prompt: "Username cannot be empty" As expected
Enter an existing username Add failed, prompt: "Username already exists" Add failed, prompt: "Username already exists" As expected

Database Table Design

Column Name Data Type Length Constraint
id int 11 PRIMARY KEY
addtime timestamp - DEFAULT CURRENT_TIMESTAMP
order_number varchar 64 DEFAULT NULL
product_id varchar 64 DEFAULT NULL
product_name varchar 64 DEFAULT NULL
price decimal 10,2 DEFAULT NULL
quantity int 11 DEFAULT NULL
user_id int 11 DEFAULT NULL
order_date datetime - DEFAULT NULL
status varchar 20 DEFAULT NULL

Code Reference

/**
 * Common Utility Controller
 */
@RestController
@RequestMapping("/api/common")
public class UtilityController {

    @Autowired
    private SystemConfigService configService;

    private static AipFace faceClient = null;
    private static String MAP_API_KEY = null;

    /**
     * Get location info based on coordinates
     */
    @GetMapping("/location")
    public ApiResponse getLocation(@RequestParam String longitude,
                                   @RequestParam String latitude) {
        if (MAP_API_KEY == null) {
            SystemConfig config = configService.getConfigByKey("map_api_key");
            if (config == null || config.getValue() == null) {
                return ApiResponse.error("Map API key is not configured.");
            }
            MAP_API_KEY = config.getValue();
        }
        Map<String, String> locationInfo = MapService.getCityByCoordinates(MAP_API_KEY, longitude, latitude);
        return ApiResponse.success(locationInfo);
    }

    /**
     * Compare two facial images
     * @param faceImage1 Base64 string of first image
     * @param faceImage2 Base64 string of second image
     * @return Comparison result
     */
    @PostMapping("/face/compare")
    public ApiResponse compareFaces(@RequestParam String faceImage1,
                                    @RequestParam String faceImage2) {
        if (faceClient == null) {
            SystemConfig apiKeyConfig = configService.getConfigByKey("face_api_key");
            SystemConfig secretConfig = configService.getConfigByKey("face_secret_key");
            if (apiKeyConfig == null || secretConfig == null) {
                return ApiResponse.error("Facial recognition API credentials are not configured.");
            }
            String accessToken = AuthService.getAccessToken(apiKeyConfig.getValue(), secretConfig.getValue());
            if (accessToken == null) {
                return ApiResponse.error("Failed to obtain facial recognition API access token.");
            }
            faceClient = new AipFace(null, apiKeyConfig.getValue(), secretConfig.getValue());
            faceClient.setConnectionTimeoutInMillis(3000);
            faceClient.setSocketTimeoutInMillis(60000);
        }
        JSONObject comparisonResult = null;
        try {
            // Assume images are provided as Base64 strings
            MatchRequest req1 = new MatchRequest(faceImage1, "BASE64");
            MatchRequest req2 = new MatchRequest(faceImage2, "BASE64");
            ArrayList<MatchRequest> requests = new ArrayList<>();
            requests.add(req1);
            requests.add(req2);
            comparisonResult = faceClient.match(requests);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error("Facial comparison failed: " + e.getMessage());
        }
        return ApiResponse.success(JSON.parseObject(comparisonResult.get("result").toString()));
    }
}

Database Script

CREATE TABLE `coffee_user` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Creation Time',
  `username` varchar(200) NOT NULL COMMENT 'Username',
  `password` varchar(200) NOT NULL COMMENT 'Password',
  `full_name` varchar(200) DEFAULT NULL COMMENT 'Full Name',
  `gender` varchar(10) DEFAULT NULL COMMENT 'Gender',
  `avatar` varchar(500) DEFAULT NULL COMMENT 'Avatar URL',
  `phone` varchar(20) DEFAULT NULL COMMENT 'Phone Number',
  `email` varchar(100) DEFAULT NULL COMMENT 'Email',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_username` (`username`),
  UNIQUE KEY `uk_email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='User Table';

CREATE TABLE `user_feedback` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Creation Time',
  `user_id` bigint NOT NULL COMMENT 'User ID',
  `username` varchar(200) DEFAULT NULL COMMENT 'Username',
  `content` text NOT NULL COMMENT 'Feedback Content',
  `admin_reply` text COMMENT 'Administrator Reply',
  `reply_time` timestamp NULL DEFAULT NULL COMMENT 'Reply Time',
  PRIMARY KEY (`id`),
  KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='User Feedback Table';

CREATE TABLE `auth_token` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
  `user_id` bigint NOT NULL COMMENT 'User ID',
  `username` varchar(100) NOT NULL COMMENT 'Username',
  `user_type` varchar(50) DEFAULT NULL COMMENT 'User Type/Role',
  `token_value` varchar(500) NOT NULL COMMENT 'Authentication Token',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Creation Time',
  `expiry_time` timestamp NOT NULL COMMENT 'Expiration Time',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_token` (`token_value`(255)),
  KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Authentication Token Table';

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.