Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Design and Implementation of a Bus Route Query System Using SpringBoot and Vue

Tech 1

System Overview

Modern society advances rapidly, and computer applications for data management have become quite sophisticated. With the rise of mobile internet, information processing no longer depends on geographical constraints, offering timely and efficient solutions that are widely appreciated. This project develops a bus route query system with two roles: administrator and user. Administrators manage profiles, users, bus routes, announcements, links, messages, and system settings. Users can register, log in, view routes, read announcements, and post messages.

The backend is built using Java and the Spring Boot framework, storing data in MySQL. This setup ensures convenience and efficiency for users, centralized business processing, and secure, scalable data handling through hardware-software collaboration.

Development Environment

  • Language: Java
  • Framework: Spring Boot
  • JDK Version: JDK 1.8
  • Server: Tomcat 7
  • Database: MySQL 5.7 (must be version 5.7)
  • Tool: Navicat 11
  • IDE: Eclipse/MyEclipse/IntelliJ IDEA
  • Build Tool: Maven 3.3.9
  • Browser: Google Chrome

Backend URL: localhost:8080/project-name/admin/dist/index.html Frontend URL: localhost:8080/project-name/front/dist/index.html (not required) Admin credentials: username admin, password admin

Technology Overview

Java

Java is an object-oriented programming language known for its static typing and multithreading capabilities. It organizes programs into modules with encapsulation, promoting independence and maintainability. Java's network interface supports web application development and handles exceptions automatically, making it robust and versatile.

Spring Boot Framework

Spring Boot simplifies the setup and configuration of Spring applications, eliminating the need for extensive boilerplate configurations. It integrates many frameworks, reducing dependency management complexity and version conflicts, thereby streamlining development processes.

MySQL Database

MySQL is a relational database management system known for speed, versatility, and security. Its simplicity allows complex operations to be performed with minimal code, making it ideal for data storage and management in projects. It provides high data sharing, low redundancy, and easy scalability with strong security features.

Core Code Examples

File Upload Controller

package com.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.annotation.IgnoreAuth;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.entity.ConfigEntity;
import com.service.ConfigService;
import com.utils.R;

@RestController
@RequestMapping("file")
public class FileController {
    @Autowired
    private ConfigService configService;

    @RequestMapping("/upload")
    @IgnoreAuth
    public R upload(@RequestParam("file") MultipartFile file, String type) throws Exception {
        if (file.isEmpty()) {
            throw new RuntimeException("File cannot be empty");
        }
        String extension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        File path = new File(ResourceUtils.getURL("classpath:static").getPath());
        if (!path.exists()) {
            path = new File("");
        }
        File uploadDir = new File(path.getAbsolutePath(), "/upload/");
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        String filename = new Date().getTime() + "." + extension;
        File destination = new File(uploadDir.getAbsolutePath() + "/" + filename);
        file.transferTo(destination);
        
        if (StringUtils.isNotBlank(type) && type.equals("1")) {
            ConfigEntity config = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "faceFile"));
            if (config == null) {
                config = new ConfigEntity();
                config.setName("faceFile");
                config.setValue(filename);
            } else {
                config.setValue(filename);
            }
            configService.insertOrUpdate(config);
        }
        return R.ok().put("file", filename);
    }

    @IgnoreAuth
    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(@RequestParam String fileName) {
        try {
            File path = new File(ResourceUtils.getURL("classpath:static").getPath());
            if (!path.exists()) {
                path = new File("");
            }
            File uploadDir = new File(path.getAbsolutePath(), "/upload/");
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            File file = new File(uploadDir.getAbsolutePath() + "/" + fileName);
            if (file.exists()) {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                headers.setContentDispositionFormData("attachment", fileName);
                return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Forum Management Controller

package com.controller;

import java.util.*;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.annotation.IgnoreAuth;
import com.entity.ForumEntity;
import com.entity.view.ForumView;
import com.service.ForumService;
import com.utils.PageUtils;
import com.utils.R;
import com.utils.MPUtil;

@RestController
@RequestMapping("/forum")
public class ForumController {
    @Autowired
    private ForumService forumService;

    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params, ForumEntity forum, HttpServletRequest request) {
        if (!request.getSession().getAttribute("role").toString().equals("管理员")) {
            forum.setUserid((Long) request.getSession().getAttribute("userId"));
        }
        EntityWrapper<ForumEntity> wrapper = new EntityWrapper<>();
        PageUtils page = forumService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(wrapper, forum), params), params));
        return R.ok().put("data", page);
    }

    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params, ForumEntity forum, HttpServletRequest request) {
        if (!request.getSession().getAttribute("role").toString().equals("管理员")) {
            forum.setUserid((Long) request.getSession().getAttribute("userId"));
        }
        EntityWrapper<ForumEntity> wrapper = new EntityWrapper<>();
        PageUtils page = forumService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(wrapper, forum), params), params));
        return R.ok().put("data", page);
    }

    @IgnoreAuth
    @RequestMapping("/flist")
    public R flist(@RequestParam Map<String, Object> params, ForumEntity forum, HttpServletRequest request) {
        EntityWrapper<ForumEntity> wrapper = new EntityWrapper<>();
        PageUtils page = forumService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(wrapper, forum), params), params));
        return R.ok().put("data", page);
    }

    @RequestMapping("/query")
    public R query(ForumEntity forum) {
        EntityWrapper<ForumEntity> wrapper = new EntityWrapper<>();
        wrapper.allEq(MPUtil.allEQMapPre(forum, "forum"));
        ForumView forumView = forumService.selectView(wrapper);
        return R.ok("Query successful").put("data", forumView);
    }

    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        ForumEntity forum = forumService.selectById(id);
        return R.ok().put("data", forum);
    }

    @IgnoreAuth
    @RequestMapping("/detail/{id}")
    public R detail(@PathVariable("id") Long id) {
        ForumEntity forum = forumService.selectById(id);
        return R.ok().put("data", forum);
    }

    @IgnoreAuth
    @RequestMapping("/list/{id}")
    public R list(@PathVariable("id") String id) {
        ForumEntity forum = forumService.selectById(id);
        getChilds(forum);
        return R.ok().put("data", forum);
    }

    private ForumEntity getChilds(ForumEntity forum) {
        List<ForumEntity> children = forumService.selectList(new EntityWrapper<ForumEntity>().eq("parentid", forum.getId()));
        if (children == null || children.isEmpty()) {
            return null;
        }
        forum.setChilds(children);
        for (ForumEntity child : children) {
            getChilds(child);
        }
        return forum;
    }

    @RequestMapping("/save")
    public R save(@RequestBody ForumEntity forum, HttpServletRequest request) {
        forum.setId(new Date().getTime() + new Double(Math.floor(Math.random() * 1000)).longValue());
        forum.setUserid((Long) request.getSession().getAttribute("userId"));
        forumService.insert(forum);
        return R.ok();
    }

    @RequestMapping("/add")
    public R add(@RequestBody ForumEntity forum, HttpServletRequest request) {
        forum.setId(new Date().getTime() + new Double(Math.floor(Math.random() * 1000)).longValue());
        forum.setUserid((Long) request.getSession().getAttribute("userId"));
        forumService.insert(forum);
        return R.ok();
    }

    @RequestMapping("/update")
    @Transactional
    public R update(@RequestBody ForumEntity forum, HttpServletRequest request) {
        forumService.updateById(forum);
        return R.ok();
    }

    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        forumService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }

    @RequestMapping("/remind/{columnName}/{type}")
    public R remindCount(@PathVariable("columnName") String columnName, HttpServletRequest request,
                         @PathVariable("type") String type, @RequestParam Map<String, Object> map) {
        map.put("column", columnName);
        map.put("type", type);
        
        if (type.equals("2")) {
            Calendar calendar = Calendar.getInstance();
            Date startDate = null;
            Date endDate = null;
            if (map.get("remindstart") != null) {
                Integer startDays = Integer.parseInt(map.get("remindstart").toString());
                calendar.setTime(new Date());
                calendar.add(Calendar.DAY_OF_MONTH, startDays);
                startDate = calendar.getTime();
                map.put("remindstart", startDate);
            }
            if (map.get("remindend") != null) {
                Integer endDays = Integer.parseInt(map.get("remindend").toString());
                calendar.setTime(new Date());
                calendar.add(Calendar.DAY_OF_MONTH, endDays);
                endDate = calendar.getTime();
                map.put("remindend", endDate);
            }
        }
        
        Wrapper<ForumEntity> wrapper = new EntityWrapper<>();
        if (map.get("remindstart") != null) {
            wrapper.ge(columnName, map.get("remindstart"));
        }
        if (map.get("remindend") != null) {
            wrapper.le(columnName, map.get("remindend"));
        }
        
        int count = forumService.selectCount(wrapper);
        return R.ok().put("count", count);
    }
}

Testing

The system was installed and tested locally before proceeding to white-box and black-box testing. The testing strategy focused on customer requirements, applied Pareto principles to prioritize critical components, and used incremental testing from unit to integration levels. Comprehensive test coverage ensured program logic validation and requirement compliance.

Conclusion

This system offers comprehensive functionality, ease of maintenance, intuitive UI, and high performance compared to existing systems. Key advantages include:

  1. Dynamic page implementation in Java enhances maintainability and reusability.
  2. Spring Boot framework separates presentation from logic, facilitating modular management.
  3. MySQL database supports XML standards, scalability, and robust security.

This project represents a complete learning experience, demonstrating practical application of modern development practices.

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.