Spring Boot
零、情况设置
1. 创建项目
2. 热摆设
添加依赖:
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-devtools</artifactId>
- <optional>true</optional>
- </dependency>
复制代码 设置application.properties文件:
- # 热部署生效
- spring.devtools.restart.enabled=true
- # 设置重启目录
- spring.devtools.restart.additional-paths=src/main/java
- # 设置classpath目录下的 WEB-INF 文件夹内容修改为不重启
- spring.devtools.restart.exclude=static/**
复制代码 打开设置,快捷方式CTRL + ALT + S,举行如下设置:
一、控制器
在Spring Boot中,控制器(Controller)是处置处罚HTTP请求和返回响应的组件。控制器是Spring MVC框架的一部门,用于实现模型-视图-控制器(MVC)设计模式中的控制器层。
SpringBoot提供了两种注解来表示此类负责继续和处置处罚 HTTP 请求:@Controller和@RestController,如果请求的是页面和数据,使用@Controller;如果只是请求数据,则可以使用@RestController。
默认情况下,@RestController注解会将返回的对象数据转换为JSON格式。
@RestController的使用方法
- @RestController // 注解,表示该类是一个RestController控制器
- public class HelloController{
- @RequestMapping("/user") // 映射路由
- public User getUser(){
- User user = new User();
- user.setUsername("zhangsan");
- user.setPassword("123");
- return user;
- }
- }
- // 运行代码后,在浏览器中输入"localhost:8080/user"即可查看返回结果。
复制代码 通常情况下,所写的控制器放在controller文件夹下。
二、路由
注解 @RequsetMapping主要负责 URL 的路由映射,可以添加在Controller 类或者具体的方法上。如果添加 Controller 类上,则这个 Controller 中的所有路由映射都会加上此映射规则,如果添加在某个方法上,则只会对当前方法生效。
常用属性参数:
- value 或 path:
- 用途:定义请求的URL路径。
- 阐明:value是@RequestMapping的属性,可以指定一个或多个URL路径。path是@RequestMapping的别名,与value功能雷同,但只能指定一个路径。
- method:
- 用途:限制请求的HTTP方法(如GET、POST、PUT、DELETE等)。
- 阐明:可以指定一个或多个HTTP方法,只有匹配这些方法的请求才会被映射到相应的处置处罚方法。
- params:
- 用途:根据请求参数的存在与否来决定是否映射请求。
- 阐明:可以指定一个或多个参数条件,只有当这些参数在请求中出现时,请求才会被映射。
- headers:
- 用途:根据请求头的存在与否来决定是否映射请求。
- 阐明:可以指定一个或多个请求头条件,只有当这些请求头在请求中出现时,请求才会被映射。
- consumes:
- 用途:指定可继续的请求体的媒体类型(如application/json、text/plain等)。
- 阐明:只有当请求的Content-Type与指定的媒体类型匹配时,请求才会被映射。
- produces:
- 用途:指定控制器方法可以产生的媒体类型。
- 阐明:这通常用于设置响应的Content-Type,告诉客户端期望接收的媒体类型。
- name:
- 用途:为映射定义一个名称,方便在其他注解中引用。
- 阐明:在大型应用中,使用名称可以简化映射的引用,进步代码的可维护性。
参数通报:
- @RequestParam:用于将HTTP请求的查询字符串参数或请求体参数绑定到控制器方法的参数上。如果参数名称一致,可以省略。
- @PathVariable:用于提取URL中的动态路径变量,并将这些变量通报给控制器方法的参数。
- @RequestBody:用于接收请求体中的参数,通常用于处置处罚JSON、XML等非表单编码的数据。
实例:
- import org.springframework.web.bind.annotation.*;
- import xxx.start.entity.User;
- @RestController
- public class ParamsController {
- @RequestMapping(value = "/getTest1", method = RequestMethod.GET)
- public String getTest1(){
- return "GET请求";
- }
- @RequestMapping(value = "/getTest2", method = RequestMethod.GET)
- // 默认情况,方法的参数名要与网址传参的名称一致。
- public String getTest2(String name, String phone){
- System.out.println("name" + name);
- System.out.println("phone" + phone);
- return "GET请求";
- }
- @RequestMapping(value = "/getTest3", method = RequestMethod.GET)
- // 传参的名称不对应,因此需要使用@RequestParam()进行指定,指定value的话,这样的话参数就必须进行传递,如果这个参数可传可不传就需要required参数
- public String getTest3(@RequestParam(value = "name", required = false) String name){
- System.out.println("name" + name);
- return "GET请求";
- }
- // POST请求
- @RequestMapping(value = "/postTest1", method = RequestMethod.POST)
- public String postTest1(){
- return "POST请求";
- }
- @RequestMapping(value = "/postTest2", method = RequestMethod.POST)
- public String postTest2(String username, String password){
- System.out.println("username" + username);
- System.out.println("password" + password);
- return "POST请求";
- }
- @RequestMapping(value = "/postTest3", method = RequestMethod.POST)
- public String postTest3(User user){ // 这里直接使用User类进行接受,需要将User中的属性名称与传参名称保持一致!
- System.out.println(user);
- return "POST请求";
- }
- @RequestMapping(value = "/postTest4", method = RequestMethod.POST)
- public String postTest4(@RequestBody User user){ // 处理请求体中的参数
- System.out.println(user);
- return "POST请求";
- }
- @RequestMapping(value = "/test/**") // 正则表达式,**可以表示多层而*只能表示一层
- public String test(){
- return "通配符请求";
- }
- }
复制代码 GET方法通常情况是地点传参,如:http://localhost:8080/getTest2?name=张三&phone=123456,这样即将数据通报到了路由getTest2的方法中。
三、文件上传
SpringBoot 工程嵌入的 tomcat 限制了请求的文件巨细,每个文件的设置最大为1MB,单次请求的文件总数不能大于10MB,如要更改默认设置,需要在 application.properties 文件中添加如下两个设置:
- # 上传的单个文件的大小
- spring.servlet.multipart.max-file-size=10MB
- # 上传的多个文件的大小
- spring.servlet.multipart.max-request-size=100MB
复制代码 实例:
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RestController;
- import org.springframework.web.multipart.MultipartFile;
- import javax.servlet.http.HttpServletRequest;
- import java.io.File;
- import java.io.IOException;
- @RestController
- public class FileUploadController {
- @PostMapping("/upload")
- public String up(String name, MultipartFile photo, HttpServletRequest request) throws IOException {
- System.out.println(name);
- // 获取图片原始名称
- System.out.println(photo.getOriginalFilename());
- // 获取文件类型
- System.out.println(photo.getContentType());
- // "user.dir"表当前工作目录的绝对路径
- System.out.println(System.getProperty("user.dir"));
- // 获取web服务器对应的路径,这里获取的是/upload文件夹的路径
- String path = request.getServletContext().getRealPath("/upload/");
- System.out.println(path);
- saveFile(photo, path);
- return "上传成功";
- }
- public void saveFile(MultipartFile photo, String path)throws IOException{
- // 判断存储的目录是否存在
- File dir = new File(path);
- if(!dir.exists()){
- // 如果不存在就创建目录
- dir.mkdir();
- }
- File file = new File(path + photo.getOriginalFilename());
- photo.transferTo(file); // 写入到磁盘文件中
- }
- }
复制代码 四、拦截器(Interceptor)
SpringBoot定义了HardlerInterceptor接口来实现自定义拦截器的功能。HandlerInterceptor接口定义了preHandle、postHandle、afterCompletion三种方法,通过重写这三种方法实现请求前、请求后等利用。
- preHandle:在控制器(Controller)方法实行之前被调用。
- postHandle:它在请求的控制器方法实行之后、渲染视图之前被调用。
- afterCompletion:请求处置处罚流程的最后阶段被调用。
拦截器的使用分为两个步调:1. 定义,2. 注册。
拦截器在定义时,将文件放置在interceptor文件夹中,使用时将文件放在config文件夹中。
定义拦截器:
- import org.springframework.web.servlet.HandlerInterceptor;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- // 注册一个拦截器
- public class LoginInterceptor implements HandlerInterceptor {
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- // 根据条件来判断是否进行拦截。
- if("条件"){
- System.out.println("通过");
- return true;
- }else{
- System.out.println("不通过");
- return false;
- }
- }
- }
复制代码 注册:
- addPathPatterns:定义拦截的地点,添加的一个拦截器没有 addPathPattern 任何一个 URL 则默认拦截所有请求。
- excludePathPatterns:定义排除某些地点不被拦截,如果没有 excludePathPatterns 任何一个请求,则默认不放过任何一个请求。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import xxx.start.interceptor.LoginInterceptor;
// 设置类,可以供springboot来读,这里是添加一个拦截器
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor()).addPathPatterns(“/user/**”);
}
}
五、RESTFUL
RESTFUL 是现在盛行的互联网软件服务架构设计风格。要求客户端使用GET、POST、PUT、DELETE四种表示利用方式的动词对服务端资源举行利用:
- GET用于获取资源
- POST用于新建资源(也可以用于更新资源)
- PUT用于更新资源
- DELETE用于删除资源。
RESTFUL 的特点:资源的表现形式是JSON或者HTML,客户端与服务端之间的交互在请求之间是无状态的,从客户端到服务端的每个请求都包含必须的信息。
HTTP 状态码:
- 1xx:信息,通过传输协议级信息。
- 2xx:成功,表示客户端的请求已成功继续。
- 3xx:重定向,表示客户端必须实行一些其他利用才能完成其请求。
- 4xx:客户端错误,此类错误状态码指向客户端。
- 5xx:服务器错误,服务器负责这些错误状态码。
Spring Boot 实现 RESTFul API:
- SpringBoot 提供的 spring-boot-starter-web 组件完全支持开辟RESTFUL API,提供了与REST利用方式(GET、POST、PUT、DELETE对应的注解)
注解
功能
@GetMapping
处置处罚 GET 请求,获取资源
@PostMapping
处置处罚 POST 请求,新增资源
@PutMapping
处置处罚 PUT 请求,更新资源
@DeleteMapping
处置处罚 DELETE 请求,删除资源
@PatchMapping
处置处罚 PATCH 请求,用于更新部门资源
实例:
- import io.swagger.annotations.ApiOperation;
- import org.springframework.web.bind.annotation.*;
- import xxx.start.entity.User;
- @RestController
- public class UserController {
- @ApiOperation("根据ID获取用户信息") // swagger的注解
- @GetMapping("/user/{id}")
- public String getUserById(@PathVariable int id){
- System.out.println(id);
- return "根据ID获取用户信息";
- }
- @PostMapping("/user")
- public String save(User user){
- return "添加用户";
- }
- @PutMapping("/user")
- public String update(User user){
- return "更新用户";
- }
- @DeleteMapping("/user/{id}")
- public String deleteById(@PathVariable int id){
- System.out.println(id);
- return "根据ID删除用户";
- }
- }
复制代码 六、Swagger
Swagger 是一个开源的 API 设计和文档工具,由 Tony Tam 于 2010 年创建,它可以帮助开辟人员更快、更简朴地设计、构建、文档化和测试 RESTful API。Swagger 可以自动生成交互式 API 文档、客户端 SDK、服务器 stub 代码等,从而使开辟人员更加轻易地开辟、测试和摆设 API 。
Swagger是一个规范和完备的框架,用于生成、形貌、调用和可视化RESTFul风格的web服务,是非常盛行的API表达工具。Swagger能够自动生成完善的RESTFul API文档,同时并根据背景代码的修改同步更新,同时提供完备的测试页面来调试API
使用方法:
- 在项目中(pom.xml)引入 springfox-swagger2 和 springfox-swagger-ui 依赖即可。
- <!-- 添加swagger2相关功能-->
- <dependency>
- <groupId>io.springfox</groupId>
- <artifactId>springfox-swagger2</artifactId>
- <version>2.9.2</version>
- </dependency>
- <!-- 添加swagger-ui相关功能-->
- <dependency>
- <groupId>io.springfox</groupId>
- <artifactId>springfox-swagger-ui</artifactId>
- <version>2.9.2</version>
- </dependency>
复制代码 - 设置Swagger,需要在config目录中编写设置文件:
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import springfox.documentation.builders.ApiInfoBuilder;
- import springfox.documentation.builders.PathSelectors;
- import springfox.documentation.builders.RequestHandlerSelectors;
- import springfox.documentation.service.ApiInfo;
- import springfox.documentation.spi.DocumentationType;
- import springfox.documentation.spring.web.plugins.Docket;
- import springfox.documentation.swagger2.annotations.EnableSwagger2;
- @Configuration // 告诉Spring容器,这个类是一个配置类
- @EnableSwagger2 // 启用Swagger2功能
- public class SwaggerConfig {
- /*
- * 配置Swagger2相关的bean
- * */
- @Bean
- public Docket createRestApi(){
- return new Docket(DocumentationType.SWAGGER_2)
- .apiInfo(apiInfo())
- .select()
- .apis(RequestHandlerSelectors.basePackage("xxx"))
- .paths(PathSelectors.any()).build();
- }
- // 此处主要是API文档页面显示信息
- private ApiInfo apiInfo(){
- return new ApiInfoBuilder()
- .title("演示项目API") // 标题
- .description("演示项目") // 描述
- .version("1.0") // 版本
- .build();
- }
- }
复制代码 注意事项:
- Spring Boot 2.6.x 之后与 Swagger 有版本冲突题目,需要在 application.properties 中加入以下设置:
- # 解决 swagger 版本与 springboot 版本不匹配的问题
- spring.mvc.pathmatch.matching-strategy=ant_path_matcher
复制代码 使用 Swagger2 举行接口测试:
- 启动项目之后,访问http://127.0.0.1:8080/swagger-ui.html即可打开自动生成的可视化测试页面。
七、MyBatis-Plus
友情链接:MyBatis-Plus 官方学习网址
MyBatis是一款优秀的数据持久ORM框架,被广泛地应用于系统,MyBatis 能够非常灵活地实现动态 SQL,可以使用 XML 或 注解 来设置和映射原生信息,能够轻松地将 JAVA 的 POJO(Plain Ordinary Java Object,普通的Java对象)与数据库中的表和字段举行映射关联。
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,它在 MyBatis 的底子上只做增强不做改变,旨在简化开辟和进步服从
使用方法:
- 在pom.xml中添加依赖:
- <!-- MyBatisPlus依赖 -->
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-boot-starter</artifactId>
- <version>3.4.2</version>
- </dependency>
- <!-- mysql驱动依赖 -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.47</version>
- </dependency>
- <!-- 数据库链接池用于向数据库申请多个连接,提高数据库的连接效率 -->
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid-spring-boot-starter</artifactId>
- <version>1.1.20</version>
- </dependency>
复制代码 - 在application.properties文件中设置数据库相干信息:
- # 连接数据库
- spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
- spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false
- spring.datasource.username=root
- spring.datasource.password=root
- mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
- #关闭mybatis-plus的自动驼峰命名法
- mybatis-plus.configuration.map-underscore-to-camel-case=false
复制代码 - 添加 @MapperScan 注解,在 StartApplication 文件(项目启动文件)中添加:
- package xxx.start;
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- @SpringBootApplication
- @MapperScan("xxx/start/mapper") // 使mapper包中的代码生效,mapper存放映射文件。
- public class StartApplication {
- public static void main(String[] args) {
- SpringApplication.run(StartApplication.class, args);
- }
- }
复制代码 - 创建 mapper 文件夹,用于存放 mapper 类,在 mapper 文件夹中利用表的文件,文件名通常为:表名 + Mapper:
- import com.baomidou.mybatisplus.core.mapper.BaseMapper;
- import org.apache.ibatis.annotations.Insert;
- import org.apache.ibatis.annotations.Mapper;
- import org.apache.ibatis.annotations.Select;
- import xxx.start.entity.UserChart;
- import java.util.List;
- //@Repository
- @Mapper
- public interface UserMapper extends BaseMapper<UserChart> { // 使用mybatisplus可以根据userchart表自动找到userchart表
- }
复制代码 - 使用 UserMapper 类,创建 UserMapperController 类:
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RestController;
- import xxx.start.entity.UserChart;
- import xxx.start.mapper.UserMapper;
- import java.util.List;
- // 数据库操作
- @RestController
- public class UserMappingController {
- @Autowired(required = false) // 会将mapper实例化出来的对象注入到userMapper中
- private UserMapper userMapper;
- @GetMapping("/usermap")
- public List query(){
- // 直接使用BaseMapper中自带的方法,selectList的值是查询条件,如果为 null 则表示查询全部。
- List<UserChart> list = userMapper.selectList(null);
- System.out.println(list);
- return list; // 返回给前端的数据
- }
- @PostMapping("/usermap")
- public String save(UserChart userChart){
- int i = userMapper.insert(userChart);
- if(i > 0){
- return "插入成功";
- }else {
- return "插入失败";
- }
- }
- }
复制代码 - UserChart 文件,是一个映射文件,用于映射数据库对应的表,放置到entity文件夹(自建文件夹)中:
- import com.baomidou.mybatisplus.annotation.IdType;
- import com.baomidou.mybatisplus.annotation.TableField;
- import com.baomidou.mybatisplus.annotation.TableId;
- import com.baomidou.mybatisplus.annotation.TableName;
- @TableName("userchart")
- // 另行说明表名为: userchart
- public class UserChart {
- @TableId(type= IdType.AUTO)
- // 表明id是自增的
- public int id;
- public String username;
- public String password;
- @TableField(value = "birth", exist = true)
- // value表示对应数据库表中的具体字段,如果属性与字段不一致需要另行设置,exist表示该属性是否为字段,默认为true。
- public String birthday;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getBirthday() {
- return birthday;
- }
- public void setBirthday(String birthday) {
- this.birthday = birthday;
- }
- @Override
- public String toString() {
- return "UserChart{" +
- "id=" + id +
- ", username='" + username + ''' +
- ", password='" + password + ''' +
- ", birthday='" + birthday + ''' +
- '}';
- }
- }
复制代码 八、目录结构
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |