第2章:SpringBoot入门案例

2.1创建spring boot项目项目


2.2pom.xml文件介绍



    
    4.0.0
    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.5.4
         
    

    
    
    com.bjpowernode.springboot
    001-springboot-fist
    
    1.0.0

    
    001-springboot-fist
    
    Demo project for Spring Boot

    
    
        1.8
    

    
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vinteage
                    junit-vinteage-engine
                
            
        
    

    
        
            
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



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编译找依赖时:
->本地仓库->找到->使用
->本地仓库->镜像仓库->找到->本地仓库->使用
->本地仓库->中央仓库(在国外)->找到->本地仓库->使用


   //镜像仓库阿里云
   
        nexus-aliyum
       *
       Nexus aliyun
        http://maven.aliyun.com/nexus/content/groups/public
   


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方法
}
    
        
        
            org.springframework.boot
            spring-boot-configuration-processor
            true
        
    
解决中文乱码

2.12SpringBoot集成jsp

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

②设置web资源文件夹

③添加依赖

    
        
        
        
            org.apache.tomcat.embed
            tomcat-embed-jasper
        
    

④指定编译jsp的路径

    
        
        
            
                
                src/main/webapp
                
                META-INF/resources
                
                
                    *.*
                
            
        
    

⑤在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" %>


   Title


${message}

运行结果: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



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.4.12-SNAPSHOT
         
    

    com.example
    demo
    0.0.1-SNAPSHOT
    demo
    Demo project for Spring Boot

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.2
        

        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



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 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






    
        
        
    

    
    
    

    
        insert into admin values (#{adminId},#{adminPwd});
    

    
        delete from admin where admin_id = #{adminId}
    

    
        update admin set admin_pwd = #{adminPwd} where admin_id = #{adminId}
    

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 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 selectAll(){
        List 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

你可能感兴趣的:(第2章:SpringBoot入门案例)