当前位置:   article > 正文

spring boot后端开发基础

spring boot后端开发基础

Spring Boot

一、开发步骤

  • 创建项目

在这里插入图片描述

  • 添加依赖

在这里插入图片描述

  • 项目结构

在这里插入图片描述

  • 添加请求处理类

在这里插入图片描述

我们在这个类中处理前端发送过来的请求,例如,我们可以创建一个HelloController类来处理前端发送过来的请求

package com.example.controller;

import org.springframework.web.bind.annotation.*;

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello() {
        System.out.println("Hello World ~");
        return "Hello World ~";
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

二、Web分析

在这里插入图片描述

浏览器:

  • 输入网址:http://192.168.100.11:8080/hello

    • 通过IP地址192.168.100.11定位到网络上的一台计算机

      我们之前在浏览器中输入的localhost,就是127.0.0.1(本机)

    • 通过端口号8080找到计算机上运行的程序

      localhost:8080 , 意思是在本地计算机中找到正在运行的8080端口的程序

    • /hello是请求资源位置

      • 资源:对计算机而言资源就是数据
        • web资源:通过网络可以访问到的资源(通常是指存放在服务器上的数据)

      localhost:8080/hello ,意思是向本地计算机中的8080端口程序,获取资源位置是/hello的数据

      • 8080端口程序,在服务器找/hello位置的资源数据,发给浏览器

服务器:(可以理解为ServerSocket)

  • 接收到浏览器发送的信息(如:/hello)
  • 在服务器上找到/hello的资源
  • 把资源发送给浏览器

网络三要素:

  • IP :网络中计算机的唯一标识
  • 端口 :计算机中运行程序的唯一标识
  • 协议 :网络中计算机之间交互的规则

问题:浏览器和服务器两端进行数据交互,使用什么协议?

答案:http协议

  • 流程

在这里插入图片描述

浏览器向服务器进行请求时:

  • 服务器按照固定的格式进行解析

在这里插入图片描述

服务器向浏览器进行响应时:

  • 浏览器按照固定的格式进行解析

在这里插入图片描述

所以,我们学习HTTP主要就是学习请求和响应数据的具体格式内容。

三、跨域问题

跨域问题出现的原因:浏览器的同源策略(要求请求与服务器满足同源条件)

同源:协议,域名,端口三个都相同才是同源(不存在跨域问题),否则就是不同源(存在跨域问题),不能读取服务器返回回来的资源

例如:

​ vue项目:http://localhost:8080

​ springboot项目:http://localhost:8081/list

分析:

  • 协议都是http
  • 地址都是localhost
  • 端口不同,vue是8080,springboot是8081,不同源,存在跨域问题
  • 解决方案:

法一:创建一个configuration包,创建CorsConfig类重写WebMvcConfigurer接口

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")// 应用CORS策略到所有的路径
                .allowedOriginPatterns("*")// 允许所有域名进行跨域请求,使用通配符"*",不推荐在生产环境
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD")// 允许的HTTP方法
                .allowCredentials(true)// 允许请求带有验证信息,如HTTP认证或cookie
                .maxAge(3600)// 预检请求的结果能够被缓存多长时间(以秒为单位)
                .allowedHeaders("*");// 允许所有头信息,通配符"*"表示接受任何请求头
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

法二: Cors过滤

@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 允许任何域名使用
        corsConfiguration.addAllowedHeader("*"); // 允许任何头
        corsConfiguration.addAllowedMethod("*"); // 允许任何方法(POST、GET等)

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration); // 对所有路径应用配置

        return new CorsFilter(source); // 传递配置源到CorsFilter
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

@Configuration: 用来标识该类为配置类。Spring容器会在启动时加载这个类的配置。

@Bean:让Spring容器管理,@Bean 注解标记在一个方法上,表明该方法将返回一个对象,通常与@Configuration一起使用

四、HTTP协议

浏览器和服务器是按照HTTP协议进行数据通信的。

HTTP协议又分为:请求协议和响应协议

  • 请求协议:浏览器将数据以请求格式发送到服务器
    • 包括:请求行请求头请求体
  • 响应协议:服务器将数据以响应格式返回给浏览器
    • 包括:响应行响应头响应体
请求方式请求说明
GET获取资源
就像是在网上浏览器中输入一个网址并访问某个网页,比如查看今天的新闻或者搜索信息。例子:你在百度中搜索“天气”,就会用GET方法向百度的服务器发送你的搜索请求。
POST提交数据
当你填写表单,比如在线注册账号或上传文件时,通常会使用POST方法。这种方法可以提交更多的数据,而不仅仅是URL能承载的。
OPTIONS探询支持的方法
在开发中,如果你想检查服务器支持哪些HTTP方法,或者在调用复杂请求之前测试服务器的功能,可以使用OPTIONS方法。
HEAD获取资源的元数据
如果你只想检查一个网页的状态,比如是否存在,或者最后更新时间,而不下载整个网页内容,就可以使用HEAD方法。
PUT上传文件
假如你在管理一个网站,需要更新或上传一个文件到服务器的指定位置,就可能会使用PUT方法。
DELETE删除资源
如果你是网站管理员,需要从服务器上永久删除一个页面或文件,就会使用DELETE方法。
TRACE追踪请求
这主要用于调试,可以请求服务器回显收到的请求信息,这样开发者可以看到中间是否有任何改动或添加。
CONNECT使用代理连接
如果你需要通过代理服务器安全地访问网络资源,例如在公司网络中访问外部HTTPS网站,可以使用CONNECT方法。
  • GET请求和POST请求的区别:
区别方式GET请求POST请求
请求参数请求参数在请求行中。
例:/brand/findAll?name=OPPO&status=1
请求参数在请求体中
请求参数长度请求参数长度有限制(浏览器不同限制也不同)请求参数长度没有限制
安全性安全性低。原因:请求参数暴露在浏览器地址栏中。安全性相对高
  • 响应状态码

    状态码类别状态码状态码说明
    1xx 信息性100Continue: 客户端应继续其请求
    2xx 成功200OK: 请求成功
    201Created: 请求已经被实现,而且有一个新的资源已经依据请求的需要而建立
    3xx 重定向301Moved Permanently: 请求的资源已永久移动到新位置
    302Found: 请求的资源临时移动到其他URI
    4xx 客户端错误400Bad Request: 服务器不理解请求的语法
    404Not Found: 服务器找不到请求的资源
    5xx 服务器错误500Internal Server Error: 服务器遇到错误,无法完成请求
    503Service Unavailable: 服务器目前无法使用(由于超载或停机维护)

五、Web服务器

Tomcat,因为springboot自带了一个web服务器,所以就不写了

六、响应前端请求

一、创建一个名为mapper的包用于处理数据库操作

package com.example.mapper;

import com.example.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {
    @Select("select * from resume")
    List<User> list();

    @Insert("insert into resume(name,age,job,email,phone,education,major,school,experience,project) " +
            "values(#{name},#{age},#{job},#{email},#{phone},#{education},#{major},#{school}," +
            "#{experience},#{project})")
    void insertUser(User user);

    @Select("select * from resume where name = #{name}")
    List<User> selectUserByName(String name);

    @Delete("delete from resume where name = #{name}")
    int deleteUserByName(String user);
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

使用#{name}参数的方式,#–> 预处理sql,防止sql注入,提高效率

  • mybatis常用注释
注解描述示例
@Select用于定义选择(查询)操作的SQL语句。@Select("SELECT * FROM users WHERE id = #{id}")
User selectUser(int id);
@Insert用于定义插入操作的SQL语句。@Insert("INSERT INTO users(name, email) VALUES(#{name}, #{email})")
void insertUser(User user);
@Update用于定义更新操作的SQL语句。@Update("UPDATE users SET name = #{name} WHERE id = #{id}")
void updateUser(User user);
@Delete用于定义删除操作的SQL语句。@Delete("DELETE FROM users WHERE id = #{id}")
int deleteUser(int id);
@Mapper标记一个接口作为MyBatis的Mapper接口。@Mapper
public interface UserMapper {}

统一回复格式 Result类

package com.itheima.pojo;

/**
 * 统一响应结果封装类
 */
public class Result {
    private Integer code ;//1 成功 , 0 失败
    private String msg; //提示信息
    private Object data; //数据 date

    public Result() {
    }
    public Result(Integer code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }

    public static Result success(Object data){
        return new Result(1, "success", data);
    }
    public static Result success(){
        return new Result(1, "success", null);
    }
    public static Result error(String msg){
        return new Result(0, msg, null);
    }

    @Override
    public String toString() {
        return "Result{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56

使用示例

package com.itheima.controller;

import com.itheima.pojo.Address;
import com.itheima.pojo.Result;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;

/**
 * 测试响应数据
 */
@RestController
public class ResponseController {
    @RequestMapping("/hello")
    public Result hello(){
        System.out.println("Hello World ~");
        //return new Result(1,"success","Hello World ~");
        return Result.success("Hello World ~");
    }

    @RequestMapping("/getAddr")
    public Result getAddr(){
        Address addr = new Address();
        addr.setProvince("广东");
        addr.setCity("深圳");
        return Result.success(addr);
    }

    @RequestMapping("/listAddr")
    public Result listAddr(){
        List<Address> list = new ArrayList<>();

        Address addr = new Address();
        addr.setProvince("广东");
        addr.setCity("深圳");

        Address addr2 = new Address();
        addr2.setProvince("陕西");
        addr2.setCity("西安");

        list.add(addr);
        list.add(addr2);
        return Result.success(list);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

@RestController包含两个注解,@Controller 和 @ResponsBody,

被@RestController注释的函数的返回值都会以响应体的方式返回

七、springboot常用注解

注解描述示例
@SpringBootApplication用于启动Spring应用的主类上,组合了@Configuration@EnableAutoConfiguration@ComponentScan注解。@SpringBootApplication
public class MyApp { ... }
@Autowired自动注入Spring容器中的Bean。@Autowired
private UserRepository userRepository;
@Component将类标记为Spring组件,使其能够被自动检测和注册为Bean。@Component
public class MyComponent { ... }
@Service标记一个服务类,是@Component的特化,用于业务逻辑层。@Service
public class UserService { ... }
@Repository标记一个DAO组件类,是@Component的特化,用于数据访问层。@Repository
public class UserRepository { ... }
@Controller标记一个控制器组件,通常用于MVC模式的Web应用。@Controller
public class UserController { ... }
@RestController结合了@Controller@ResponseBody,用于RESTful Web服务。@RestController
public class MyRestController { ... }
@RequestMapping映射HTTP请求到Controller的处理器方法上。@RequestMapping("/users")
public List<User> getUsers() { ... }
@GetMapping映射HTTP GET请求到方法上,是@RequestMapping(method = RequestMethod.GET)的简写。@GetMapping("/users")
public List<User> getUsers() { ... }
@PostMapping映射HTTP POST请求到方法上,是@RequestMapping(method = RequestMethod.POST)的简写。@PostMapping("/users")
public User addUser(@RequestBody User user) { ... }
@PutMapping映射HTTP PUT请求到方法上,是@RequestMapping(method = RequestMethod.PUT)的简写。@PutMapping("/users/{id}")
public User updateUser(@PathVariable("id") Long id, @RequestBody User user) { ... }
@DeleteMapping映射HTTP DELETE请求到方法上,是@RequestMapping(method = RequestMethod.DELETE)的简写。@DeleteMapping("/users/{id}")
public void deleteUser(@PathVariable("id") Long id) { ... }
@Configuration标记一个类作为配置类,Spring容器可以从中获取Bean定义。@Configuration
public class AppConfig { ... }
@Bean在配置类中,标记一个方法以定义一个Spring Bean。@Bean
public MyBean myBean() { return new MyBean(); }
@Value注入属性值到配置的字段或方法。@Value("${user.name}")
private String userName;
@Profile指定某些Bean只有在特定的配置文件(profile)激活时才创建。@Profile("dev")
public class DevConfig { ... }
@EnableAutoConfiguration开启Spring Boot的自动配置机制。@EnableAutoConfiguration
public class MyAutoConfig { ... }
  • 创建一个简单的RESTful API

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class MyApp {

    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }

    @GetMapping("/hello")
    public String sayHello(@RequestParam(value = "name", defaultValue = "World") String name) {
        return String.format("Hello %s!", name);
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

在这个例子中,@SpringBootApplication 注解用于主类,启用自动配置、组件扫描和配置属性的支持。@RestController 表明该类处理HTTP请求。@GetMapping 指定一个方法来处理对/hello路径的GET请求。

  • 服务层和数据访问层

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.stereotype.Repository;
    
    @Service
    public class UserService {
    
        private final UserRepository userRepository;
    
        @Autowired
        public UserService(UserRepository userRepository) {
            this.userRepository = userRepository;
        }
    
        public User getUserById(Long id) {
            return userRepository.findById(id).orElse(null);
        }
    }
    
    @Repository
    interface UserRepository extends JpaRepository<User, Long> {
        // Spring Data JPA 会自动实现常见的数据库操作
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    这个例子中,@Service 注解标记了一个服务类,表明它执行业务逻辑。@Repository 注解标记了数据访问接口,Spring Data JPA将自动实现此接口。@Autowired 用于构造函数,实现依赖注入。

  • 配置类和Bean定义

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {
    
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

@Configuration 告诉Spring该类包含一个或多个@Bean定义。@Bean 注解在方法上表明该方法生成一个由Spring容器管理的bean。

  • 响应体和路径变量

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @PostMapping("/users/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        return userService.updateUser(user);  // 假设有一个 userService 处理用户更新
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

@RestController 标记了一个类为控制器,@PostMapping 指定方法响应POST请求。@PathVariable@RequestBody 分别用来绑定URL路径中的变量和HTTP请求体到方法的参数。

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号