Spring Boot项目快速创建-开发流程(笔记)
紧张流程:前端发送网络哀求->controller->调用service->利用mapper->操作数据库->对entity数据对象赋值->返回前端
前期预备:
maven、mysql下载好
跟学视频,感谢老师: https://www.bilibili.com/video/BV1gm411m7i6/?share_source=copy_web&vd_source=92d754038ee61d01dacfbb2bacae8320
打点:
00:00 - 42:53 GET接口
42:54 - 51:24 POST接口
51:25 - 54:20 DELETE接口
54:21 - 1:02:11 UPDATE接口
1:02:17 - 1:04:22 打包
一、项目创建
初始化Spring boot应用:Spring Initializr
配置好以下内容(根据实际环境选择java版本) ,点GENERATE天生项目。
https://i-blog.csdnimg.cn/direct/ca6e00ef8d4e4c7a9461b998eeb972a2.png
解压项目之后,idea打开open,导入项目标pom.xml文件。
https://i-blog.csdnimg.cn/direct/d93c7aa6957b406ea9889b9c2aa88d1d.png https://i-blog.csdnimg.cn/direct/60d794ac8c5e4998867199273c9b1ead.png
https://i-blog.csdnimg.cn/direct/744b6b538e6744a2a9d12e6e0cf2b90b.png
项目结构,源代码全部放在JAVA文件夹下
https://i-blog.csdnimg.cn/direct/f53510709a5a4161a9e0ef915a3b5f0a.png
因为还没有数据库,以是先把pom.xml里数据库的部分注释掉(否则会报错)
https://i-blog.csdnimg.cn/direct/716a22c2ae68489dba3f58d95423a355.png
然后革新一下maven,手动reload一下
https://i-blog.csdnimg.cn/direct/025383636d9a45cb8224edaa68b792c9.png
接下来实验运行,打开java文件,点击三角,运行main方法
https://i-blog.csdnimg.cn/direct/35be163d484e49ff92905e2b608bda4a.png https://i-blog.csdnimg.cn/direct/93dba4a8689641879b90327c61c43e64.png
可以望见运行起来
https://i-blog.csdnimg.cn/direct/e0d06739f6f8414cb6ad5d49c50eea9c.png
右键创建一个测试的controller,编写代码然后运行。
https://i-blog.csdnimg.cn/direct/a12745484d9d4c9283f8e00b93a2ec29.png https://i-blog.csdnimg.cn/direct/411aa3a44bb94552b3d624abb2e438f9.png
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping ("/hello")
public String hello() {
return "Hello World";
}
}
运行后,浏览器访问localhost:8080/hello
https://i-blog.csdnimg.cn/direct/a48cb82d085a4965ac67dbba3dfd75e5.png
基本概念
[*]**@Controller**:标记类为 Spring MVC 控制器,处置处罚 HTTP 哀求并返回视图(如 HTML)。
[*]**@ResponseBody**:将方法的返回值直接写入 HTTP 响体中,而非渲染视图。
[*]**@RestController** = @Controller + @ResponseBody,专用于 RESTful API,自动将返回对象转为 JSON/XML 格式。
焦点功能
[*]通过 @RequestMapping、@GetMapping、@PostMapping 等注解绑定 URL 路径。
改为List:
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class TestController {
@GetMapping ("/hello")
public List<String> hello() {
return List.of("Hello","World");
}
}
显示JSON格式 :
https://i-blog.csdnimg.cn/direct/f927fb9f1d394d60a4086fcf1e7bff49.png
二、rest api规范
8个HTTP方法:
GET
POST
PUT
DELETE
OPTIONS
HEAD
TRACE
CONNECT
1.创建数据库
启动数据库:net start mysql
登录数据库:mysql -uroot -p1234(-u和-p后写本身的用户名和密码)
//创建数据库
create database test
character set utf8mb4
collate utf8mb4_general_ci
//选中该数据库
use test;
//创建数据表
create table student(
id int auto_increment primary key,
name varchar(50) not null,
phone char(11) not null,
age int
);
//插入一条数据
insert into student (name,phone,age)
values('TOM','12345678910',30); 2.写实际代码
①GET接口
规复上面注释的依靠
https://i-blog.csdnimg.cn/direct/4a2fcd93b8034f099873051a5b497a6d.png
新建对应的package,在package里新建接口StudentRepository:
https://i-blog.csdnimg.cn/direct/f2cf3d1ce9894223800b45cea7fca181.png https://i-blog.csdnimg.cn/direct/728bc2c553e94589b9f64d3411aea2c6.png
再建一个学生类:
https://i-blog.csdnimg.cn/direct/7d02f31d9e0441b3b3fbdeae62106ec8.png
//Student.java
package com.example.demo.dao;
import jakarta.persistence.*;
@Entity
@Table(name="student")
public class Student {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "name")
private String name;
@Column(name = "phone")
private String phone;
@Column(name = "age")
private int age;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
//StudentRepository.java
package com.example.demo.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface StudentRepository extends JpaRepository<Student,Long> {
}
然后再创建一个package,写service层,同样新建一个接口文件StudentService,以及对应的一个实现StudentServiceImpl
现在目录是这个格式:
https://i-blog.csdnimg.cn/direct/b075fa75f7df41458ac4c3775918c8c2.png
//StudentServiceImpl.java
package com.example.demo.service;
import com.example.demo.dao.Student;
import com.example.demo.dao.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentRepository studentRepository;
@Override
public Student getStudentById(long id) {
return studentRepository.findById(id).orElseThrow(RuntimeException::new);
}
}
//StudentService.java
package com.example.demo.service;
import com.example.demo.dao.Student;
public interface StudentService {
public Student getStudentById(long id);
}
接下来写对应的api层controller的代码,新建package名为controller,包里建StudentController类。
https://i-blog.csdnimg.cn/direct/8f807c7b4ff8490bba251b4b36306466.png
package com.example.demo.controller;
import com.example.demo.dao.Student;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("/student/{id}")
public Student getStudent(@PathVariable long id) {
return studentService.getStudentById(id);
}
}
配置数据库url(用户名和密码写本身的):
https://i-blog.csdnimg.cn/direct/1d92aadb09104cba951e738a74310459.png
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=1234 在浏览器中输入 localhost:8080/student/1
返回信息:
https://i-blog.csdnimg.cn/direct/44f94ab1038848ae8f2380e662f95090.png
因为controller直接返回了这些值不敷规范,有些加密字段是不想展示给前端的,比如这里将年事保密,不显示。
以是新建一个dto的package以及StudentDTO对象,用来展示可以给前端的数据。
https://i-blog.csdnimg.cn/direct/adc3d63e87b44f6f8d403381d3aabe97.png
package com.example.demo.dto;
public class StudentDTO {
private long id;
private String name;
private String phone;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
修改controller层和service层 :
package com.example.demo.controller;
import com.example.demo.Response;
import com.example.demo.dao.Student;
import com.example.demo.dto.StudentDTO;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("/student/{id}")
public Response<StudentDTO> getStudent(@PathVariable long id) {
return Response.newSuccess(studentService.getStudentById(id));
}
}
package com.example.demo.service;
import com.example.demo.dao.Student;
import com.example.demo.dto.StudentDTO;
public interface StudentService {
StudentDTO getStudentById(long id);
}
package com.example.demo.service;
import com.example.demo.converter.StudentConverter;
import com.example.demo.dao.Student;
import com.example.demo.dao.StudentRepository;
import com.example.demo.dto.StudentDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentRepository studentRepository;
@Override
public StudentDTO getStudentById(long id) {
Student student= studentRepository.findById(id).orElseThrow(RuntimeException::new);
return StudentConverter.convertStudent(student);
}
}
新建package和类:
https://i-blog.csdnimg.cn/direct/6b22032d5f6d4aeebe084f5da8e1dfc7.png
package com.example.demo.converter;
import com.example.demo.dao.Student;
import com.example.demo.dto.StudentDTO;
public class StudentConverter {
public static StudentDTO convertStudent(Student student) {
StudentDTO studentDTO = new StudentDTO();
studentDTO.setId(student.getId());
studentDTO.setName(student.getName());
studentDTO.setPhone(student.getPhone());
return studentDTO;
}
}
新建一个Response类,统逐一些后端访问的格式:
https://i-blog.csdnimg.cn/direct/913d7f73575e472ebfcfb27d2c530e34.png
package com.example.demo;
public class Response <T>{
private T data;
private boolean success;
private String errorMsg;
public static <K> Response<K> newSuccess(K data) {
Response<K> response = new Response<>();
response.setData(data);
response.setSuccess(true);
return response;
}
public static Response<Void> newFail(String errorMsg) {
Response<Void> response = new Response<>();
response.setErrorMsg(errorMsg);
response.setSuccess(false);
return response;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
}
把代码都修改完之后启动,可以望见age隐藏了没有显示。返回成功。
https://i-blog.csdnimg.cn/direct/647b4c34a48145a4ac4e90000777b560.png
以上是完备的GET查询接口的实现,用来查询id=1的学生信息。
②POST接口
接下来新增一个POST接口,用来新增学生信息。
目标:将前端传来的json文件转为Java对象存储至数据库。因为传过来的DTO,以是须要converter,之以是返回getbyid,因为这个方法返回是Long。
编写代码,在原有文件上新增就行,以下复制完备的:
package com.example.demo.controller;
import com.example.demo.Response;
import com.example.demo.dao.Student;
import com.example.demo.dto.StudentDTO;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("/student/{id}")
public Response<StudentDTO> getStudent(@PathVariable long id) {
return Response.newSuccess(studentService.getStudentById(id));
}
@RequestMapping("/student")
@PostMapping("/student")
public Response<Long> addNewStudent(@RequestParam StudentDTO studentDTO) {
return Response.newSuccess(studentService.addNewStudent(studentDTO));
}
}
package com.example.demo.service;
import com.example.demo.dao.Student;
import com.example.demo.dto.StudentDTO;
public interface StudentService {
StudentDTO getStudentById(long id);
Long addNewStudent(StudentDTO studentDTO);
}
package com.example.demo.service;
import com.example.demo.converter.StudentConverter;
import com.example.demo.dao.Student;
import com.example.demo.dao.StudentRepository;
import com.example.demo.dto.StudentDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentRepository studentRepository;
@Override
public StudentDTO getStudentById(long id) {
Student student= studentRepository.findById(id).orElseThrow(RuntimeException::new);
return StudentConverter.convertStudent(student);
}
@Override
public Long addNewStudent(StudentDTO studentDTO) {
List<Student> studentList=studentRepository.findByPhone(studentDTO.getPhone());
if (!CollectionUtils.isEmpty(studentList)){
throw new IllegalStateException("phone:"+studentDTO.getPhone()+" has been taken");
}
Student student=studentRepository.save(StudentConverter.convertStudent(studentDTO));
return student.getId();
}
}
package com.example.demo.converter;
import com.example.demo.dao.Student;
import com.example.demo.dto.StudentDTO;
public class StudentConverter {
public static StudentDTO convertStudent(Student student) {
StudentDTO studentDTO = new StudentDTO();
studentDTO.setId(student.getId());
studentDTO.setName(student.getName());
studentDTO.setPhone(student.getPhone());
return studentDTO;
}
public static Student convertStudent(StudentDTO studentDTO) {
Student student = new Student();
student.setName(studentDTO.getName());
student.setPhone(studentDTO.getPhone());
return student;
}
}
package com.example.demo.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface StudentRepository extends JpaRepository<Student,Long> {
List<Student> findByPhone(String phone);
}
修改完代码就可以使用Postman工具新增学生信息(没有下载以是跳过这步了)
③DELETE接口
接下来实现DELETE删除接口。
在原有文件新增就行,新增代码如下:
//StudentController
@DeleteMapping("/student/{id}")
public void deleteStudentById(@PathVariable long id) {
studentService.deleteStudentById(id);
}
//StudentService
void deleteStudentById(long id);
//StudentServiceImpl
@Override
public void deleteStudentById(long id) {
studentRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("id:"+ id +"doesn't exist!"));
studentRepository.deleteById(id);
} 接下来也是使用postman来删除和查询。(没下载以是又跳过这步,之后如果下载了再来补)
④UPDATE接口
接下来实现UPDATE接口。
在原有文件新增代码如下:
//StudentController
@PutMapping("/student/{id}")
public Response<StudentDTO> updateStudentById(@PathVariable long id, @RequestParam (required = false)String name,
@RequestParam(required = false)String phone) {
return Response.newSuccess(studentService.updataStudentById(id,name,phone));
}
//StudentService
StudentDTO updataStudentById(long id, String name, String phone);
//StudentServiceImpl
@Override
@Transactional
public StudentDTO updataStudentById(long id, String name, String phone) {
Student studentInDB=studentRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("id:"+ id +"doesn't exist!"));
if(StringUtils.hasLength(name) && !studentInDB.getName().equals(name)){
studentInDB.setName(name);
}
if(StringUtils.hasLength(phone) && !studentInDB.getPhone().equals(phone)){
studentInDB.setPhone(phone);
}
Student student=studentRepository.save(studentInDB);
return StudentConverter.convertStudent(student);
} 接下来也是使用postman来更新和查询。
三、打包项目
使用下令:mvn clean install
https://i-blog.csdnimg.cn/direct/c342b61fd0524cebbe2af642c9d9504e.png
但是出现错误:
https://i-blog.csdnimg.cn/direct/15e082bbab494dc294edf175e36ad474.png
错误信息:
Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:3.4.1:clean (default-clean) on project demo: The plugin org.apache.maven.plugins:maven-clean-plugin:3.4.1 requires Maven version 3.6.3 ->
To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.
For more information about the errors and possible solutions, please read the following articles:
http://cwiki.apache.org/confluence/display/MAVEN/PluginIncompatibleException 缘故原由是当前maven版本为3.6.1,但项目依靠 Spring Boot 3.4.4,官方要求 Maven 3.8.8+ 或 Java 21+。
重新下载更高级的maven版本:Welcome to Apache Maven – Maven
下载教程:Maven下载以及项目创建(笔记)_maven 依靠 如何下载 com.github-CSDN博客
须要注意!重新配置maven环境变量时,最好删除原来的MAVEN_HOME,重新添加,否则不会更新。
IDEA重新配置maven路径,重启:
https://i-blog.csdnimg.cn/direct/d38baae28497460e875016ba1fbd76b3.png
可以看到已经将版本更新了
https://i-blog.csdnimg.cn/direct/59897ed977d94476b98a6cf0345def16.png
使用下令:mvn clean install ,成功啦!!
https://i-blog.csdnimg.cn/direct/dd9a88de0e034aad9feb4c2e63b91fa2.png
https://i-blog.csdnimg.cn/direct/e902b00af73149a2ad8f3f85d8c72e6d.png
复制一下jar包路径
https://i-blog.csdnimg.cn/direct/8b2fa950995242a08544b63e17d72087.png
可以用java -jar demo-0.0.1-SNAPSHOT.jar来启动项目: https://i-blog.csdnimg.cn/direct/da77ea6ec5ac4c11b84137533f1a8596.png
以上,总结:
https://i-blog.csdnimg.cn/direct/9ec6d1eada324f519ef7d5639b157539.jpeg
完结撒花,零基础,耗时7小时。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]