springboot-mvc项目示例代码

混编项目代码示例,前端去写视图层,后端去写控制器

项目目录结构:

powershell 复制代码
src/
├── main/
│   ├── java/
│   │   └── com/
│   │       └── example/
│   │           └── app/
│   │               ├── Application.java
│   │               ├── controller/
│   │               │   └── UserController.java
│   │               └── model/
│   │                   ├── User.java
│   │                   └── ApiResponse.java
│   └── resources/
│       ├── templates/
│       │   └── user-list.html
│       ├── static/
│       │   ├── css/
│       │   ├── js/
│       │   └── images/
│       └── application.properties
pom.xml

UserController文件

java 复制代码
package com.example.app.controller;

import com.example.app.model.User;
import com.example.app.model.ApiResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {

    private List<User> userList = new ArrayList<>();

    // 视图层方法 - 返回用户列表页面
    @GetMapping("/users")
    public String userListPage(Model model) {
        model.addAttribute("users", userList);
        model.addAttribute("newUser", new User());
        return "user-list";
    }

    // 后端接口 - 获取所有用户 (REST API)
    @GetMapping("/api/users")
    @ResponseBody
    public List<User> getAllUsers() {
        return userList;
    }

    // 后端接口 - 添加用户 (REST API)
    @PostMapping("/api/users")
    @ResponseBody
    public ApiResponse addUser(@RequestBody User user) {
        user.setId(System.currentTimeMillis());
        userList.add(user);
        return new ApiResponse(true, "用户添加成功", user);
    }

    // 后端接口 - 删除用户 (REST API)
    @DeleteMapping("/api/users/{id}")
    @ResponseBody
    public ApiResponse deleteUser(@PathVariable Long id) {
        boolean removed = userList.removeIf(user -> user.getId().equals(id));
        if (removed) {
            return new ApiResponse(true, "用户删除成功");
        } else {
            return new ApiResponse(false, "用户不存在");
        }
    }
}

user-list.html文件

html 复制代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户管理系统</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        .container { max-width: 800px; margin: 0 auto; padding: 20px; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; }
        input { width: 100%; padding: 8px; border: 1px solid #ddd; }
        button { padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer; }
        .user-item { padding: 10px; border: 1px solid #eee; margin: 5px 0; display: flex; justify-content: space-between; }
        .error { color: red; }
        .success { color: green; }
    </style>
</head>
<body>
<div class="container">
    <h1>用户管理系统</h1>

    <!-- 添加用户表单 -->
    <div class="form-section">
        <h2>添加用户</h2>
        <form id="userForm">
            <div class="form-group">
                <label>姓名:</label>
                <input type="text" id="name" name="name" required>
            </div>
            <div class="form-group">
                <label>邮箱:</label>
                <input type="email" id="email" name="email" required>
            </div>
            <button type="submit">添加用户</button>
        </form>
    </div>

    <!-- 消息显示 -->
    <div id="message"></div>

    <!-- 用户列表 -->
    <div class="user-list">
        <h2>用户列表</h2>
        <div id="usersContainer">
            <!-- 用户列表将通过JavaScript动态加载 -->
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        loadUsers();
        setupForm();
    });

    function loadUsers() {
        axios.get('/api/users')
            .then(response => {
                displayUsers(response.data);
            })
            .catch(error => {
                showMessage('加载用户列表失败: ' + error.message, 'error');
            });
    }

    function displayUsers(users) {
        const container = document.getElementById('usersContainer');

        if (users.length === 0) {
            container.innerHTML = '<p>暂无用户</p>';
            return;
        }

        let html = '';
        users.forEach(user => {
            html += `
                    <div class="user-item">
                        <div>
                            <strong>${user.name}</strong> - ${user.email}
                        </div>
                        <button onclick="deleteUser(${user.id})">删除</button>
                    </div>
                `;
        });
        container.innerHTML = html;
    }

    function setupForm() {
        document.getElementById('userForm').addEventListener('submit', function(e) {
            e.preventDefault();

            const user = {
                name: document.getElementById('name').value,
                email: document.getElementById('email').value
            };

            axios.post('/api/users', user)
                .then(response => {
                    if (response.data.success) {
                        showMessage(response.data.message, 'success');
                        document.getElementById('userForm').reset();
                        loadUsers();
                    } else {
                        showMessage(response.data.message, 'error');
                    }
                })
                .catch(error => {
                    showMessage('添加用户失败: ' + error.message, 'error');
                });
        });
    }

    function deleteUser(userId) {
        if (confirm('确定要删除这个用户吗?')) {
            axios.delete(`/api/users/${userId}`)
                .then(response => {
                    if (response.data.success) {
                        showMessage(response.data.message, 'success');
                        loadUsers();
                    } else {
                        showMessage(response.data.message, 'error');
                    }
                })
                .catch(error => {
                    showMessage('删除用户失败: ' + error.message, 'error');
                });
        }
    }

    function showMessage(message, type) {
        const messageDiv = document.getElementById('message');
        messageDiv.textContent = message;
        messageDiv.className = type;

        setTimeout(() => {
            messageDiv.textContent = '';
            messageDiv.className = '';
        }, 3000);
    }
</script>
</body>
</html>

application.properties文件

powershell 复制代码
# 服务器配置
server.port=8080

# Thymeleaf配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.cache=false

# 静态资源路径
spring.web.resources.static-locations=classpath:/static/

User文件

java 复制代码
package com.example.app.model;

import lombok.Data;

@Data
public class User {
    private Long id;
    private String name;
    private String email;
}

ApiResponse文件

java 复制代码
package com.example.app.model;

import lombok.Data;

@Data
public class ApiResponse {
    private boolean success;
    private String message;
    private Object data;
    public ApiResponse(boolean success, String message) {
        this.success = success;
        this.message = message;
    }

    public ApiResponse(boolean success, String message, Object data) {
        this.success = success;
        this.message = message;
        this.data = data;
    }
}

Application文件

java 复制代码
package com.example.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
相关推荐
后端小张1 小时前
【JAVA进阶】Spring Boot 核心知识点之自动配置:原理与实战
java·开发语言·spring boot·后端·spring·spring cloud·自动配置
3***C7446 小时前
Spring Boot 整合 log4j2 日志配置教程
spring boot·单元测试·log4j
tg-zm8899966 小时前
2025返利商城源码/挂机自动收益可二开多语言/自定义返利比例/三级分销理财商城
java·mysql·php·laravel·1024程序员节
X***C8626 小时前
SpringBoot:几种常用的接口日期格式化方法
java·spring boot·后端
i***t9196 小时前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
前端达人7 小时前
你的App消息推送为什么石沉大海?看Service Worker源码我终于懂了
java·开发语言
小光学长7 小时前
基于ssm的宠物交易系统的设计与实现850mb48h(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·前端·数据库
编程大师哥7 小时前
vxe-table 透视表分组汇总及排序基础配置
java
8***84827 小时前
spring security 超详细使用教程(接入springboot、前后端分离)
java·spring boot·spring
o***74177 小时前
基于SpringBoot的DeepSeek-demo 深度求索-demo 支持流式输出、历史记录
spring boot·后端·lua