SpringBoot小记

@RequestBody 的使用时机

当传递过来的参数无法覆盖 @RequestBody 修饰的对象中所有的属性,就不用加。

1、在 Controller 中注入 Repository 的接口:

@Autowired
private StudentRepository studentRepository;

注意在 studentRepositoryImpl 中添加 @Repository 注解。

2、@RequestBody 接收一个 JSON 格式的数据,自动的把一个JSON的字符串转换为一个java对象。但如果前端是 JSP,使用的是 application/x-www-form-urlencoded 或者 multipart/form-data,则前端不需要添加注解。

@PostMapping("/save")
public void add(@RequestBody Student student) {
    studentRepository.saveOrUpdate(student);
}

@ResponseBody 方法会返回JSON格式,如果控制器添加了 @RestController,就不需要添加 @ResponseBody 了。

@PathVariable 将参数上的值与 URL 绑定。

SpringBoot 整合 Mybatis

1、建表

CREATE TABLE student(
	id int PRIMARY KEY auto_increment,
	name VARCHAR(11),
	score DOUBLE,
	birthday DATE
)

2、创建实体类

3、创建 StudentRepository 接口

package com.ai.repository;

import com.ai.entity.Student;

public interface StudentRepository {
    void add(Student student);
    void deleteById(Long id);
    void update(Student student);
    void findAll();
    void findById(Long id);
}

4、创建 Mapper 接口

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.repository.StudentRepository">
    <select id="findAll" resultType="Student">
        select * from student
    </select>
    <select id="findById" resultType="Student" parameterType="java.lang.Long">
        select * from student where id = #{id}
    </select>
    <insert id="add" parameterType="Student">
        insert into student(name, score, birthday) values (#{name}, #{score}, #{birthday})
    </insert>
    <update id="update" parameterType="Student">
        update student set name = #{name}, score = #{score}, birthday = #{birthday} where id = #{id}
    </update>
    <delete id="deleteById" parameterType="java.lang.Long">
        delete from student where id = #{id}
    </delete>
</mapper>

6、创建 StudentHandler,注入 StudentRepository

package com.ai.controller;

import com.ai.entity.Student;
import com.ai.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class StudentHandler {
    @Autowired
    StudentRepository studentRepository;

    @PostMapping("/add")
    public void add(@RequestBody Student student) {
        studentRepository.add(student);
    }
    @DeleteMapping("/deleteById/{id}")
    public void deleteById(Long id) {
        studentRepository.deleteById(id);
    }

    @GetMapping("/findAll")
    public List<Student> findAll() {
        return studentRepository.findAll();
    }
    @GetMapping("/findById/{id}")
    public Student findById(@PathVariable("id") Long id) {
        return studentRepository.findById(id);
    }

    @PutMapping("/update")
    public void update(@RequestBody Student student) {
        studentRepository.update(student);
    }
}

7、创建配置文件 yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mbtest?useUnicode=true&characterEncoding=utf-8
    username: root
    password: 1314
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  mapper-locations: classpath:/mapping/*.xml
  type-aliases-package: com.ai.entity

8、创建启动类

package com.ai;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.ai.repository")
public class Application
{
    public static void main( String[] args )
    {
        SpringApplication.run(Application.class, args);
    }
}

SpringBoot 整合 Spring Data JPA

1、添加依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.ai</groupId>
  <artifactId>springboot-jpa</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>springboot-jpa</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.7.RELEASE</version>
  </parent>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.11</version>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
    </dependency>
  </dependencies>
</project>

2、实体类

package com.ai.entity;

import lombok.Data;

import javax.persistence.*;
import java.util.Date;

@Data
@Entity
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column
    private String name;
    @Column
    private Double score;
    @Column
    private Date birthday;
}

3、创建 StudentRepository 接口

package com.ai.repository;

import com.ai.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;

public interface StudentRepository extends JpaRepository<Student, Long> {
}

4、创建 StudentHandler,注入 StudentRepository

package com.ai.controller;

import com.ai.entity.Student;
import com.ai.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class StudentHandler {
    @Autowired
    StudentRepository studentRepository;

    @GetMapping("/findAll")
    public List<Student> findAll() {
        return studentRepository.findAll();
    }

    @GetMapping("findById/{id}")
    public Student findById(@PathVariable("id") Long id) {
        return studentRepository.findById(id).get();
    }

    @PostMapping("/save")
    public Student save(Student student) {
        return studentRepository.save(student);
    }

    @PutMapping("/update")
    public Student update(Student student) {
        return studentRepository.save(student);
    }

    @DeleteMapping("/delete")
    public void delete(Long id) {
        studentRepository.deleteById(id);
    }
}

5、配置文件

spring:
  datasource:
    url: jdbc:mysql://localhost:3306?mbtest?useUnicode=true&characterEncoding=utf-8
    username: root
    password: 1314
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    show-sql: true
    properties:
      hibernate:
        format_sql: true

SpringBoot 整合 Redis

1、导入依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.ai</groupId>
  <artifactId>springboot-redis</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>springboot-redis</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.7.RELEASE</version>
  </parent>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-pool2</artifactId>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
    </dependency>
  </dependencies>
</project>

2、创建实体类,实现序列化接口,否则无法写入 redis 数据库。

package com.ai.entity;

import lombok.Data;

import java.io.Serializable;
import java.util.Date;

@Data
public class Student implements Serializable {
    private Integer id;
    private String name;
    private Double score;
    private Date birthday;
}

3、控制器

package com.ai.controller;

import com.ai.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StudentHandler {

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/set")
    public void set(@RequestBody Student student) {
        redisTemplate.opsForValue().set("student", student);
    }
}

4、配置文件 application.yml

spring:
  redis:
    host: localhost
    database: 0
    port: 6379

Redis 5 种数据类型

  • 字符串
  • 列表
  • 集合
  • 有序集合
  • 哈希

SpringBoot 整合 SpringSecurity

1、导入依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.ai</groupId>
  <artifactId>springboot-springsecurity</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>springboot-springsecurity</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.7.RELEASE</version>
  </parent>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
  </dependencies>
</project>

2、创建 Handler

package com.ai;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloHandler {

    @GetMapping("/index")
    public String index() {
        return "index";
    }
}

3、创建 application.yml 并设置自定义密码

spring:
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
  security:
    user:
      name: admin
      password: 1314

权限管理

定义两个 HTML 资源:index.html、admin.html,同时定义两个角色:admin, user,admin 拥有访问这两个资源的权限,user 只能访问 index.html。

权限给角色,角色赋给用户(账号)。账户有多个角色,也就用了多种权限。

7、创建 SecurityConfig 类

package com.ai.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 角色和权限的关系
        http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN")
                .antMatchers("/index").access("hasRole('ADMIN') or hasRole('USER')")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll()
                .and()
                .csrf()
                .disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 账户和角色的关系
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
                .withUser("user").password(new MyPasswordEncoder().encode("123")).roles("USER")
                .and()
                .withUser("admin").password(new MyPasswordEncoder().encode("123")).roles("ADMIN", "USER");
    }
}

8、修改 Handler

package com.ai.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloHandler {

    @GetMapping("/index")
    public String index() {
        return "index";
    }
    @GetMapping("/admin")
    public String admin() {
        return "admin";
    }
    @GetMapping("/login")
    public String login() {
        return "login";
    }
}

9、login.html

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html" lang="en">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <form th:action="@{/login}"  method="post">
        用户名:<input type="text" name="username" /></br>
        密码:<input type="text" name="password" /></br>
        <input type="submit" value="登录">
    </form>
</body>
</html>

SpringBoot 常用注解

Web相关注解

@RequestMapping:负责URL到Controller中具体函数的映射

@RequestController:@Controller 和 @ResponseBody 的集合,表明是REST风格的控制器,将函数的返回值直接填入HTTP响应体中。

@PathVariable:将URL的占位符参数绑定到方法的参数上

@RequestParam:将请求的参数绑定到方法参数上

@RequestBody:绑定 请求体 到方法参数上。

变量注入

@Autowired:按名称注入

@Resource:按类型注入

异常处理

@RestControllerAdvice@ExceptionHandler


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1216271933@qq.com

×

喜欢就点赞,疼爱就打赏