Spring Boot

import com.xxx.jpa.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * 实体类类型
 * id键的类型
 */
public interface JpaUserRepository extends JpaRepository<User,Integer> {
//    这里是自定义的方法,当系统自定义不满足需求时,直接这么写
    public User findByUsername(String username);
}

Spring Boot

1.基础

软件设计层面框架

通过Spring Boot 可以快速构建一个基于Spring框架的Java Application,简化配置,自动装配

可以不用写配置文件

JavaConfiguration用Java类替代XML的配置方式。

Spring Boot对常用的第三方库提供了配置方案,可以很好地和Spring进行整合,一键式搭建功能完备的Java企业级应用。

开箱即用是Spring Boot的特点

  • 优势:

    不需要任何XML配置文件

    内嵌Tomcat,可以直接部署
    默认支持JSON数据,不需要进行转换

    支持 RESTful
    配置文件非常简单,支持YAML格式

Spring Boot是一种只需要极少配置就可以快速搭建Spring应用,并且集成了常用的第三方类库,让开发者可以快速进行企业级应用开发。

Spring Boot 2×要求必须基于Spring 5.x,Spring 5.x要求Java版本必须是8以上。

1.创建项目

  • 新建项目

在这里插入图片描述

  • 配置基本信息

在这里插入图片描述

  • 配置依赖

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nyiBeCdV-1624577578724)(Spring Boot.assets/image-20210605225439887.png)]在这里插入图片描述

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-txPI9779-1624577578729)(Spring Boot.assets/image-20210605225505101.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TaxAnpgD-1624577578732)(Spring Boot.assets/image-20210605225608584.png)]

  • 指定路径

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nxDjBikF-1624577578734)(Spring Boot.assets/image-20210605225813817.png)]

  • 新建controller包和类

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EVf2Bq8F-1624577578736)(Spring Boot.assets/image-20210605231450798.png)]

package com.xxx.springboot.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/hello")
public class HelloHandler {

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

  • 启动项目

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-o4q5eOyX-1624577578738)(Spring Boot.assets/image-20210605231708464.png)]

2.使用

1.创建handlwe

2.创建启动类


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootApplication {

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

}

启动类必须覆盖所有与业务相关的类︰启动类所在的包必须是业务类所在包的同包或者父包,如果没有覆盖,业务类就不会自动装配到loC容器中。
当然可以修改

这是等价的


import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

//@SpringBootApplication
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.xxx")

public class SpringbootApplication {

    public static void main(String[] args) {

        SpringApplication.run(SpringbootApplication.class, args);
    }

}

3.配置文件

1.自定义banner

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VzhS4ClB-1624577578740)(Spring Boot.assets/image-20210606074559580.png)]

2.常用配置

1.properities

在application.properities中配置

#端口
server.port=8181
#项目访问路径
server.servlet.context-path=/springboot
#cookie失效时间,单位是s
server.servlet.session.cookie.max-age=100
#session失效时间
server.servlet.session.timeout=100
#编码格式
server.tomcat.uri-encoding=utf-8

2.YAML

YAML是不同于Properties 的另外一种文件格式,同样可以用来写配置文件,Spring Boot默认支持YAML格式,YAML的优点在于编写简单,结构清晰,利用缩进的形式来表示层级关系。

相比于Properties,YAML可以进一步简化配置文件的编写,更加方便。

  • 创建application.yml
server:
  port: 8181
  servlet:
    context-path: /springboot
    session:
      cookie:
        max-age: 100
      timeout: 100
  tomcat:
    uri-encoding: utf-8

需要注意的是YAML格式书写规范非常严格,属性名和属性值之间必须至少一个空格。

如果 Properties和YAML两种类型的文件同时存在,Properties的优先级更高。

3.路径

配置文件除了可以放置在resources 路径下之外,还有3个地方可以放置,如下图所示。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Vlpkm54I-1624577578742)(Spring Boot.assets/image-20210606092229853.png)]

优先级顺序如下所示:
1、根路径下的config中的配置文件

2、根路径下的配置文件
3、resources路径下的config中的配置文件

4、resources路径下的配置文件

可以直接在Handler中读取YAML文件中的数据,比如在业务方法中向客户端返回当前服务的端口信息

@Value


import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/hello")
public class HelloHandler {
//    spEL Spring Expression language,通过这个获取值
    @Value("${server.port}")
    private String port;
    @GetMapping("/index")
    public String index(){
        return this.port;
    }
}

@Value注解同样适用于Properties文件。

4.Spring Boot整合Jsp

Spring Boot与视图层的整合

  • JSP
  • Thymeleaf

Java Server Page,是Java提供的一种动态网页技术,底层是Servlet,可以直接在HTML中插入Java代码

JSP底层原理:
JSP是一种中间层组件,开发者可以在这个组件中将Java代码与HTML代码进行整合,由JSP引擎将组件转为Servlet,再把开发者定义在组件中的混合代码翻译成Servlet的响应语句,输出给客户端。

1.jsp

1.创建基于Maven的web项目

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GNwLe1A5-1624577578744)(Spring Boot.assets/image-20210606103013852.png)]

2.修改pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>

<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.xxx</groupId>
  <artifactId>springbootweb</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>springbootweb Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
<!--    修改jdk版本-->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
<!--引入父依赖-->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.4.RELEASE</version>
  </parent>
  <dependencies>
<!--    web -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

<!--    jsp-->
    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-jasper</artifactId>
        <version>9.0.30</version>
    </dependency>
  </dependencies>
3.创建handler
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/hello")
public class HelloHandler {

    @GetMapping("/index")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("mess","hello springboot");
        return modelAndView;
    }
}

4.创建视图
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>Index</h1>
    ${mess}
</body>
</html>

5.配置application.yml
  • 主要配置了视图解析器

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8WVOQxJQ-1624577578746)(Spring Boot.assets/image-20210606134833776.png)]

server:
  port: 8181
spring:
  mvc:
    view:
      prefix: /
      suffix: .jsp
6.创建启动类
  • 启动启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
       SpringApplication.run(Application.class,args);
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-67zmCa9a-1624577578748)(Spring Boot.assets/image-20210606140355348.png)]

2.JSTL

1.pom.xml
<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.20</version>
</dependency>

Lombok的功能是简化实体类代码的编写工作,常用的方法getter、setter、toString等方法都可以由Lombok自动生成,开发者不需要自己手动编写,Lombok的使用需要安装插件。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2MutibqX-1624577578749)(Spring Boot.assets/image-20210606141553584.png)]

2.创建实体类
import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class User {
    private Integer id;
    private String name;
}

3.Hander中创建业务方法,返回User对象
import com.xxx.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserHand {
    @GetMapping("/find")
    public ModelAndView find(){

        User user1 = new User(1,"张三");
        User user2 = new User(2,"李四");
        User user3 = new User(3,"王五 ");
        List<User> list = Arrays.asList(user1,user2,user3);
        ModelAndView modelAndView = new ModelAndView("index");
        modelAndView.addObject("list",list);
        return  modelAndView;
    }
}
4.视图层
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <table>
        <tr>
            <th>编号</th>
            <th>姓名</th>
        </tr>

        <c:forEach items="${list}" var="user">
            <tr>
                <td>${user.id}</td>
                <td>${user.name}</td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

3.综合

1.创建UserRepository

import com.xxx.entity.User;

import java.util.Collection;

public interface UserRepository {
//    定义方法
    public Collection<User> findAll();
    public User findById(Integer id);
    public void save(User user);
    public void deleteById(Integer id);
    public void update(User user);
}
2.创建UserRepositor的实现类
import com.xxx.entity.User;
import com.xxx.repository.UserRepository;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
@Repository
public class UserRepositoryImpl implements UserRepository {
//    用集合代替数据库
    private static Map<Integer,User> map;
    static {
        map = new HashMap<>();
        map.put(1,new User(1,"张三"));
        map.put(2,new User(1,"李四"));
        map.put(3,new User(1,"王五"));

    }
    @Override
    public Collection<User> findAll() {
        return map.values();
    }

    @Override
    public User findById(Integer id) {
        return map.get(id);
    }

    @Override
    public void save(User user) {
        map.put(user.getId(),user);
    }

    @Override
    public void deleteById(Integer id) {
        map.remove(id);
    }

    @Override
    public void update(User user) {
        map.put(user.getId(),user);
    }
}
3.UserService
import com.xxx.entity.User;

import java.util.Collection;

public interface UserService {
    public Collection<User> findAll();
    public User findById(Integer id);
    public void save(User user);
    public void deleteById(Integer id);
    public void update(User user);
}
4.UserService的实现类

import com.xxx.entity.User;
import com.xxx.repository.UserRepository;
import com.xxx.repository.impl.UserRepositoryImpl;
import com.xxx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.Collection;
@Service
public class UserServiceImpl implements UserService {
//    自动装载
    @Autowired
    private UserRepository userRepository;
    @Override
    public Collection<User> findAll() {
        return userRepository.findAll();
    }

    @Override
    public User findById(Integer id) {
        return userRepository.findById(id);
    }

    @Override
    public void save(User user) {
        userRepository.save(user);
    }

    @Override
    public void deleteById(Integer id) {
        userRepository.deleteById(id);
    }

    @Override
    public void update(User user) {
        userRepository.update(user);
    }
}
5.hander

import com.xxx.entity.User;
import com.xxx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserHand {
    @Autowired
    private UserService userService;

    @GetMapping("/findAll")
    public ModelAndView findAll(){
        ModelAndView modelAndView = new ModelAndView("index2");
        modelAndView.addObject("list",userService.findAll());
        return  modelAndView;
    }

    @GetMapping("/findById/{id}")
    public ModelAndView findById(@PathVariable Integer id){
        ModelAndView modelAndView = new ModelAndView("update");
        modelAndView.addObject("list",userService.findById(id));
        return  modelAndView;
    }

    @PostMapping("/save")
    public String save(User user){
       userService.save(user);
       return  "redirect:/user/findAll";
    }

    @GetMapping("/deleteById/{id}")
    public String deleteById(@PathVariable Integer id){
        userService.deleteById(id);
        return  "redirect:/user/findAll";
    }

    @PostMapping("/update")
    public String update(User user){
        userService.update(user);
        return  "redirect:/user/findAll";
    }

}
6.视图层
  • index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <table>
        <tr>
            <th>编号</th>
            <th>姓名</th>
            <th>操作</th>
        </tr>

        <c:forEach items="${list}" var="user">
            <tr>
                <td>${user.id}</td>
                <td>${user.name}</td>
                <td>
                    <a href="/deleteById/${user.id}">删除</a>
                    <a href="/findById/${user.id}">修改</a>
                </td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>
  • save.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/user/save" method="post">
        <input type="text" name="id"/><br/>
        <input type="text" name="name"/><br/>
        <input type="submit" /><br/>

    </form>
</body>
</html>
  • update
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/user/update" method="post">
        <input type="text" name="id" value="${user.id}"/><br/>
        <input type="text" name="name" value="${user.name}"/><br/>
        <input type="submit" /><br/>
    </form>
</body>
</html>

5.Spring Boot整合Thymeleaf

Spring Boot整合Thymeleaf
Thymeleaf 是目前较为流行的视图层技术,Spring Boot官方推荐使用Thymeleaf。

什么是Thymeleaf
Thymeleaf是一个支持原生THML文件的Java模版,可以实现前后端分离的交互方式,即视图与业务数据分开响应,它可以直接将服务端返回的数据生成HTML文件,同时也可以处理XML、JavaScript、CSS等格式。
Thymeleaf最大的特点是既可以直接在浏览器打开(静态方式),也可以结合服务端将业务数据填充到HTML之后动态生成的页面(动态方法),Spring Boot支持Thymeleaf,使用起来非常方便。

1.使用

1.创建maven工程

创建Maven工程,不需要创建Web 工程

2.修改pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.xxx</groupId>
    <artifactId>Thymeleaf</artifactId>
    <version>1.0-SNAPSHOT</version>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>

        </dependency>
    </dependencies>
</project>
3.创建application.yml
#配置视图解析器
#classpath:指的是resources的路径
spring:
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    servlet:
#       设置响应类型
      content-type: text/html
    encoding: UTF-8 #编码方式
    mode: HTML5 #校验H5格式
    cache: false #关闭缓存,可以看到页面修改的结果
4.创建handler
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/hello")
public class HelloHandler {

    @GetMapping("/index")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("index");
        modelAndView.addObject("name","张三");
        return modelAndView;
    }
}
5.启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}
6.界面
<!DOCTYPE html>
<html lang="en">
<!--引入thymeleaf标签-->
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>index</h1>
<!--    获取后台传过来的值-->
    <p th:text="${name}">Hello</p>
</body>
</html>

如果需要加载后台返回的业务数据,则需要在HTML页面中使用Thymeleaf模版标签来完成。

1.需要引入模版标签。

<html xmlns:th="http://www.thymeleaf.org">

2.通过特定的标签完成操作。

 <p th:text="${name}">Hello</p>

Thymeleaf模版标签不同于JSTL,Thymeleaf模版标签是直接嵌入到HTML原生标签内部。

2.Thymeleaf常用标签

1. th:text

th:text用于文本的显示,将业务数据的值填充到HTML标签中。

2.th:if

thif 用于条件判断,对业务数据的值进行判断,如果条件成立,则显示内容,否则不显示,具体的使用如下所示。

    @GetMapping("/if")
    public ModelAndView ifText(){
        ModelAndView modelAndView = new ModelAndView("test");
        modelAndView.addObject("score",90);
        return modelAndView;
    }
<!DOCTYPE html>
<html lang="en">
<!--引入thymeleaf标签-->
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--    获取后台传过来的值-->
<p th:if="${score >=90}">优秀</p>
<p th:if="${score < 90}">良好</p>
</body>
</html>
3.th:unless

th:unless也用作条件判断,逻辑与th:if恰好相反,如果条件不成立则显示,否则不显示。

<p th:unless="${score >=90}">优秀</p>
<p th:unless="${score < 90}">良好</p>
4. th:switch th:case

th:switch th:case两个结合起来使用,用作多条件等值判断,逻辑与Java中的switch-case一致,当switch中的业务数据等于某个case 时,就显示该case对应的内容。

@GetMapping("/switch")
public ModelAndView switchTest(){
    ModelAndView modelAndView = new ModelAndView("test");
    modelAndView.addObject("studentId",1);
    return modelAndView;
}
    <div th:switch="${studentId}">
        <p th:case="1">张三</p>
        <p th:case="2">李四</p>
        <p th:case="3">王五</p>
    </div>
5. th:action

用来指定请求的URL,相当于form表单中的action属性

    @GetMapping("/redirect/{url}")
    public String redirect(@PathVariable("url") String url){
        return url;
    }

    @GetMapping("/redirect2/{url}")
    public String redirect2(@PathVariable("url") String url, Model model){
        model.addAttribute("url","/hello/login");
        return url;
    }

    @PostMapping("/login")
    @ResponseBody
    public String login(){
        return "login";
    }
  <p>第一种</p>
    <form action="/hello/login" method="post">
        <input type="submit">
    </form>
    <p>第二种</p>
    <form th:action="@{/hello/login}" method="post">
        <input type="submit">
    </form>

    <p>第三种</p>
    <form th:action="${url}" method="post">
        <input type="submit">
    </form>

如果action的值直接写在HTML中,则需要使用@f,如果是从后台传来的数据,则使用$f。

6. th:each

遍历集合

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class User {
    private Integer id;
    private String name;
}
<table>
    <tr>
        <th>编号</th>
        <th>姓名</th>
    </tr>

    <tr th:each="user:${list}">
        <td th:text="${user.id}"></td>
        <td th:text="${user.name}"></td>
    </tr>
</table>
7.th:value

text:文字的显示,value:对应着一个属相

用来给标签赋值。

@GetMapping("/value")
public ModelAndView value(){
    ModelAndView modelAndView = new ModelAndView("test");
    modelAndView.addObject("value","sssssss");
    return modelAndView;
}
<input type="text" th:value="${value}">
8. th:src

用来引入静态资源,相当于HTML原生标签img、script的 src属性。

在resources中创建static目录,项目允许进入这个项目

图片,css,js,静态加载的 html都需要放置在resources/static文件中

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6t8Defun-1624577578752)(Spring Boot.assets/image-20210607172849166.png)]

    @GetMapping("/src")
    public ModelAndView src(){
        ModelAndView modelAndView = new ModelAndView("test");
//        static就是根路径
        modelAndView.addObject("src","/10.gif");
        return modelAndView;
    }
<img th:src="${src}">
<!--如果src的值直接写在HTML中,需要加@{}-->
<img th:src="@{/10.gif}">
<!--这接这样写是不行的-->
<img src="../static/10.gif">
9. th:href
@GetMapping("/href")
public ModelAndView href(){
    ModelAndView modelAndView = new ModelAndView("test");
    modelAndView.addObject("href","/10.gif");
    return modelAndView;
}
<a th:href="${href}">sss</a>
10.th:selsected

用作给HTML元素设置选中,条件成立则选中,否则不选中。


@GetMapping("/select")
public ModelAndView select(){
    List<User> list = Arrays.asList(
        new User(1,"张三"),
        new User(2,"李四"),
        new User(3,"王五")
    );
    ModelAndView modelAndView = new ModelAndView("test");
    modelAndView.addObject("list",list);
    modelAndView.addObject("name","李四");
    return modelAndView;
}
<select>
    <option
            th:each="user:${list}"
            th:value="user.id"
            th:text="${user.name}"
            th:selected="${user.name == name}">
    </option>
</select>

结合th:each 来使用,首先遍历list集合动态创建option元素,根据每次遍历出的user.name与业务数据中的name是否相等来决定是否要选择。

11. th:arr

给HTML标签的任意属性赋值

@GetMapping("/attr")
public ModelAndView attr(){
    ModelAndView modelAndView = new ModelAndView("test");
    modelAndView.addObject("attr","sssss");
    return modelAndView;
}
<input th:attr="value=${attr}">
<!--二者等价-->
<input th:value="${attr}">

3.Thymeleaf对象

Thymeleaf支持直接访问Servlet Web原生资源,HttpServletRequest、HttpServletResponse、HttpSession,ServletContext。

#request:获取HttpServletRequest对象
#response:获取HttpservletResponse对象
#session:获取Httpsession对象
#servletContext:获取servletContext对象
1.原生
    @GetMapping("/servlet")
    public String servlet(HttpServletRequest request){
        request.setAttribute("value","request");
        request.getSession().setAttribute("value","session");
        request.getServletContext().setAttribute("value","Context");
        return "test";
    }
<p th:text="${#request.getAttribute('value')}"></p>
<p th:text="${#session.getAttribute('value')}"></p>
<p th:text="${#servletContext.getAttribute('value')}"></p>
<p th:text="${#response}"></p>
2.简化

Thymeleaf支持直接访问session,$ {#request.getAttribute( ’ name ’ )}也可以简化 ${name}

    @GetMapping("/servlet2")
    public ModelAndView servlet2(HttpSession session){
        session.setAttribute("name","李四");
        ModelAndView modelAndView = new ModelAndView("test");
//        这里是放到request中
        modelAndView.addObject("name","张三");
        return modelAndView;
    }
<p th:text="${name}"></p>
<!--二者等价-->
<p th:text="${#request.getAttribute('name')}"></p>
<p th:text="${session.name}"></p>
<p th:text="${#session.getAttribute('name')}"></p>

4.Thymeleaf内置对象

dates:日期格式化.

calendars:日期操作

numbers:数字格式化

strings:字符串格式化

bools: boolean

arrays:数组内置对象

lists: List集合内置对象

sets: Set集合内置对象

maps: Map集合内置对象

    @GetMapping("/utility")
    public ModelAndView utility(){
        ModelAndView modelAndView = new ModelAndView("test");
//        这里是放到request中
        modelAndView.addObject("date",new Date());

        Calendar calendar = Calendar.getInstance();
        modelAndView.addObject("calendar",calendar);
        modelAndView.addObject("number",0.06);
        modelAndView.addObject("string","hello world");
        modelAndView.addObject("boolean",true);
        modelAndView.addObject("array",Arrays.asList("张三","李四","王五"));
        List<User> list = Arrays.asList(
                new User(1,"张三"),
                new User(2,"李四"),
                new User(3,"王五")
        );

        modelAndView.addObject("list",list);

        Set<User> set = new HashSet<>();
        set.add( new User(1,"张三"));
        set.add( new User(2,"李四"));
        set.add( new User(3,"王五"));
        modelAndView.addObject("set",set);

        Map<Integer,User> map = new HashMap<>();
        map.put(1,new User(1,"张三"));
        map.put(2,new User(2,"李四"));
        map.put(3, new User(3,"王五"));
        return modelAndView;
    }
<p>date格式化:<span th:text="${#dates.format(date,'yyyy-MM-dd')}"></span></p>
<p>当前日期:<span th:text="${#dates.createToday()}"></span></p>
<p>当前时间:<span th:text="${#dates.createNow()}"></span></p>
<p>Calendar格式化:<span th:text="${#calendars.format(calendar,'yyyy-MM-dd')}"></span></p>
<!--2,2:百分号前面与后面有多少位-->
<p>number百分比格式化:<span th:text="${#numbers.formatPercent(number,2,2)}"></span></p>
<p>name是否为空:<span th:text="${#strings.isEmpty(string)}"></span></p>
<p>name的长度:<span th:text="${#strings.length(string)}"></span></p>
<p>name的长度:<span th:text="${#strings.length(string)}"></span></p>
<p>name拼接:<span th:text="${#strings.concat('GOOD',string)}"></span></p>
<p>boolean是否为true:<span th:text="${#bools.isTrue(boolean)}"></span></p>
<p>arrays的长度:<span th:text="${#arrays.length(array)}"></span></p>
<p>arrays是否包含张三:<span th:text="${#arrays.contains(array,'张三')}"></span></p>
<p>List是否为空:<span th:text="${#lists.isEmpty(list)}"></span></p>
<p>List的长度:<span th:text="${#lists.size(list)}"></span></p>
<p>Set是否为空:<span th:text="${#sets.isEmpty(set)}"></span></p>
<p>set的长度:<span th:text="${#sets.size(set)}"></span></p>
<p>map是否为空:<span th:text="${#maps.isEmpty(map)}"></span></p>
<p>map的长度:<span th:text="${#maps.size(map)}"></span></p>

6.Spring JdbcTemplate

JdbcTemplate是Spring自带的JDBC模版组件,底层实现了对JDBC的封装,用法与MyBatis类似,需要开发者自定义SQL语句,JdbcTemplate 帮助我们完成数据库的连接,SQL执行,结果集的封装。
不足之处是灵活性不如MyBatis,因为MyBatis的SQL语句定义在XML中,更有利于维护和扩展,JdbcTemplate 以硬编码的方式将SQL直接写在Java代码中,不利于扩展维护。

1.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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.xxx</groupId>
    <artifactId>springbootdao</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.2.4.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-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>

2.实体类

import lombok.Data;
@Data
public class User {
    private Integer id;
    private String username;
    private String password;
    private Integer age;
}

3.创建UserRepository接口

import com.xxx.entity.User;
import java.util.Collection;
public interface UserRepository {
    //    定义方法
    public Collection<User> findAll();
    public User findById(Integer id);
    public void save(User user);
    public void deleteById(Integer id);
    public void update(User user);
}

4.创建实现类

package com.xxx.reposititory.impl;

import com.xxx.entity.User;
import com.xxx.reposititory.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserRepositoryImpl implements UserRepository {
//    框架自带JdbcTemplate,直接注入
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public List<User> findAll() {

        return jdbcTemplate.query(
                "select * from t_user",
                 new BeanPropertyRowMapper<User>(User.class)
        );
    }

    public User findById(Integer id) {
        return jdbcTemplate.queryForObject(
                "select * from t_user where id = ?",
                new Object[]{id},
                new BeanPropertyRowMapper<User>(User.class)
        );
    }

    public int save(User user) {
        return jdbcTemplate.update(
                "insert into t_user(username,passoword,age) values (?,?,?)",
                user.getUsername(),
                user.getPassword(),
                user.getAge()
        );
    }

    public int deleteById(Integer id) {
        return jdbcTemplate.update(
                "delete from t_user where id = ?",
                id
        );
    }

    public int update(User user) {
        return jdbcTemplate.update(
                "update t_user set username = ?,password = ?,age = ? where id = ?",
                user.getUsername(),
                user.getPassword(),
                user.getAge(),
                user.getId()
        );
    }
}

5.创建Controller

package com.xxx.controller;

import com.xxx.entity.User;
import com.xxx.reposititory.impl.UserRepositoryImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserHandler {

    @Autowired
    private UserRepositoryImpl userRepository;

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

    @GetMapping("/findById/{id}")
     public User findById(@PathVariable Integer id){
        return userRepository.findById(id);
    }

    @PostMapping("/sava")
    public int save(@RequestBody User user){
        return userRepository.save(user);
    }

    @PutMapping("/update")
    public int update(@RequestBody User user){
        return userRepository.update(user);
    }

    @DeleteMapping("/deleteById/{id}")
    public int deleteById(@PathVariable("id") Integer id){
        return userRepository.deleteById(id);
    }
}

6.配置文件

server:
  port: 8181
spring:
  mvc:
    view:
      prefix: /
      suffix: .jsp

  datasource:
    url: jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456

7.启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

8.注意

1.query

query(String sql,RowMapper rowMapper)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SeN7Uxa2-1624577578754)(Spring Boot.assets/image-20210623143151772.png)]

RowMapper是一个接口,作用是解析结果集,将JDBC查询出的ResultSet对象转换成对应的POJO。

queryForObject(String sql,Object[]args,RowMapper rowMapper)

该方法用来查询一条数据,并将结果封装成一个POJO。

2.update

增加、删除、修改的操作都可以调用个这个方法。

7.Spring Boot整合MyBatis

MyBatis自动整合p3c0数据库,不需要在配置了

1.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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.xxx</groupId>
    <artifactId>springbootdao</artifactId>
    <version>1.0-SNAPSHOT</version>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

<!--        引入mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
    </dependencies>
</project>

2.实体类

import lombok.Data;

@Data
public class User {
    private Integer id;
    private String username;
    private String password;
    private Integer age;
}

3. 创建UserRepository接口

import com.xxx.entity.User;

import java.util.Collection;
public interface UserRepository {
    //    定义方法
    public Collection<User> findAll();
    public User findById(Integer id);
    public void save(User user);
    public void deleteById(Integer id);
    public void update(User user);
}

4. 创建UserRepository.xml

/resources/mapper/UserRepository.xml

<?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">
<!--        namespace:mybatis加载配置接口所去找的路径 -->
<mapper namespace="com.xxx.mybatis.repository.UserRepository">
    <!--    parameterType:调用这个方法所要传的参数-->
    <select id="findAll" resultType="User">
        select * from t_user
    </select>

    <select id="findById" parameterType="java.lang.Integer" resultType="user">
        select * from t_user where id= #{id}
    </select>

    <insert id="save" parameterType="User">
        insert into t_user(username,password,age) values(#{username},#{password},#{age})
    </insert>

    <update id="update" parameterType="User">
        update t_user =#{user},password = #{password},age = #{age} where id = #{id};
    </update>

    <delete id="deteteById" parameterType="java.lang.Integer">
        delete from t_user where id = #{id}
    </delete>

</mapper>

5. 创建handler

import com.xxx.entity.User;
import com.xxx.mybatis.respository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserHandler {

    @Autowired
    private UserRepository userRepository;

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

    @GetMapping("/findById/{id}")
    public User findById(@PathVariable Integer id){
        return  userRepository.findById(id);
    }

    @PostMapping("/save")
    public int  save(@RequestBody User user){
        return userRepository.save(user);
    }

    @GetMapping("/deleteById/{id}")
    public int deleteById(@PathVariable Integer id){
        return userRepository.deleteById(id);
    }

    @PostMapping("/update")
    public int update(@RequestBody User user){
        return  userRepository.update(user);
    }

}

6.配置文件

server:
  port: 8181
spring:
  mvc:
    view:
      prefix: /
      suffix: .jsp

  datasource:
    url: jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456

mybatis:
#  xml配置文件
  mapper-locations: classpath:/mapper/*.xml
#  实体类所在位置
  type-aliases-package: com.xxx.entity

7.创建启动类

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

@SpringBootApplication
//扫描接口所在的包
@MapperScan("com.xxx.mybatis.repository")
public class MyBatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyBatisApplication.class, args);
    }
}

8.Spring Boot整合Spring DataJPA

Spring Data JPA是Spring Data大家族的一员

  • JPA和Spring DataJPA的关系

JPA (Java Persistence API)jJava持久层规范,定义了一系列ORM接口,它本身是不能直接使用,

Spring Data JPA是Spring框架提供的对JPA规范的抽象,通过约定的命名规范完成持久层接口的编写,在不需要实现接口的情况下,就可以完成对数据库的操作。
简单理解,通过Spring Data JPA只需要定义接口而不需要实现,就能完成CRUD操作。

Spring Data JPA本身并不是一个具体的实现,它只是一个抽象层,底层还是需要Hibernate这样的JPA来提供支持。

  • Spring DataJPA和Spring JdbcTemplate的关系

Spring JdbcTemplate是Spring框架提供的一套操作数据库的模版,Spring Data JPA是JPA的抽象。

1.pom.xml

<!--Spring Boot集成 Spring Data JPA-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot- -jpa</artifactId>
</dependency>

2.实体类

  • 实体类与表的映射
import lombok.Data;

import javax.persistence.*;

@Data
//表名的映射
@Entity(name = "t_user")
public class User {
//    字段映射
//    id映射
    @Id
//    自增长映射
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
//  普通字段映射
    @Column
    private String username;
    @Column
    private String password;
    @Column
    private Integer age;
}
  • @Entity将实体类与数据表进行映射
  • @ld将实体类中的成员变量与数据表的主键进行映射,一般都是id
  • @Generatedvalue表示自动生成主键,strategy为主键选择生成策略
  • @Column将实体类中的成员变量与数据表的普通字段进行映射

3.创建UserRepositity

package com.xxx.jpa.repository;


import com.xxx.jpa.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * 实体类类型
 * id键的类型
 */
public interface JpaUserRepository extends JpaRepository<User,Integer> {
//    这里是自定义的方法,当系统自定义不满足需求时,直接这么写
    public User findByUsername(String username);
}

4.创建controller

import com.xxx.jpa.entity.User;
import com.xxx.jpa.repository.JpaUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;

@RestController
@RequestMapping("/userjpa")
public class UserHandlerJpa {

        @Autowired
        private JpaUserRepository userRepository;

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

        @GetMapping("/findById/{id}")
        public User findById(@PathVariable Integer id){
            return userRepository.findById(id).get();
        }
//
        @PostMapping("/sava")
        public void save(@RequestBody User user){
             userRepository.save(user);
        }
//
        @PutMapping("/update")
        public void update(@RequestBody User user){
             userRepository.save(user);
        }
//
        @DeleteMapping("/deleteById/{id}")
        public void deleteById(@PathVariable("id") Integer id){
             userRepository.deleteById(id);
        }
    
      @GetMapping("/findByUserName/{username}")
        public User findByUserName(@PathVariable String username){
            //这时需要在接口里去定义
             return userRepository.findByUsername(username);
        }

}

5.配置文件

server:
  port: 8181
spring:
  mvc:
    view:
      prefix: /
      suffix: .jsp

  datasource:
    url: jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
#    打印sql语句
  jpa:
    show-sql: true
    properties:
      hibernate:
#        格式化sql语句
        format_sql: true





6.在继承JpaRepsitory的基础上,开发者也可以自定义方法。

9.Spring Boot整合Spring Security

SpringSecurity

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-arBSDtrp-1624577578757)(Spring Boot.assets/image-20210624190237098.png)]

角色拥有权限,然后分批给用户

1.创建Maven工程,pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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,xxx</groupId>
    <artifactId>springsecrity</artifactId>
    <version>1.0-SNAPSHOT</version>

<!--    引入父依赖-->
      <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
          <version>2.2.4.RELEASE</version>
      </parent>

    <dependencies>
<!--        web依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

<!--        静态模板-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
<!--        security-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        
    </dependencies>
</project>

2.controller

package com.xxx.controller;

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

@Controller
public class SecurityHandler {

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

3.index.html

在resources目录下穿件templates文件夹,然后再创建index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>index</p>
    <form method="post" action="/logout">
        <input type="submit" value="退出">
    </form>
</body>
</html>

4.配置文件

application.yml

spring:
  thymeleaf:
#    前缀
    prefix: classpath:/templates/
    suffix: .html

5.启动类

package com.xxx;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

输入用户名、密码才可以进行访问,默认的用户名是user,密码是启动Spring Security自动生成的随机密码。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sSqYl84m-1624577578759)(Spring Boot.assets/image-20210624195154365.png)]

6.自定义密码

  • 配置文件
spring:
  thymeleaf:
#    前缀
    prefix: classpath:/templates/
    suffix: .html

  security:
    user:
      name: admin
      password: 123

2.实际运用

定义两个资源· index.html. admin.html

定义两个角色

ADMIN访问index.html和admin.html.

USER访问index.html

1.创建SecurityConfig类
  • 在config包中
package com.xxx.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
//开启web验证
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //实现两个类

    /**
     * 角色和资源的关系
     * @param http
     * @throws Exception
     *
     *  .anyRequest().authenticated():所有请求都要验证
     */
    @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();
    }

    /**
     * 用户和角色的关系
     * @param auth
     * @throws Exception
     */
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
//        创建user用户,密码是000,赋予USER角色,and():创建多个用户
      auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
              .withUser("user").password(new  MyPasswordEncoder().encode("000"))
              .roles("USER")
              .and()
              .withUser("admin")
              .password(new MyPasswordEncoder().encode("123"))
              .roles("ADMIN","USER");
    }
}

2.自定义MyPassorldEncoder
package com.xxx.config;

import org.springframework.security.crypto.password.PasswordEncoder;

public class MyPasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence charSequence) {
        return charSequence.toString();
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {
        return s.equals(charSequence.toString());
    }
}

3.修改Controller
package com.xxx.controller;

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

@Controller
public class SecurityHandler {

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

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

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

4.html
  • login.html
<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p th:if="${param.error}">
        用户名或密码错误
    </p>

    <form th:action="@{/login}" method="post">
        用户名:<input type="text" name="username"><br/>
        密码:<input type="password" name="password"><br/>
        <input type="submit" value="登录">
    </form>
</body>
</html>
  • index
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>欢迎回来</p>
    <form method="post" action="/logout">
        <input type="submit" value="退出">
    </form>
</body>
</html>
  • admin.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>后台管理系统</p>
    <form method="post" action="/logout">
        <input type="submit" value="退出">
    </form>
</body>
</html>

,密码是000,赋予USER角色,and():创建多个用户
auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
.withUser(“user”).password(new MyPasswordEncoder().encode(“000”))
.roles(“USER”)
.and()
.withUser(“admin”)
.password(new MyPasswordEncoder().encode(“123”))
.roles(“ADMIN”,“USER”);
}
}




#### 2.自定义MyPassorldEncoder

~~~java
package com.xxx.config;

import org.springframework.security.crypto.password.PasswordEncoder;

public class MyPasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence charSequence) {
        return charSequence.toString();
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {
        return s.equals(charSequence.toString());
    }
}

3.修改Controller
package com.xxx.controller;

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

@Controller
public class SecurityHandler {

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

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

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

4.html
  • login.html
<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p th:if="${param.error}">
        用户名或密码错误
    </p>

    <form th:action="@{/login}" method="post">
        用户名:<input type="text" name="username"><br/>
        密码:<input type="password" name="password"><br/>
        <input type="submit" value="登录">
    </form>
</body>
</html>
  • index
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>欢迎回来</p>
    <form method="post" action="/logout">
        <input type="submit" value="退出">
    </form>
</body>
</html>
  • admin.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>后台管理系统</p>
    <form method="post" action="/logout">
        <input type="submit" value="退出">
    </form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值