SpringBoot+Uniapp实战:从零搭建校园自助打印微信小程序(附完整源码)
SpringBootUniapp实战从零搭建校园自助打印微信小程序校园打印服务一直是学生群体中的高频需求但传统的打印店往往存在排队时间长、营业时间受限等问题。本文将带你从零开始使用SpringBoot和Uniapp框架开发一个功能完善的校园自助打印微信小程序实现线上预约、文件上传、支付等完整流程。1. 项目规划与技术选型在开始编码前我们需要明确项目的核心功能和架构设计。校园自助打印系统主要解决以下几个痛点学生可以随时上传文件避免排队等待打印店可以合理安排打印任务提高工作效率管理员可以统一管理打印店和用户信息技术栈选择技术分类选用技术说明后端框架SpringBoot 2.7.x快速构建RESTful API前端框架Uniapp跨平台小程序开发数据库MySQL 8.0关系型数据存储缓存Redis提高系统响应速度文件存储阿里云OSS安全可靠的文件存储方案支付接口微信支付集成小程序支付功能提示建议开发环境使用JDK 1.8或以上版本Node.js 14.xHBuilder X作为Uniapp开发工具。2. 数据库设计与实体关系良好的数据库设计是系统稳定运行的基础。我们采用MySQL作为主数据库主要包含以下核心表用户表(user)id: 主键username: 用户名password: 加密密码phone: 联系方式balance: 账户余额打印店表(print_shop)id: 主键name: 店铺名称location: 位置信息business_hours: 营业时间status: 营业状态打印订单表(print_order)id: 主键user_id: 用户IDshop_id: 打印店IDfile_url: 文件存储路径print_config: 打印配置(黑白/彩色,单双面等)status: 订单状态create_time: 创建时间CREATE TABLE print_order ( id bigint NOT NULL AUTO_INCREMENT, user_id bigint NOT NULL, shop_id bigint NOT NULL, file_url varchar(255) NOT NULL, print_config json DEFAULT NULL, status tinyint NOT NULL DEFAULT 0 COMMENT 0-待处理 1-处理中 2-已完成 3-已取消, create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY idx_user_id (user_id), KEY idx_shop_id (shop_id) ) ENGINEInnoDB DEFAULT CHARSETutf8mb4;3. SpringBoot后端核心实现3.1 项目结构搭建采用Maven构建项目主要包结构如下src/main/java ├── com.campus.print │ ├── config # 配置类 │ ├── controller # 控制器 │ ├── service # 服务层 │ ├── dao # 数据访问层 │ ├── entity # 实体类 │ ├── util # 工具类 │ └── exception # 异常处理3.2 文件上传接口实现文件上传是打印系统的核心功能我们使用阿里云OSS作为文件存储服务RestController RequestMapping(/api/file) public class FileController { Autowired private OSS ossClient; Value(${aliyun.oss.bucketName}) private String bucketName; PostMapping(/upload) public Result upload(RequestParam(file) MultipartFile file, RequestParam(userId) Long userId) { try { // 生成唯一文件名 String fileName UUID.randomUUID().toString() file.getOriginalFilename().substring( file.getOriginalFilename().lastIndexOf(.) ); // 上传到OSS ossClient.putObject(bucketName, print/ fileName, file.getInputStream()); // 返回文件访问URL String fileUrl https:// bucketName .oss-cn-hangzhou.aliyuncs.com/print/ fileName; return Result.success(fileUrl); } catch (Exception e) { log.error(文件上传失败, e); return Result.fail(文件上传失败); } } }3.3 订单状态机设计打印订单有多种状态我们使用状态模式来管理状态流转public interface OrderState { void handle(PrintOrder order); } Service public class OrderPendingState implements OrderState { Override public void handle(PrintOrder order) { order.setStatus(0); // 发送通知给打印店 notifyShop(order); } } Service public class OrderProcessingState implements OrderState { Override public void handle(PrintOrder order) { order.setStatus(1); // 发送通知给用户 notifyUser(order); } }4. Uniapp前端开发实战4.1 项目初始化与配置使用HBuilder X创建Uniapp项目配置manifest.json文件{ mp-weixin: { appid: 你的小程序AppID, setting: { urlCheck: false, es6: true, postcss: true, minified: true }, usingComponents: true, permission: { scope.userLocation: { desc: 你的位置信息将用于查找附近的打印店 } } } }4.2 首页地图展示打印店利用微信小程序的地图组件展示周边打印店template view classcontainer map idmap :latitudelatitude :longitudelongitude :markersmarkers markertaphandleMarkerTap /map view classshop-list view v-forshop in nearbyShops :keyshop.id classshop-item clicknavigateToShop(shop.id) text{{shop.name}}/text text{{shop.distance}}米/text /view /view /view /template script export default { data() { return { latitude: 0, longitude: 0, markers: [], nearbyShops: [] } }, onLoad() { this.getLocation(); this.loadNearbyShops(); }, methods: { getLocation() { uni.getLocation({ type: gcj02, success: (res) { this.latitude res.latitude; this.longitude res.longitude; } }); }, async loadNearbyShops() { const res await this.$http.get(/api/shop/nearby, { params: { lat: this.latitude, lng: this.longitude, radius: 1000 } }); this.nearbyShops res.data; this.markers res.data.map(shop ({ id: shop.id, latitude: shop.latitude, longitude: shop.longitude, iconPath: /static/marker.png, width: 30, height: 30 })); } } } /script4.3 文件上传与打印配置实现文件选择、上传和打印参数配置功能// pages/upload/upload.vue methods: { chooseFile() { uni.chooseMessageFile({ count: 1, type: file, success: (res) { this.file res.tempFiles[0]; this.uploadFile(); } }); }, async uploadFile() { uni.showLoading({ title: 上传中... }); try { const formData new FormData(); formData.append(file, this.file); formData.append(userId, this.userId); const res await this.$http.post(/api/file/upload, formData, { header: { Content-Type: multipart/form-data } }); this.fileUrl res.data; uni.hideLoading(); uni.showToast({ title: 上传成功, icon: success }); } catch (e) { uni.hideLoading(); uni.showToast({ title: 上传失败, icon: none }); } }, submitOrder() { if (!this.fileUrl) { uni.showToast({ title: 请先上传文件, icon: none }); return; } const orderData { userId: this.userId, shopId: this.shopId, fileUrl: this.fileUrl, printConfig: { color: this.colorType, duplex: this.duplex, copies: this.copies, pageRange: this.pageRange } }; this.createOrder(orderData); } }5. 系统安全与性能优化5.1 接口安全防护JWT认证所有API请求需要携带有效的JWT token参数校验使用Hibernate Validator进行参数校验防SQL注入使用MyBatis的#{}参数绑定XSS防护对用户输入进行转义处理Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers(/api/auth/**).permitAll() .antMatchers(/api/file/download/**).permitAll() .anyRequest().authenticated(); http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); } Bean public JwtAuthenticationFilter jwtAuthenticationFilter() { return new JwtAuthenticationFilter(); } }5.2 缓存策略优化使用Redis缓存热点数据减少数据库压力打印店信息缓存设置30分钟过期时间用户信息缓存设置1小时过期时间订单状态缓存设置5分钟过期时间Service public class ShopServiceImpl implements ShopService { Autowired private RedisTemplateString, Object redisTemplate; private static final String SHOP_CACHE_PREFIX shop:; Override public Shop getShopById(Long id) { String cacheKey SHOP_CACHE_PREFIX id; Shop shop (Shop) redisTemplate.opsForValue().get(cacheKey); if (shop null) { shop shopDao.selectById(id); if (shop ! null) { redisTemplate.opsForValue().set( cacheKey, shop, 30, TimeUnit.MINUTES ); } } return shop; } }6. 部署与上线6.1 后端服务部署使用Docker容器化部署SpringBoot应用# Dockerfile FROM openjdk:8-jdk-alpine VOLUME /tmp ARG JAR_FILEtarget/*.jar COPY ${JAR_FILE} app.jar ENTRYPOINT [java,-jar,/app.jar]部署命令# 构建镜像 docker build -t campus-print . # 运行容器 docker run -d -p 8080:8080 \ -e SPRING_DATASOURCE_URLjdbc:mysql://mysql-server:3306/campus_print \ -e SPRING_REDIS_HOSTredis-server \ --name campus-print \ campus-print6.2 小程序发布流程在微信公众平台完成小程序注册配置服务器域名白名单使用HBuilder X进行代码打包上传代码到微信开发者平台提交审核并发布注意确保所有接口都使用HTTPS协议小程序要求的域名必须备案。7. 项目扩展与进阶完成基础功能后可以考虑以下扩展方向智能推荐基于用户历史打印记录推荐打印店打印预览集成PDF.js实现文件预览功能优惠券系统增加营销功能吸引用户数据统计为打印店提供经营数据分析// 智能推荐算法示例 public ListShop recommendShops(Long userId) { // 获取用户历史订单 ListPrintOrder orders orderDao.findByUserId(userId); // 分析常用打印店 MapLong, Integer shopFrequency orders.stream() .collect(Collectors.groupingBy( PrintOrder::getShopId, Collectors.summingInt(o - 1) )); // 获取用户当前位置 UserLocation location getCurrentLocation(userId); // 综合距离和频率进行推荐 return shopDao.findAll().stream() .sorted(Comparator .comparingDouble((Shop s) - calculateDistance(location, s.getLocation()) * 0.7 - shopFrequency.getOrDefault(s.getId(), 0) * 0.3 ) ) .limit(5) .collect(Collectors.toList()); }在实际开发中我们遇到了文件格式兼容性问题最终通过集成LibreOffice实现了常见办公文档的自动转换。对于高并发场景采用消息队列对打印任务进行削峰处理确保系统稳定性。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2420419.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!