白骑士的Java教学项目实战篇 8.3 开发一个简单的Java Web应用

65 篇文章 0 订阅

        在本章节中,我们将通过开发一个简单的Java Web应用程序来进一步提升Java开发技能。我们将使用Spring Boot框架来构建一个简单的任务管理系统Web应用。这个项目将帮助你了解如何使用Spring Boot创建Web应用、处理HTTP请求、与数据库交互以及进行简单的前端开发。通过这个项目,你将全面掌握Java Web开发的基础知识和实践技巧。

项目需求

        我们的目标是开发一个简单的任务管理系统Web应用,具有以下功能:

  • 添加任务
  • 查看所有任务
  • 删除任务
  • 标记任务为完成

项目设计

        首先,我们设计应用的结构。应用将包含以下组件:

  • 实体类:‘Task‘
  • 数据访问层:‘TaskRepository‘
  • 服务层:‘TaskService‘
  • 控制器层:‘TaskController‘
  • 前端视图:使用Thymeleaf模板引擎

创建Spring Boot项目

        我们可以使用Spring Initializr生成项目框架。选择以下依赖项:

  • Spring Web
  • Spring Data JPA
  • H2 Database
  • Thymeleaf

项目结构

        项目结构如下:

src
 └── main
     ├── java
     │   └── com
     │       └── example
     │           └── taskmanager
     │               ├── TaskManagerApplication.java
     │               ├── controller
     │               │   └── TaskController.java
     │               ├── entity
     │               │   └── Task.java
     │               ├── repository
     │               │   └── TaskRepository.java
     │               └── service
     │                   └── TaskService.java
     └── resources
         ├── application.properties
         ├── static
         └── templates
             └── index.html

实体类

        ‘Task‘类表示一个任务,包含以下属性和方法:

package com.example.taskmanager.entity;


import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;


@Entity
public class Task {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String description;
    private boolean completed;

    public Task() {
    }

    public Task(String description) {
        this.description = description;
        this.completed = false;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public boolean isCompleted() {
        return completed;
    }

    public void setCompleted(boolean completed) {
        this.completed = completed;
    }
}

数据访问层

        ‘TaskRepository‘接口扩展了‘JpaRepository‘接口,提供对任务数据的CRUD操作:

package com.example.taskmanager.repository;


import com.example.taskmanager.entity.Task;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;


@Repository
public interface TaskRepository extends JpaRepository<Task, Long> {
}

服务层

        ‘TaskService‘类包含业务逻辑和数据访问方法:

package com.example.taskmanager.service;


import com.example.taskmanager.entity.Task;
import com.example.taskmanager.repository.TaskRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;


@Service
public class TaskService {
    private final TaskRepository taskRepository;

    @Autowired
    public TaskService(TaskRepository taskRepository) {
        this.taskRepository = taskRepository;
    }

    public List<Task> getAllTasks() {
        return taskRepository.findAll();
    }

    public Task addTask(String description) {
        Task task = new Task(description);
        return taskRepository.save(task);
    }

    public void deleteTask(Long id) {
        taskRepository.deleteById(id);
    }

    public Task markTaskAsCompleted(Long id) {
        Task task = taskRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid task ID"));
        task.setCompleted(true);
        return taskRepository.save(task);
    }
}

控制器层

        ‘TaskController‘类处理HTTP请求并返回视图:

package com.example.taskmanager.controller;


import com.example.taskmanager.entity.Task;
import com.example.taskmanager.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


@Controller
public class TaskController {
    private final TaskService taskService;

    @Autowired
    public TaskController(TaskService taskService) {
        this.taskService = taskService;
    }

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("tasks", taskService.getAllTasks());
        return "index";
    }

    @PostMapping("/add")
    public String addTask(@RequestParam String description) {
        taskService.addTask(description);
        return "redirect:/";
    }

    @PostMapping("/delete")
    public String deleteTask(@RequestParam Long id) {
        taskService.deleteTask(id);
        return "redirect:/";
    }

    @PostMapping("/complete")
    public String completeTask(@RequestParam Long id) {
        taskService.markTaskAsCompleted(id);
        return "redirect:/";
    }
}

前端视图

        在‘src/main/resources/templates‘目录下创建‘index.html‘文件:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Task Manager</title>
    <link rel="stylesheet" type="text/css" href="/static/style.css"/>
</head>

<body>
    <h1>Task Manager</h1>
    <form action="/add" method="post">
        <input type="text" name="description" placeholder="Enter task description" required/>
        <button type="submit">Add Task</button>
    </form>

    <table>
        <thead>
            <tr>
                <th>Description</th>
                <th>Completed</th>
                <th>Actions</th>
            </tr>
        </thead>

        <tbody>
            <tr th:each="task : ${tasks}">
                <td th:text="${task.description}">Task Description</td>
                <td th:text="${task.completed}">false</td>
                <td>
                    <form action="/complete" method="post" th:if="${!task.completed}">
                        <input type="hidden" name="id" th:value="${task.id}"/>
                        <button type="submit">Complete</button>
                    </form>

                    <form action="/delete" method="post">
                        <input type="hidden" name="id" th:value="${task.id}"/>
                        <button type="submit">Delete</button>
                    </form>
                </td>
            </tr>
        </tbody>
    </table>
</body>
</html>

配置文件

        在‘src/main/resources‘目录下创建‘application.properties‘文件,配置H2数据库:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true

启动应用

        ‘TaskManagerApplication‘类是Spring Boot应用的入口,包含‘main‘方法:

package com.example.taskmanager;


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


@SpringBootApplication
public class TaskManagerApplication {

    public static void main(String[] args) {
        SpringApplication.run(TaskManagerApplication.class, args);
    }
}

总结

        通过本篇博客,我们开发了一个简单的Java Web应用——任务管理系统。该应用展示了如何使用Spring Boot框架创建Web应用、处理HTTP请求、与数据库交互以及进行简单的前端开发。通过这个项目,你不仅熟悉了Spring Boot的基本用法,还掌握了如何设计和实现一个实际的Web应用。希望你能通过这个项目进一步提升Java Web开发技能,为将来的复杂项目打下坚实的基础。祝你学习愉快,不断进步!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

白骑士所长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值