做自己没做过的事情叫做成长
做自己不愿做的事情叫做改变
做自己不敢做的事情叫做突破
共勉
目录结构
实体类
@Data
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String sex;
private Integer gradeId;
}
服务层
接口
public interface StudentService {
/**
* 新增
* @param student 新增对象
* @return springData提供的方法是返回的对象,所以我们也需要返回对象
*/
Student save(Student student);
/**
* 修改
* @param student 修改对象
* @return springData提供的方法是返回的对象,所以我们也需要返回对象
*/
Student update(Student student);
/**
* 删除
* @param id 根据id删除
*/
void delete(Integer id);
/**
* 分页
* @param page 页码
* @param size 每页数量
* @param student 用于存储模糊查询参数
* @return
*/
Page<Student> findByPage(Integer page, Integer size, Student student);
/**
* 通过id 查询
* @param id 根据id查询,用于修改
* @return springData提供的方法是返回的对象,所以我们也需要返回对象
*/
Student findById(Integer id);
}
实现类
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
/**
* 新增
* @param student 新增对象
* @return springData提供的方法是返回的对象,所以我们也需要返回对象
*/
@Override
public Student save(Student student) {
return studentDao.save(student);
}
/**
* 修改
* @param student 修改对象
* @return springData提供的方法是返回的对象,所以我们也需要返回对象
*/
@Override
public Student update(Student student) {
return studentDao.save(student);
}
/**
* 删除
* @param id 根据id删除
*/
@Override
public void delete(Integer id) {
studentDao.deleteById(id);
}
/**
* 分页
* @param page 页码
* @param size 每页数量
* @param student 用于存储模糊查询参数
* @return
*/
@Override
public Page<Student> findByPage(Integer page, Integer size, Student student) {
//模糊查询,需要注意的是 name要和你所需要查询的字段名相同
ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("name",ExampleMatcher.GenericPropertyMatchers.startsWith());
// Example.of(student,matcher);因为第一个参数只能是对象,所以我们需要用对象存储查询条件
Example<Student> studentExample = Example.of(student,matcher);
//分页初始化
PageRequest request = PageRequest.of(page, size);
//分页查询
Page<Student> studentPage =studentDao.findAll(studentExample,request);
return studentPage;
}
/**
* 通过id 查询
* @param id 根据id查询,用于修改
* @return springData提供的方法是返回的对象,所以我们也需要返回对象
*/
@Override
public Student findById(Integer id) {
return studentDao.findById(id).get();
}
}
dao层
public interface StudentDao extends JpaRepository<Student,Integer> {
}
控制层
@RestController
@RequestMapping("/student")
@Api(value = "swagger ui 注释 api 级别")
public class StudentController {
@Autowired
private StudentService studentService;
/**
* 页面跳转
* @return
*/
@RequestMapping("/add")
@ApiOperation(value = "跳转到增加页面",notes = "跳转到增加页面")
public String add(){
return "add";
}
/**
* 新增
*
* @param student
* @return
*/
@RequestMapping("/save")
@ApiOperation(value = "新增学生",notes = "")
public Student save(@RequestBody Student student) {
System.out.println(student);
return studentService.save(student);
}
/**
* 修改
*
* @param student
* @return
*/
@ApiOperation(value = "修改学生",notes = "")
@RequestMapping("/update")
public Student update(Student student) {
return studentService.save(student);
}
/**
* 删除
*
* @param id
*/
@RequestMapping("/delete")
@ApiOperation(value = "删除学生",notes = "")
public int delete(Integer id) {
try {
studentService.delete(id);
return 1;
} catch (Exception e) {
e.printStackTrace();
return 2;
}
}
/**
* 分页
* 在服务层我已经表明的很清楚啦,就不再一一解释了
* @param page
* @param size
* @return
*/
@RequestMapping("/findByPage")
@ApiOperation(value = "分页查询",notes = "")
public Page<Student> findByPage(Integer page, Integer size, Student student) {
if (page == null) {
page = 0; //初始化页码,注意他是从0开始
}
if (size == null) {
size = 3; //初始化每页条数
}
Page<Student> byPage = studentService.findByPage(page, size,student);
return byPage;
}
/**
* 通过id 查询
*
* @param id
* @return
*/
@RequestMapping("/findById")
@ApiOperation(value = "id查询",notes = "")
public Student findById(Integer id) {
Student byId = studentService.findById(id);
return byId;
}
}
swagger2的配置
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.student.controller"))
.paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot整合Swagger2生产接口文档")
.description("如果前端妹子看不懂可随时来询问我")
.termsOfServiceUrl("https://blog.csdn.net/I_No_dream")
.contact("name")
.version("2.2")
.build();
}
}
解决跨域问题
@Configuration
public class WebConfig implements WebMvcConfigurer {
//跨域配置
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
//重写父类提供的跨域请求处理的接口
public void addCorsMappings(CorsRegistry registry) {
//添加映射路径
registry.addMapping("/**")
//放行哪些原始域
.allowedOrigins("*")
//是否发送Cookie信息
.allowCredentials(true)
//放行哪些原始域(请求方式)
.allowedMethods("GET", "POST", "PUT", "DELETE")
//放行哪些原始域(头部信息)
.allowedHeaders("*")
//暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
.exposedHeaders("Header1", "Header2");
}
};
}
}
main函数
@SpringBootApplication
@EnableSwagger2
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
配置文件
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: 123456
jpa:
show-sql: true #显示sql语句
hibernate:
ddl-auto: update
naming:
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
database: mysql #配置现在所使用的数据库
pom.xml文件
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--接口文档生产-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
html页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<table border="1" cellpadding="5">
<tr>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>年纪</th>
<th>操作</th>
</tr>
<template v-for="student in students.content">
<tr>
<td>{{student.id}}</td>
<td>{{student.name}}</td>
<td>{{student.sex}}</td>
<td>{{student.gradeId}}</td>
<td>
<a href="#" @click="Delete(student.id)">刪除</a>
<a href="#" @click="Edit(student)">編輯</a>
</td>
</tr>
</template>
<template>
<tr>
<td><input type="text" placeholder="不需要再见填充" readonly="readonly" v-model="student.id" /></td>
<td><input type="text" placeholder="请输入用户名" v-model="student.name" /></td>
<td><input type="text" placeholder="请输入性别" v-model="student.sex" /></td>
<td><input type="text" placeholder="请输入年纪" v-model="student.gradeId" /></td>
<td>
<button type="button" @click="save()">保存</button>
</td>
</tr>
</template>
</table>
第<span v-text="students.number+1"></span>页/共<span v-text="students.totalPages"></span>页<br />
<a href="#" @click="pageJump(0)">首页</a>
<a href="#" @click="pageJump(students.number-1)">上一页</a>
<a href="#" @click="pageJump(students.number+1)">下一页</a>
<a href="#" @click="pageJump(students.totalPages-1)">尾页</a>
</div>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
student: {
id: '',
name: '',
sex: '',
gradeId: ''
},
students: [],
page: 0
},
methods: {
findAll: function(page) {
var _this = this;
axios.get("http://localhost:8080/student/findByPage", {
params: {
page: page
}
})
.then(function(res) {
_this.students = res.data;
})
.catch(function(err) {
console.log(err);
})
},
save: function() {
var _this = this;
var student = JSON.stringify(_this.student);
if (student.id != null && student.id != '') {
this.student = s;
axios.put("http://localhost:8080/student/update", student, {
headers: {
"Content-Type": "application/json;charset=utf-8"
}
})
.then(function(res) {
_this.student.name = null;
_this.student.sex = null;
_this.student.gradeId = null;
_this.findAll();
})
.catch(function(err) {
console.log(err);
});
} else {
axios.post("http://localhost:8080/student/save", student, {
headers: {
"Content-Type": "application/json;charset=utf-8"
}
})
.then(function(res) {
_this.student.name = null;
_this.student.sex = null;
_this.student.gradeId = null;
_this.findAll();
})
.catch(function(err) {
console.log(err);
});
}
},
Delete: function(sid) {
var _this = this;
axios.delete("http://localhost:8080/student/delete", {
params: {
id: sid
}
})
.then(function(res) {
_this.findAll();
})
.catch(function(err) {
console.log(err);
})
},
Edit:function(student){
this.student = student;
},
pageJump:function(number){
this.findAll(number);
}
},
created: function() {
this.findAll();
}
})
</script>
</body>
</html>