一个简单的Spring Boot应用的基础结构示例,以及如何设置一个基本的旅游管理系统。这个例子将包含用户注册和登录的基本功能。
首先,你需要设置一个新的Spring Boot项目。可以通过Spring Initializr网站(https://start.spring.io/)来快速生成一个基础项目结构,选择必要的依赖项,比如Web、Thymeleaf、Spring Data JPA 和 MySQL Driver。
接下来是项目的基本目录结构:
travel-management-system/
├── src/main/java/com/example/travelmanagementsystem
│ ├── application.properties
│ ├── controller
│ │ └── UserController.java
│ ├── entity
│ │ └── User.java
│ ├── repository
│ │ └── UserRepository.java
│ └── service
│ └── UserService.java
└── src/main/resources
├── application.properties
└── data.sql
application.properties
(在src/main/resources
下)
properties
spring.datasource.url=jdbc:mysql://localhost:3306/travel_management_system?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
User.java
(在entity
包下)
java
package com.example.travelmanagementsystem.entity;
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 username;
private String password;
// Getters and Setters
}
UserRepository.java
(在repository
包下)
java
package com.example.travelmanagementsystem.repository;
import com.example.travelmanagementsystem.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
UserService.java
(在service
包下)
java
package com.example.travelmanagementsystem.service;
import com.example.travelmanagementsystem.entity.User;
import com.example.travelmanagementsystem.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User save(User user) {
return userRepository.save(user);
}
public User findByUsername(String username) {
return userRepository.findByUsername(username);
}
}
UserController.java
(在controller
包下)
java
package com.example.travelmanagementsystem.controller;
import com.example.travelmanagementsystem.entity.User;
import com.example.travelmanagementsystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/register")
public User register(@RequestBody User user) {
return userService.save(user);
}
@GetMapping("/{username}")
public User getUserByUsername(@PathVariable String username) {
return userService.findByUsername(username);
}
}
以上代码提供了一个非常基础的用户注册和查询的功能。为了完成一个完整的旅游管理系统,还需要增加更多的功能模块,比如旅游线路管理、订单管理等,并且需要编写前端页面与后端交互。此外,还需要考虑安全性、异常处理、日志记录等方面的问题。