确保在你的项目中引入Spring、Spring MVC、MyBatis等相关依赖。
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.8.RELEASE</version>
</dependency>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.8.RELEASE</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
在application.properties
或application.yml
中配置数据库连接和MyBatis。
# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/family_service
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# MyBatis配置
mybatis.type-aliases-package=com.example.familymanagement.domain
mybatis.mapper-locations=classpath:/mapper/*.xml
// User.java
public class User {
private Long id;
private String username;
private String password;
// getters and setters
}
// UserMapper.java
public interface UserMapper {
User getUserByUsername(String username);
void addUser(User user);
void updateUser(User user);
void deleteUser(Long id);
}
5.创建Controller层
// UserController.java
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/login")
public String login() {
return "login"; // 返回登录页面视图名
}
@PostMapping("/login")
public String login(@RequestParam String username, @RequestParam String password, Model model) {
User user = userService.getUserByUsername(username);
if (user != null && user.getPassword().equals(password)) {
model.addAttribute("user", user);
return "home"; // 登录成功,返回首页视图名
} else {
model.addAttribute("error", "用户名或密码错误");
return "login"; // 登录失败,返回登录页面视图名
}
}
@GetMapping("/add")
public String addUserForm() {
return "add_user"; // 返回添加用户页面视图名
}
@PostMapping("/add")
public String addUser(@ModelAttribute User user) {
userService.addUser(user);
return "redirect:/user/login"; // 添加用户成功后重定向到登录页面
}
@GetMapping("/edit/{id}")
public String editUserForm(@PathVariable Long id, Model model) {
User user = userService.getUserById(id);
model.addAttribute("user", user);
return "edit_user"; // 返回编辑用户页面视图名
}
@PostMapping("/edit")
public String editUser(@ModelAttribute User user) {
userService.updateUser(user);
return "redirect:/user/login"; // 编辑用户成功后重定向到登录页面
}
@GetMapping("/delete/{id}")
public String deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return "redirect:/user/login"; // 删除用户成功后重定向到登录页面
}
}