超详细的Java Web开发

Java Web开发是一个广泛的主题,涉及多个方面,包括前端技术、后端框架、数据库交互、部署等。下面是一个详细的Java Web开发框架,包括从项目搭建到具体代码实现的全过程。

Java Web开发框架

1. 环境搭建
1.1 安装开发工具
  • IDE:IntelliJ IDEA 或 Eclipse
  • 服务器:Apache Tomcat
  • 数据库:MySQL
  • 版本控制:Git
1.2 创建项目
  • 使用IntelliJ IDEA或Eclipse创建一个新的Maven项目。
  • 添加必要的依赖项,例如Spring Boot、Spring MVC、MyBatis、Thymeleaf等。

2. 项目结构

my-web-app
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── example
│   │   │           ├── controller
│   │   │           ├── service
│   │   │           ├── dao
│   │   │           └── model
│   │   ├── resources
│   │   │   ├── application.properties
│   │   │   └── mapper
│   │   └── webapp
│   │       └── WEB-INF
│   │           └── views
│   └── test
│       └── java
│           └── com
│               └── example
└── pom.xml

3. 依赖管理

pom.xml中添加必要的依赖项:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>my-web-app</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <!-- Spring Boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- MySQL Connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- Thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- MyBatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

4. 配置文件

application.properties
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

5. 实体类

User.java
package com.example.model;

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

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;

    // Getters and Setters
}

6. 数据访问对象(DAO)

UserMapper.java
package com.example.dao;

import com.example.model.User;
import org.apache.ibatis.annotations.*;

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM user WHERE id = #{id}")
    User findById(@Param("id") Long id);

    @Insert("INSERT INTO user(name, email) VALUES(#{name}, #{email})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(User user);

    @Update("UPDATE user SET name=#{name}, email=#{email} WHERE id=#{id}")
    void update(User user);

    @Delete("DELETE FROM user WHERE id=#{id}")
    void deleteById(@Param("id") Long id);
}

7. 服务层

UserService.java
package com.example.service;

import com.example.dao.UserMapper;
import com.example.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public User findById(Long id) {
        return userMapper.findById(id);
    }

    public void save(User user) {
        if (user.getId() == null) {
            userMapper.insert(user);
        } else {
            userMapper.update(user);
        }
    }

    public void deleteById(Long id) {
        userMapper.deleteById(id);
    }
}

8. 控制器

UserController.java
package com.example.controller;

import com.example.model.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public String listUsers(Model model) {
        // 假设有一个方法可以获取所有用户
        model.addAttribute("users", userService.findAll());
        return "users/list";
    }

    @GetMapping("/{id}")
    public String showUser(@PathVariable Long id, Model model) {
        User user = userService.findById(id);
        model.addAttribute("user", user);
        return "users/show";
    }

    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("user", new User());
        return "users/add";
    }

    @PostMapping("/add")
    public String addUser(@ModelAttribute User user) {
        userService.save(user);
        return "redirect:/users";
    }

    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Long id, Model model) {
        User user = userService.findById(id);
        model.addAttribute("user", user);
        return "users/edit";
    }

    @PostMapping("/edit/{id}")
    public String editUser(@PathVariable Long id, @ModelAttribute User user) {
        user.setId(id);
        userService.save(user);
        return "redirect:/users";
    }

    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable Long id) {
        userService.deleteById(id);
        return "redirect:/users";
    }
}

9. 视图层

list.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>User List</title>
</head>
<body>
    <h1>User List</h1>
    <a href="/users/add">Add User</a>
    <table>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Actions</th>
        </tr>
        <tr th:each="user : ${users}">
            <td th:text="${user.id}"></td>
            <td th:text="${user.name}"></td>
            <td th:text="${user.email}"></td>
            <td>
                <a th:href="@{/users/edit/{id}(id=${user.id})}">Edit</a>
                <a th:href="@{/users/delete/{id}(id=${user.id})}">Delete</a>
            </td>
        </tr>
    </table>
</body>
</html>
add.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Add User</title>
</head>
<body>
    <h1>Add User</h1>
    <form th:action="@{/users/add}" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required><br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required><br>
        <button type="submit">Save</button>
    </form>
</body>
</html>

10. 部署

  1. 打包:使用Maven打包命令生成WAR文件。

    mvn clean package
  2. 部署:将生成的WAR文件部署到Tomcat服务器。

    • 将WAR文件复制到Tomcat的webapps目录。
    • 启动Tomcat服务器。

11. 运行项目

  1. 启动Tomcat:确保Tomcat服务器正在运行。
  2. 访问应用:在浏览器中访问http://localhost:8080/users,你应该能看到用户列表页面。

你可以搭建一个完整的Java Web应用,包括前端页面、后端服务、数据库交互和部署。希望这些内容对你有所帮助,给个赞和关注支持一下,收藏备用

猜你喜欢

转载自blog.csdn.net/speaking_me/article/details/143080858