springboot项目整合本地mysql—练习用
背景
用于初识 springboot + mysql 整合项目。
springboot + maven 配置
<!--添加JDBC依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
application.yml 文件配置mysql连接数据
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/text?useSSL=false
username: xxxx
password: xxxx
springboot入口
@SpringBootApplication
public class RunApplication {
public static void main(String[] args) {
SpringApplication.run(RunApplication.class, args);
}
}
创建操作数据库接口
public interface UserService {
public void insert(String username,String password);
}
创建实体类实现 UserService
@Service
public class UserServiceImp implements UserService{
@Autowired
private JdbcTemplate jdbcTemplate;
public void insert(String username, String password) {
jdbcTemplate.update("insert into usersheet(username,password) values(?,?)",username,password);
}
}
创建操作mysql逻辑方法
@RestController
public class UserController {
@Autowired
private UserServiceImp userServiceImp;
@RequestMapping(value = "/createuserdata",method = RequestMethod.POST)
@ResponseBody
public CreateClass crteaeUser(@RequestBody CreateClass createClass){
String username = createClass.getUsername();
String password = createClass.getPassword();
userServiceImp.insert(username,password);
String content = "创建成功。";
createClass.setContent(content);
return createClass;
}
}
ajax 发送请求
function cilickP01(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
if (this.readyState==4 && this.status==200){
resultJson = JSON.parse(this.responseText);
var content = resultJson["content"];
document.getElementById("span01").innerHTML=content;
}
}
var username = document.getElementById("input01").value;
var password = document.getElementById("input02").value;
var url = "/createuserdata";
data = JSON.stringify({"username":username,"password":password});
xhr.open("post",url);
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(data);
}
数据库验证
SELECT * FROM usersheet;