springboot+mybatis+thymeleaf增删改查及前后端交互
准备工作
目录结构
pom.xml文件 都是在创建springboot项目的时候勾选的 无需后续导入依赖包
创建mysql表
编写配置文件application.yml
spring:
thymeleaf:
prefix: classpath:/templates/
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.0.103:3306/user
driver-class-name: com.mysql.cj.jdbc.Driver
initialization-mode: always
type: com.alibaba.druid.pool.DruidDataSource
导入html文件
编写实体类 User
public class User {
private Integer id;
private String name;
private String gender;
private Integer age;
private String address;
private String qq;
private String email;
}
功能实现
编写mapper层实现CRUD语句的Usermapper
@Mapper
public interface UserMapper {
@Select("select * from user")
public List<User> getAllUser();
@Select("select * from user where id=#{id}")
public User getUserById(Integer id);
@Delete("delete from user where id=#{id}")
public int delUserById(Integer id);
@Update("update user set gender=#{gender},age=#{age},address=#{address},qq=#{qq},email=#{email} where name=#{name}")
public int UpdateUser(User user);
@Options(useGeneratedKeys = true,keyProperty = "id")//是指定主键生成的并且主键是id
@Insert("insert into user(name,gender,age,address,qq,email) values (#{name},#{gender},#{age},#{address},#{qq},#{email})")
public int InsertUser(User user);
}
编写service层的UserService
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public List<User> userList(){
return userMapper.getAllUser();
}
public int insert(User user){
return userMapper.InsertUser(user);
}
public int delete(Integer id){
return userMapper.delUserById(id);
}
public int update(User user){
return userMapper.UpdateUser(user);
}
public User getById(Integer id){
return userMapper.getUserById(id);
}
}
编写controller层的UserController
@Controller
public class UserController {
@Autowired
UserService userService;
@RequestMapping("/index")
public String index(){
return "index";
}
/*查询用户列表*/
@RequestMapping("/list")
public String userList(Model model){
model.addAttribute("users",userService.userList());
return "list";
}
/*删除用户*/
@RequestMapping("/del")
public String deleteUser(Integer id){
userService.delete(id);
return "redirect:/list";
}
/*添加用户页面*/
@RequestMapping("/add")
public String addUser(ModelMap map){
map.addAttribute("user",new User());
return "add";
}
/*更新用户页面*/
@RequestMapping("/update")
public String updateUser(ModelMap map){
map.addAttribute("user",new User());
return "update";
}
/*添加完用户后重定向到list页面*/
@RequestMapping("/saveI")
public String saveI(@ModelAttribute User user){
userService.insert(user);
return "redirect:/list";
}
/*更新完用户后重定向到list页面*/
@RequestMapping("/saveU")
public String saveU(@ModelAttribute User user){
userService.update(user);
return "redirect:/list";
}
修改list.html
使用th:each循环把查询到的用户列表展示出来
修改删除添加按钮都加上在controller层写的映射地址以及跳转地址
修改add.html文件 即选择添加联系人后跳转的页面
修改update.html文件,即选择修改后跳转的页面