springboot整合jdbc-实现添加用户
-
创建实体类(pojo/Users)
public class Users { private Integer id; private String username; private String usersex; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUsersex() { return usersex; } public void setUsersex(String usersex) { this.usersex = usersex; } }
-
编写页面(resources/templates/addUser.html)
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form th:action="@{/user/addUser}" method="post"> <input type="text" name="username"><br> <input type="text" name="usersex"><br> <input type="submit" value="ok"> </form> </body> </html>
-
创建PageController(controller/PageController)
//页面跳转controller @Controller public class PageController { //页面跳转方法 @RequestMapping("/{page}") public String showPage(@PathVariable String page){ return page; } }
-
创建UsersController(controller/UsersController)
@Controller @RequestMapping("/user") public class UsersController { @Autowired private UsersService usersService; @PostMapping("/addUser") public String showInfo(Users users){ try{ this.usersService.addUser(users); }catch (Exception e){ e.printStackTrace(); return "error"; } return "redirect:/ok"; } }
-
编写service接口和实现类
(service/UsersService)
public interface UsersService { void addUser(Users users); }
(service/impl/UsersServiceImpl)
//用户管理业务层 @Service public class UsersServiceImpl implements UsersService { @Autowired private UsersDao usersDao; //添加用户 @Override @Transactional public void addUser(Users users) { this.usersDao.insertUsers(users); } }
-
编写dao接口和实现类
(dao/UsersDao)
public interface UsersDao { void insertUsers(Users users); }
(dao/impl/UsersDaoImpl)
//持久层 @Repository public class UsersDaoImpl implements UsersDao { @Autowired private JdbcTemplate jdbcTemplate; //添加用户 @Override public void insertUsers(Users users) { String sql = "insert into users(username,usersex) value(?,?)"; this.jdbcTemplate.update(sql,users.getUsername(),users.getUsersex()); } }