第2章:SpringBoot入门案例

2021-09-03  本文已影响0人  努力学习的lfk

2.1创建spring boot项目项目


2.2pom.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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <!-- 描述这个POM文件是遵从哪个版本的项目描述符-->
    <modelVersion>4.0.0</modelVersion>
    <!--指向当前工程的父工程的gav坐标-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <!--当前工程的gav坐标-->
    <!--一般是项目的java文件所在的包名,其确定了在项目install的时候的打包路径-->
    <groupId>com.bjpowernode.springboot</groupId>
    <artifactId>001-springboot-fist</artifactId>
    <!--配和groupId,artifactId使用,其确定了被打jar包的所属版本文件夹名,同时也会加在jar包文件名上-->
    <version>1.0.0</version>

    <!--jar包的名称和version共同组成包名-->
    <name>001-springboot-fist</name>
    <!--项目包的简单描述-->
    <description>Demo project for Spring Boot</description>

    <!--指定java编译的版本-->
    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--SpringBoot框架web项目起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--SpringBoot框架测试起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vinteage</groupId>
                    <artifactId>junit-vinteage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!--SpringBoot项目打包编译的插件-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.3目录结构介绍

注意:SpringBoot项目代码必须放在Application类所在的同级目录或下级目录中

2.4使用SpringBoot框架继承SpringMVC


即只要创建了SpringBoot框架,则就集成了SpringMVC

验证:

编写代码:

运行:
启动项目入口类

访问工程:

@Controller(用在控制器的类上面的)

放在控制器(处理器)类的上面,创建控制器对象的,能够接受用户提交的参数,显示请求的处理结果。

@RequestMapping

在Spring MVC 中使用 @RequestMapping 来映射请求,也就是通过它来指定控制器可以处理哪些URL请求,相当于Servlet中在web.xml中配置的映射作用一致。

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
    String name() default "";
    @AliasFor("path")
    String[] value() default {};
    @AliasFor("value")
    String[] path() default {};
    RequestMethod[] method() default {};
    String[] params() default {};
    String[] headers() default {};
    String[] consumes() default {};
    String[] produces() default {};
}

@RequestMapping 中的 value 和 path 属性(这两个属性作用相同,可以互换,如果仅有这一个属性,则可以省略)
@RequestMapping 中的 method 主要用来定义接收浏览器发来的何种请求。
@RequestMapping 的 params 属性表示请求参数,也就是追加在URL上的键值对,多个请求参数以&隔开。
@RequestMapping 的 headers 属性,该属性表示请求头
学习资料:https://blog.csdn.net/renanrenan/article/details/84654362/

@ResponseBody

@ResponseBody的作用其实是将java对象转为json格式的数据。
第一种用法,方法头部;第二种用法,方法修饰符后。效果一样。
学习资料:https://jingyan.baidu.com/article/a24b33cd3c841319fe002b8a.html


2.5使用SpringBoot的核心配置文件application.properties

在application.properties设置内嵌Tomcat端口号和上下文根

#设置内嵌Tomcat端口号
server.port=8081

#设置上下文跟根
server.servlet.context-path=/springboot

2.6SpringBoot框架的核心配置文件application.properties和application.yml(或者application.yaml)同时存在时

//程序代码
@Controller
public class IndexController {

    @RequestMapping(value = "/say")
    public @ResponseBody Object say(String message){
        return "Say Hello"+message;
    }
}
#设置端口号与上下文根
server:
  port: 8082
  servlet:
    context-path: /

2.7SpringBoot的核心配置文件application.yml或者application.yaml

//程序代码
@Controller
public class IndexController {
    @RequestMapping(value = "/say")
    public @ResponseBody String say(){
        return "Hello SpringBoot";
    }
application.properties和application.yml文件都存在时的执行结果 application.properties和application.yml文件都存在时的执行结果 只有application.yml文件的执行结果 只有application.yml文件的执行结果

小结:application.properties和application.yml文件都存在时,优先执行application.properties文件

maven编译找依赖时:
->本地仓库->找到->使用
->本地仓库->镜像仓库->找到->本地仓库->使用
->本地仓库->中央仓库(在国外)->找到->本地仓库->使用

<mirrors>
   //镜像仓库阿里云
   <mirror>
       <id> nexus-aliyum</id>
       <mirrorof>*</mirrorof>
       <name>Nexus aliyun</name>
       <url> http://maven.aliyun.com/nexus/content/groups/public</url>
   </mirror>
</mirrors>

2.8多环境下核心配置文件(.properties)的使用

工作中开发的化境有哪些:开发环境、测试环境、准生产环境、生产环境

//程序代码
@Controller
public class IndexController {
    @RequestMapping(value = "/say")
    public  @ResponseBody String say(){
        return "Hello SpringBoot!";
    }
}

选择开发环境-运行结果
选择测试环境-运行结果
选择准生产环境-运行结果
选择生产环境-运行结果

2.9多环境下核心配置文件(.yml或.yaml)的使用

//程序代码
@Controller
public class IndexController {
    @RequestMapping(value = "/say")
    public  @ResponseBody String say(){
        return "Hello SpringBoot!";
    }
}

选择开发环境-运行结果
选择测试环境-运行结果
选择准生产环境-运行结果
选择生产环境-运行结果

2.10SpringBoot在核心配置文件application.properties自定义配置

//程序代码
@Controller
public class IndexController {

    @Value("${school.name}")
    private String schoolName;

    @Value("${websit}")
    private String websit;

    @RequestMapping(value = "/say")
    public @ResponseBody String say(){
        return "Hello World!"+schoolName+":"+websit;
    }
}
自定义配置

运行结果:
Tomcat started on port(s): 8081 (http) with context path ''

程序运行结果
@Value:简单类型的属性赋值(需要先创建对象注解)

属性:value是String类型的,表示简单类型的属性值
位置:

1.在属性定义的上面,无需set方法(推荐使用)

@Value给对象赋值.png

2.在set方法的上面

@Value给对象赋值2.png

2.11SpringBoot在核心配置文件将自定义配置映射到对象

要求:前缀必须是统一的

appllication.properties文件👇

#上下文根和端口号
server.port=8080
server.servlet.context-path=/

school.name=bjpowernode
school.websit=http://www.bjpowernode.com

abc.name=abc
abc.websit=http://www.abc.com

School对象👇

package com.bjpowernode.springboot.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

//将类定义为一个bean的注解,将此类交给spring容器进行管理
@Component
//表示使用配置文件中前缀为school的属性的值初始化该bean定义产生的bean实例的同名属性
@ConfigurationProperties(prefix = "school")
public class School {
   private String name;
   private String websit;

   public String getName() {
       return name;
   }
   public void setName(String name) {
       this.name = name;
   }
   public String getWebsit() {
       return websit;
   }
   public void setWebsit(String websit) {
       this.websit = websit;
   }
}

Controller控制器👇

package com.bjpowernode.springboot.web;

import com.bjpowernode.springboot.config.School;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IndexController {

   @Autowired
   private School school;

   @RequestMapping(value = "/say")
   public @ResponseBody String say(){
       return "school.name="+school.getName()+",school.websit="+school.getWebsit();
   }
}

运行结果:Tomcat started on port(s): 8080 (http) with context path '

@Autowired引用类型的属性赋值(需要先创建对象注解)

spring框架提供的注解,实现引用类型的赋值,使用的是自动注入原理,支持byName,byType

@Autowired的required属性
required是一个Boolean类型的,默认true
required=true:表示引用类型赋值失败,程序报错,终止执行。
required=false:表示引用类型赋值失败,程序正常执行,引用类型为null。

默认使用byType自动注入:
位置:
1)在属性定义的上面,无需set方法(推荐使用)

@Autowired在属性定义上.png

2)在set方法的上面

@Autowired在set方法上.png

使用byName方式:
1)在属性上面加入@Autowired

2)在属性上面加入@Qualifier(value="bean的id"):
表示使用指定名称的bean完成赋值。

@Component表示将类定义为一个bean的注解,将此类交给spring容器进行管理
@ConfigurationProperties(配置属性注解)表示使用配置文件中前缀为school的属性的值初始化该bean定义产生的bean实例的同名属性

@Component
@ConfigurationProperties(prefix = "school")
public class School {
   private String name;
   private String websit;
   //省略getter/setter方法
}
    <dependencies>
        <!--解决使用@ConfigurationProperties注解出现的警告-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
解决中文乱码

2.12SpringBoot集成jsp

①创建文件夹存放jsp
:创建一个普通文件夹webapp

②设置web资源文件夹

③添加依赖

    <dependencies>
        <!--引用SpringBoot内嵌Tomcat队jsp的解析依赖,不添加解析不了-->
        <!--仅仅只是展示jsp页面,只添加以下一个依赖-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
    </dependencies>

④指定编译jsp的路径

    <build>
        <!--
            SpringBoot项目默认推荐使用的前端引擎是thymeleaf
            现在我们要使用SpringBoot集成jsp,手动指定jsp最后编译的路径
            而且SpringBoot集成jsp编译jsp的路径是SpringBoot规定好的位置
            META-INF/resources
        -->
        <resources>
            <resource>
                <!--源文件夹-->
                <directory>src/main/webapp</directory>
                <!--指定编译到META-INF/resources-->
                <targetPath>META-INF/resources</targetPath>
                <!--指定源文件夹中的哪个资源要进行编译-->
                <includes>
                    <include>*.*</include>
                </includes>
            </resource>
        </resources>
    </build>

⑤在application.properties中配置视图解析器

#配置视图解析器
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp

⑥编写代码

控制器👇

package com.bjpowernode.springboot.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class IndexController {
   @RequestMapping("/say")
   public ModelAndView  say(){
       ModelAndView modelAndView=new ModelAndView();
       >modelAndView.addObject("message","Hello,SpringBoot");
       modelAndView.setViewName("say");
       return modelAndView;
   }
}

jsp页面(web资源文件夹内)👇

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Title</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>

运行结果:Tomcat started on port(s): 8080 (http) with context path ''

ModelAndView

使用ModelAndView类用来存储处理完后的结果数据,以及显示该数据的视图。业务处理器调用模型层处理完用户请求后,把结果数据存储在该类的model属性中,把要返回的视图信息存储在该类的view属性中,然后让该ModelAndView返回该Spring MVC框架。框架通过调用配置文件中定义的视图解析器,对该对象进行解析,最后把结果数据显示在指定的页面上。

具体作用:
1. 设置转向地址(返回指定页面)
ModelAndView构造方法可以指定返回的页面名称,ModelAndView view = new ModelAndView("path:ok");
也可以通过setViewName()方法跳转到指定的页面 。

2.返回所需数值
用于传递控制方法处理结果数据到结果页面,也就是说我们把结果页面上需要的数据放到ModelAndView对象中即可。
addObject()设置需要返回的值。
addAttribute(String key,Object value);


2.13手动创建SpringBoot工程

新建maven工程 pom文件改造完成 手动创建完成

项目实例

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.12-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

resources-application.yml👇

spring:
  profiles:
    active: dev

resources-application-dev-yml👇

server:
  port: 8081

spring:
  datasource:
    username: root
    password: abc1234.
    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  mapper-locations: classpath:mappring/*Mapper.xml
  type-aliases-package: com.example.entity

#showSql
logging:
  level:
    com:
      example:
        mapper : debug

entity-Admin👇

package com.example.entity;

public class Admin {
    private Integer adminId;
    private String adminPwd;

    public Integer getAdminId() {
        return adminId;
    }

    public void setAdminId(Integer adminId) {
        this.adminId = adminId;
    }

    public String getAdminPwd() {
        return adminPwd;
    }

    public void setAdminPwd(String adminPwd) {
        this.adminPwd = adminPwd;
    }

    @Override
    public String toString() {
        return "Admin{" +
                "adminId=" + adminId +
                ", adminPwd='" + adminPwd + '\'' +
                '}';
    }
}

mapper-AdminMapper👇

package com.example.mapper;

import com.example.entity.Admin;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface AdminMapper {

    /*根据adminId查询数据*/
    public Admin selectById(@Param("adminId") int adminId);

    /*查询所有数据*/
    public List<Admin> selectAll();

    /*添加数据*/
    public int insertAdmin(@Param("adminId") int adminId,@Param("adminPwd") String adminPwd);

    /*根据adminId删除数据*/
    public int deleteById(@Param("adminId") int adminId);

    /*根据adminId修改密码*/
    public int updateById(@Param("adminId") int adminId,@Param("adminPwd") String adminPwd);

}

resources-mapping-AdminMapper.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">

<mapper namespace="com.example.mapper.AdminMapper">

    <resultMap id="BaseResultMap" type="com.example.entity.Admin">
        <result column="admin_id" jdbcType="INTEGER" property="adminId" />
        <result column="admin_pwd" jdbcType="VARCHAR" property="adminPwd" />
    </resultMap>

    <select id="selectById" resultMap="BaseResultMap">
        select * from admin where admin_id = #{adminId}
    </select>
    
    <select id="selectAll" resultMap="BaseResultMap">
        select * from admin
    </select>

    <insert id="insertAdmin">
        insert into admin values (#{adminId},#{adminPwd});
    </insert>

    <delete id="deleteById">
        delete from admin where admin_id = #{adminId}
    </delete>

    <update id="updateById">
        update admin set admin_pwd = #{adminPwd} where admin_id = #{adminId}
    </update>
</mapper>

service-AdminService👇

package com.example.service;

import com.example.entity.Admin;
import com.example.mapper.AdminMapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminService {
    @Autowired
    AdminMapper adminMapper;

    /*查询所有数据*/
    public Admin selectById(int adminId){
        return adminMapper.selectById(adminId);
    }

    /*public int selectByIdPwd(String username,String password){
        return adminMapper.selectByIdPwd(username,password);
    }*/

    /*添加数据*/
    public List<Admin> selectAll(){
        return adminMapper.selectAll();
    }

    /*public int insertUser(){
        return adminMapper.insertUser();
    }*/

    /*添加数据*/
    public int insertAdmin(int adminId,String adminPwd){
        return  adminMapper.insertAdmin(adminId,adminPwd);
    }

    /*根据adminId删除数据*/
    public int deleteById(int adminId){
        return adminMapper.deleteById(adminId);
    }

    /*根据adminId修改密码*/
    public int updateById(int adminId,String adminPwd){
        return adminMapper.updateById(adminId,adminPwd);
    }
}

controller-AdminController👇

package com.example.controller;

import com.example.entity.Admin;
import com.example.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/adminController")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /*根据adminId查询数据*/
    @RequestMapping("/selectById/{adminId}")
    public  @ResponseBody Admin selectById(@PathVariable int adminId){
        Admin sel = adminService.selectById(adminId);
        System.out.println(sel);
        return sel;
    }

    /*查询所有数据*/
    @RequestMapping("/selectAll")
    public  @ResponseBody List<Admin> selectAll(){
        List<Admin> sel = adminService.selectAll();
        System.out.println(sel);
        return sel;
    }

    /*添加数据*/
    @RequestMapping("/insertAdmin/{adminId}&{adminPwd}")
    public  @ResponseBody int insertAdmin(@PathVariable int adminId,@PathVariable String adminPwd){
        int i = adminService.insertAdmin(adminId, adminPwd);
        System.out.println("成功添加"+i+"条编号为"+adminId+"的数据");
        return adminId;
    }

    /*根据adminId删除数据*/
    @RequestMapping("/deleteById/{adminId}")
    public  @ResponseBody int deleteById(@PathVariable int adminId){
        int i = adminService.deleteById(adminId);
        System.out.println("成功删除"+i+"条编号为"+adminId+"的数据");
        return adminId;
    }

    /*根据adminId修改密码*/
    @RequestMapping("/updateById/{adminId},{adminPwd}")
    public  @ResponseBody int updateById(@PathVariable int adminId,@PathVariable String adminPwd){
        adminService.updateById(adminId, adminPwd);
        System.out.println("成功修改编号为"+adminId+"的数据");
        return adminId;
    }
}

启动入口类:java.com.exampl.DemoApplication👇

package com.example;

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

@MapperScan("com.example.mapper")//扫描的mapper
@SpringBootApplication
public class DemoApplication {

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

}
后端代码项目结构

笔记来源:B站动力节点Spring Boot学习视频

视频链接:https://www.bilibili.com/video/BV1PZ4y1j7QK?p=12&spm_id_from=pageDriver

上一篇下一篇

猜你喜欢

热点阅读