本文内容,基于前面文章基础之上编写,如果搭建环境这些不知道,可以查看前面的。
1 springboot入门之 Hello World
2 springboot入门之 整合thymeleaf
添加pom依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
properties中配置DataSource
spring.datasource.url=jdbc:mysql://localhost:3306/test01?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
编写dao层,service层。
- dao接口
public interface UserDao {
Integer addUser(String name, Integer age);
}
- dao 实现类
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Integer addUser(String name, Integer age) {
return jdbcTemplate.update("INSERT INTO USER VALUES (null,?,?);", name, age);
}
}
- service接口
public interface UserService {
int addUser(String name, Integer age);
}
- service实现类
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public int addUser(String name, Integer age) {
try {
return userDao.addUser(name,age);
}catch (Exception e){
e.printStackTrace();
return 0;
}
}
}
创建mysql数据库和表
-- 创建数据库
CREATE DATABASE test01 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
-- 创建用户表
CREATE TABLE user(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(30),
age INT
);
完成controller和页面
UserController.java
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@RequestMapping(value = "/")
public String user() {
return "/user";
}
@ResponseBody
@RequestMapping(value = "/addUser")
public Map<String, Object> addUser(@RequestParam(name = "uname") String name, @RequestParam(name = "age") Integer age) {
Map<String, Object> map = new HashMap<>();
int count = userService.addUser(name, age);
map.put("name", name);
map.put("age", age);
map.put("msg", "操作" + (count > 0 ? "成功" : "失败"));
return map;
}
}
user.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户界面</title>
</head>
<body>
<h2>添加用户</h2>
<form method="post" action="./addUser">
<label>用户名:</label><input type="text" name="uname">
<label>年龄:</label><input type="number" name="age">
<input type="submit" value="添加"/>
</form>
</body>
</html>