一、实现启动打开html页面
创建项目后,给 application.yml(或 application.properties )配置基本的端口和访问路径(下面是 .yml 格式的配置文件)
server:
port: 8080
servlet:
context-path: /springbootTest # 访问的根路径,访问某个文件时需要写入根路径:localhost:8080/springbootTest
注入要用到的依赖,注入到 pom.xml 的中(亦可以在新建项目时选择好要注入的依赖)
<!-- 得到一个可执行的基于SpringMVC 的web应用;影响@RequestMapping等注解的使用-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
在 resources 下新建一个 templates 文件夹,在 templates 下新建一个html文件,命名为index
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>indexTest</title>
</head>
<body>
进入index页面
</body>
</html>
在 com.example.springbootdemo 下新建一个 java 文件,用来打开 index.html 页面,命名为 indexTest;并加入注解实现
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller //访问页面
public class indexTest {
//访问页面
@RequestMapping("/hello")
public String hello(){
return "index";
}
}
启动项目,在浏览器输入路径:localhost:8080/springbootTest/hello 即可访问到 index.html 页面
二、实现简单的crud(增删查改)
在 com.example.springbootdemo 下新建 po ,新建 Student.java 实体类
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Student {
private String stuName;
private String stuWord;
@Id
@GeneratedValue //字段自增则要加这个注解
private Integer stuId;
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuWord() {
return stuWord;
}
public void setStuWord(String stuWord) {
this.stuWord = stuWord;
}
public Integer getStuId() {
return stuId;
}
public void setStuId(Integer stuId) {
this.stuId = stuId;
}
}
1.@Entity:对实体注释。任何Hibernate映射对象都要有这个注释
2.@Id:声明此属性为主键。该属性值可以通过应该自身创建,但是Hibernate推荐通过Hibernate生成
3.@GeneratedValue:指定主键的生成策略;默认自增
在 application.yml(或 application.properties )配置数据库池、数据库操作
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: "jdbc:mysql://localhost:3306/user?useSSL=false&serverTimezone=UTC"
username: "root"
password: "root"
jpa:
hibernate:
ddl-auto: update # 自动更新(没表建立表后更新,有表直接更新)
show-sql: true # 显示出操作时使用到的sql语句
thymeleaf:
prefix: classpath:/templates/
suffix: .html
cache: false
1.JPA:顾名思义就是Java Persistence API的意思,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。
个人理解:就是实现数据库的相关操作
2.Thymeleaf:是一款模板引擎。它不同于一般地在模板里编码实现逻辑,而是利用了XML标签和属性,由模板引擎来执行这些DOM上预定义好的逻辑。
个人理解:就是实现前端页面获得后端传过来的内容
注入依赖到 pom.xml 的中(亦可以在新建项目时选择好要注入的依赖)
<!-- thymeleaf模板 如果用到就导入-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Spring data jpa :实现数据库相关操作-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL数据库驱动版本-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
在 com.example.springbootdemo 下新建 repository 文件夹,新建一个接口 StudentRepository
import com.example.demo.po.Student;
import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentRepository extends JpaRepository<Student,Integer> {
}
新建 Crud.java 文件实现crud操作
import com.example.demo.po.Student;
import com.example.demo.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class Crud {
@Autowired
private StudentRepository studentRepository;
@RequestMapping(value = "/save" , method = RequestMethod.GET)
public void save(@RequestParam("stuName") String username,@RequestParam("stuWord") String password){
Student student = new Student();
student.setStuName(username);
student.setStuWord(password);
studentRepository.save(student); // 返回 实体类 类型的方法
}
@RequestMapping(value = "/delete" , method = RequestMethod.GET)
public void delete(@RequestParam("iD") Integer id){
Student student = new Student();
student.setStuId(id);
studentRepository.delete(student); // void 类型的方法
}
@RequestMapping(value = "/find" , method = RequestMethod.GET)
public List<Student> find(){
List<Student> data = studentRepository.findAll();
return data;
}
@RequestMapping(value = "/revise", method = RequestMethod.GET)
public void revise(@RequestParam("iD") Integer id , @RequestParam("stuName") String stuName , @RequestParam("stuWord") String stuWord){
Student student = new Student();
student.setStuId(id);
student.setStuName(stuName);
student.setStuWord(stuWord);
studentRepository.save(student);
}
@RequestMapping(value = "/findPage" , method = RequestMethod.GET)
public String findByPage(){
Pageable pageable = new PageRequest(0,5);
Page<Student> datas = studentRepository.findAll(pageable);
String result = "";
result+="总条数:"+datas.getTotalElements()+"<br>";
result+="总页数:"+datas.getTotalPages()+"<br>";
for (Student s :datas) {
result+=s.getStuId()+" || "+s.getStuName()+" || "+s.getStuWord()+"<br>";
}
return result;
}
}
在 indexTest.java 里添加一个方法来跳转到 crud.html
通过 request.setAttribute 传内容到 crud.html ,页面再根据th:xxx="${yyy}"拿到内容
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
@RequestMapping("/crud")
public String crud(HttpServletRequest request){
request.setAttribute("add","/springbootTest/save");
request.setAttribute("delete","/springbootTest/delete");
request.setAttribute("find","/springbootTest/find");
request.setAttribute("findpage","/springbootTest/findPage");
request.setAttribute("revise","/springbootTest/revise");
return "crud";
}
新建 crud.html 到 templates 中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CRUD操作</title>
</head>
<body>
<div id="all-content">
<p>userName: <input type="text" name="stuName" id="add-name"></p>
<p>passWord: <input type="password" name="stuWord" id="add-word"></p>
<p><input id="add" type="button" value="添加" th:url="${add}" v-on:click="add()"></p>
<hr>
<p>ID:<input type="text" name="iD" id="del-id"></p>
<p><input id="delete" type="button" value="根据id删除一个学生实体类" th:url="${delete}" v-on:click="deleteByStudent()"></p>
<hr>
<p><input id="find" type="button" value="查找全部" th:url="${find}" v-on:click="find()"></p>
<hr>
<p><input id="findpage" type="button" value="分页查找" th:url="${findpage}" v-on:click="findpage()"></p>
<hr>
<p>ID: <input type="text" name="iD" id="re-id"></p>
<p>stuName: <input type="text" name="stuName" id="re-name"></p>
<p>newPWD: <input type="password" name="newPWD" id="re-word"></p>
<p><input id="revise" type="button" value="根据id修改学生信息" th:url="${revise}" v-on:click="revise()"></p>
<hr>
<table id="show-data" border="1px">
<tr>
<td>Id</td>
<td>姓名</td>
<td>密码</td>
</tr>
<tr v-for="datas in allData">
<td>{{datas.stuId}}</td>
<td>{{datas.stuName}}</td>
<td>{{datas.stuWord}}</td>
</tr>
</table>
<p id="show-page-data"></p>
</div>
</body>
<script type="text/javascript" th:src="@{/js/jquery.3.3.1.js}"></script>
<script type="text/javascript" th:src="@{/js/vue.min.js}"></script>
<script ype="text/javascript">
var vm = new Vue({
el:'#all-content',
data:{
allData:''
},
methods:{
find:function(){
that = this;
var url = $('#find').attr('url');
$.ajax({
url:url,
type:'GET',
success:function(data){
that.allData = data;
},
error:function(res){
console.log("res:"+res);
}
})
},
add:function(){
that = this;
var url = $('#add').attr('url');
var name = $('#add-name').val();
var word = $('#add-word').val();
$.ajax({
url:url,
type:'GET',
data:{
stuName:name,
stuWord:word
},
success:function(data){
that.find();
},
error:function(res){
console.log("res:"+res);
}
})
},
deleteByStudent:function(){
that = this;
var url = $('#delete').attr('url');
var id = $('#del-id').val();
$.ajax({
url:url,
type:'GET',
data:{
iD:id
},
success:function(data){
that.find();
},
error:function(res){
console.log("res:"+res);
}
})
},
findpage:function(){
var url = $('#findpage').attr('url');
$.ajax({
url:url,
type:'GET',
success:function(data){
$('#show-page-data').text(data);
},
error:function(res){
console.log("res:"+res);
}
})
},
revise:function(){
that = this;
var url = $('#revise').attr('url');
var id = $('#re-id').val();
var name = $('#re-name').val();
var word = $('#re-word').val();
$.ajax({
url:url,
type:'GET',
data:{
iD:id,
stuName:name,
stuWord:word
},
success:function(data){
that.find();
},
error:function(res){
console.log("res:"+res);
}
})
}
},
created:function(){
this.find();
}
})
</script>
</html>
这里注意引入js外部文件,是通过 thymeleaf 模板的方式引入
启动项目,在浏览器输入路径:localhost:8080/springbootTest/crud 即可访问到 crud.html 页面
三、自定义数据操作
当简单的数据库操作无法满足要求时,可以自己自定义数据库操作
在接口 StudentRepository 中自定义方法
使它继承 JpaRepository ,就可以自定义数据库操作方法了,不过它有一定格式要求,由:“操作类型+根据什么属性进行操作” 组成。如下:根据学生ID删除学生
public interface StudentRepository extends JpaRepository<Student,Integer> {
public void deleteByStuId(Integer id); //自定义数据库操作方法(根据学生Id删除学生信息)
}
在 indexTest.java 中添加对应操作代码
request.setAttribute("deletebyid","/springbootTest/deleteById");
在 Crud.java 中添加对应操作代码
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping(value = "/deleteById" , method = RequestMethod.GET)
public void deleteById(@RequestParam("iD") Integer id){
studentRepository.deleteById(id); // void 类型的方法
}
在 crud.html 中添加对应操作代码
<p>ID:<input type="text" name="iD" id="delbyid-id"></p>
<p><input id="deletebyid" type="button" value="根据id删除其对应的信息(自定义方法)" th:url="${deletebyid}" v-on:click="deletebyid()"></p>
// vue 里面的 methods 中的一个方法
...
deletebyid:function(){
that = this;
var url = $('#deletebyid').attr('url');
var id = $('#delbyid-id').val();
$.ajax({
url:url,
type:'GET',
data:{
iD:id
},
success:function(data){
that.find();
},
error:function(res){
console.log("res:"+res);
}
})
}
...
启动项目,在浏览器输入路径:localhost:8080/springbootTest/crud 即可访问到 crud.html 页面
注意事项
- 注意导入的包,不要导错包
- 注意编码格式统一,不然会出现编码格式不统一导致无法运行