有勇气的牛排博客

Spring boot快速上手

有勇气的牛排 338 Java 2023-01-31 23:09:28

快速入门

1 SpringBoot简介

SpringBoot是一个快速开发框架,封装了Maven常用依赖、能够快速整合第三方框架;简化XML配置,全部采用注解形式,内置Tomcat、Jetty、Undertow,帮助开发者能够实现快速开发,SpringBoot的Web组件,默认集成SpringMVC框架。

  • 帮助开发者快速整合第三方框架(原理:maven依赖封装)
  • 去除xml配置,完全采用注解化(原理:Spring体系中内置注解方式)
  • 无序外部Tomcat、内部实现服务器(原理:Java语言支持内嵌入Tomcat服务器)

系统要求:

Java1.8+

Spring Framework 5.0以上

2 创建项目

1 创建maven项目

image-20230130223955920

2、修改maven仓库

image-20230130224229286

3、添加依赖

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

com.couragesteak.controller:视图层(web)和接口(业务逻辑)

com.couragesteak.service:接口

Web开发

1 静态资源

Spring Boot默认提供静态资源目录位置需置于classpath(resource)下,目录名需符合如下规则:

/static

/public

/resources

/META-INF/resources

2 yaml与properties用法

2.1 配置文件(推荐yml)

在resource下创建文件application.properties

cs.name=cs
cs.star=9

在resource下创建文件application.yml

cs: name: cs star: 9

2.2 读取

package com.couragesteak.service.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /* * 读取配置文件 * */ @RestController public class read_properties { @Value("${cs.name}") private String name; @Value("${cs.star}") private String star; @RequestMapping("/getProperties") public String getProperties() { return name + " : " + star; } }

3 渲染web视图

com.couragesteak.controller:视图层

com.couragesteak.service:业务逻辑层

com.couragesteak.dao:数据访问层

默认模板引擎:Thymeleaf、FreeMarker、Velocity、Groovy、Mustache

3.1 使用FreeMarker模板

3.1.1 pom依赖引入

<!-- 引入freeMarker的依赖包. --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>

3.1.2 前端代码

src/main/resources/创建一个templates

freemarkIndex.ftl

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 名字:${name} <br> <#if sex=="0"> 男 <#elseif sex=="1"> 女 <#else> 未知 </#if> <br> <#if (age>=18)> 成年 <#else> 未成年 </#if> <#list userList as user> ${user} </#list> </body> </html>

3.1.3 后端代码

package com.couragesteak.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.Map; @Controller public class FreemarkIndexController { // http://127.0.0.1:8080/freemarkIndex @RequestMapping("/freemarkIndex") public String freemarkIndex(Map<String, Object> result, HttpServletRequest request) { // 传数据到页面 result.put("name", "有勇气的牛排"); result.put("sex", "0"); result.put("age", 22); ArrayList<Object> userList = new ArrayList<>(); userList.add("国学"); userList.add("大师"); result.put("userList",userList); // request.setAttribute("name","cs"); return "freemarkIndex"; } }

Freemarker配置

spring: http: encoding: force: true ### 模版引擎编码为UTF-8 charset: UTF-8 freemarker: allow-request-override: false cache: false check-template-location: true charset: UTF-8 content-type: text/html; charset=utf-8 expose-request-attributes: false expose-session-attributes: false expose-spring-macro-helpers: false ## 模版文件结尾.ftl suffix: .ftl ## 模版文件目录 template-loader-path: classpath:/templates
两种方法 
1 用符号代替: > gt , >=  gte  ,< lt  , <= lte
2 加括号 <#if(x>y)>

3.2 thymeleaf渲染web页面

thymeleaf是一款用于渲染 xml/xhtml/xhtml5内容的模板引擎,类似于jsp、Velocity、FreeMaker等,它可以轻易的与Spring MVC等web框架进行集成作为 Web应用的模板引擎。

3.2.1 Maven依赖

<!-- 模板引擎 引入thymeleaf的依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>

3.2.2 新增配置

### ThymeLeaf配置 spring: thymeleaf: #prefix:指定模板所在的目录 prefix: classpath:/templates/ #check-tempate-location: 检查模板路径是否存在 check-template-location: true #cache: 是否缓存,开发模式下设置为false,避免改了模板还要重启服务器,线上设置为true,可以提高性能。 cache: true suffix: .html encoding: UTF-8 mode: HTML5

4 数据访问

CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(32) NOT NULL COMMENT '用户名称', `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; insert into users values (null, 'cs', '22');

4.1 整合 JdbcTemplate

4.1.1 Maven依赖

<!-- SpringBoot整合jdbc 模板框架 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- SpringBoot整合mysql驱动类 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency>

4.1.2 新增配置

spring: datasource: url: jdbc:mysql://localhost:3306/spring_boot username: root password: root123456 driver-class-name: com.mysql.jdbc.Driver

4.1.3 后端

jdbcTemplate_UserService.java

/* * 数据访问 * 整合jdbcTemplate * */ package com.couragesteak.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class jdbcTemplate_UserService { @Autowired // 获取模板 private JdbcTemplate jdbcTemplate; /* * 插入数据到user表 * */ // http://127.0.0.1:8080/insertUser?userName=cs1&age=20 @RequestMapping("insertUser") public String insertUser(String userName, Integer age) { // insert into users values (null, 'cs', '22'); int update = jdbcTemplate.update("insert into users values (null, ?, ?)", userName, age); return update > 0 ? "success" : "fail"; } }

4.2 整合MyBatis

4.2.1 Maven依赖

<!-- springboot 整合mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency>

4.2.2 application.yml

spring: datasource: url: jdbc:mysql://localhost:3306/spring_boot username: root password: root123456 driver-class-name: com.mysql.jdbc.Driver

4.2.3 Mapper代码

package com.couragesteak.mapper; import com.couragesteak.entity.UserEntity; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; public interface UserMapper { // 插入数据 @Insert("insert into users values (null, #{userName}, #{age});") int insertUser(@Param("userName") String userName,@Param("age") Integer age); @Select("select id as id, name as name, age as age from users where id=#{id}") UserEntity selectByUserId(@Param("id") Integer id); }

4.2.3 后端

/* * mybatis查询 * */ // http://127.0.0.1:8080/mybatisFindById?id=3 @RequestMapping("/mybatisFindById") public UserEntity mybatisFindById(Integer id){ System.out.println("============"); System.out.println(id); return userMapper.selectByUserId(id); }

5 整合热部署


留言

专栏
文章
加入群聊