.SpringBoot简介 -SpringBoot是Java框架之一,可以快速整合其他框架 -通过Maven构建SpringBoot项目,不需要过多的的XML的配置,直接使用注解即可 -SpringBoot同时也支持微服务SpringCloud、Dubbo框架 -使用场景:SpringBoot+Spring+SpringMVC+MyBatis 2.使用Maven构建SpringBoot项目(IDEA版) -File-->Spring Initializr-->...-->Dependencies: Web: SpringWeb -设置项目的编码 File-->Settings-->Editor-->File Encodings-->选择UTF-8 -运行启动类即可 3.SpringBoot目录结构 --src: - main:开发的主要目录 $ java:java代码目录 $ resources目录 (1)static:静态文件 (2)templates:动态文件 (3)application.properties:用于配置端口、数据库等 - test:测试用例 -target:mave打包后的结果 4.SpringBoot实现一个SpringMVC请求
package com.youhui.sboot.s01;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* User:youHui
*/
@Controller
@RequestMapping
public class S01MvcController {
@RequestMapping
public ModelAndView homeTest(){
System.out.println("springMVC创建成功");
return new ModelAndView("s01.html");
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
hello SpringBoot
</body>
</html>
-pom.xml:依赖文件的配置 -External Libraries:所有依赖的包 4.SpringBoot配置文件(application.properties) -SpringBoot启动时会加载application.properties文件 -为了配置文件结构的清晰度把application.properties文件的后缀名改为.yml eg:application.yml #端口号的配置 server: port: 8080 #Freemark的配置 freemarker: cache: false checkTemplateLocation: true contentType: text/html suffix: .html templateEncoding: UTF-8 templateLoaderPath: classpath:templates 5.通过@Value和Expression表达式,把application.yml读到Java中 -@Value
package com.youhui.sboot.s02;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* User:youHui
*/
@Controller
@RequestMapping("/s02")
public class S02Controller {
//获取yml中的值
@Value("${com.youhui.name}")
public String name;
@RequestMapping("/getYmlData")
@ResponseBody
public String getYmlData(){
System.out.println("name:" + name);
return "获取成功" + name;
}
}
application.yml:
#设置值
com.youhui:
name: youhui
-Expression表达式:主要用于获取自定义配置文件的数据 $ 需要添加依赖:复制到pom.xml文件中 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> $ 创建resource.yml $ 创建ResourceConfig.java用来与自定义的yml文件形成对应
package com.youhui.sboot.s02;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* User:youHui
*/
@Configuration
@ConfigurationProperties(prefix = "com.web")
@PropertySource(value = "classpath:resource.yml", factory = YmlResourceFactory.class)
public class ResourceConfig {
//定义自定义文件yml中对应的属性
private String name;
private String url;
private String date;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
//读取实现类
package com.youhui.sboot.s02;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import java.io.IOException;
import java.util.Properties;
/**
* ResourceConfig读取自定义配置文件yml
* 需要借助这个类才能实现
*/
public class YmlResourceFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
Properties ymlProperties = factory.getObject();
String propertyName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(propertyName, ymlProperties);
}
}
package com.youhui.sboot.s02;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* User:youHui
*/
@Controller
@RequestMapping("/s02")
public class S02Controller {
@Autowired
public ResourceConfig resource;
@RequestMapping("/getYmlData")
@ResponseBody
public String getYmlData(){
System.out.println("url:" + resource.getUrl());
return "获取成功" + resource.getName();
}
}
6.SpringBoot的热部署
-热部署就是修改Java代码不需要重启服务器,点击编译即可
-热部署是通过依赖下载devtools jar包实现的
-在pom.xml文件中添加以下代码
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
7.SpringBoot编写测试用例
-方法一:在test目录下相应的包里创建测试类
package com.youhui.sboot;
import com.youhui.sboot.s02.S02Controller;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
* User:youHui
*/
@SpringBootTest
public class S02ControllerTest {
@Autowired
S02Controller s02Controller;
//测试的函数
@Test
public void getYmlDataTest(){
s02Controller.getYmlData();
}
}
-方法二:使用MockMvc模拟Http请求
package com.youhui.sboot;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
/**
* User:youHui
*/
@SpringBootTest
public class S02MockMvcTest {
MockMvc mockMvc;
//通过@Autowired注入SpringBoot上下文
@Autowired
WebApplicationContext context;
//每次测试都会执行setup函数即:初始化mockMvc
@BeforeEach
public void setup(){
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
//测试函数
@Test
public void getYmlDataTest() throws Exception{
String result = mockMvc.perform(MockMvcBuilders.get("/s02/getYmlData"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn().getResponse().getContentAsString();
System.out.println("返回的结果:"+result);
}
}
8.SpringBoot整合JSON渲染数据 -一般用于ajax异步请求,需要加@ResponseBody注解,返回数据 -在pom.xml中添加依赖 <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency>
package com.youhui.sboot.s03;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.xml.crypto.Data;
import java.util.Date;
/**
* User:youHui
*/
@Controller
@RequestMapping("/s03")
public class S03Controller {
@RequestMapping
@ResponseBody
public String home(){
//使用阿里巴巴的JSON类
//JSONObject jsonObject = new JSONObject();
//jsonObject.put("error",0);
//jsonObject.put("data","success");
//return jsonObject.toJSONString();
User user = new User();
user.setName("张三");
user.setSex("男");
user.setAge(18);
user.setPwd("123456");
user.setTime(new Date());
//也可以把JSON数据放到一个类中
return JSONData.success(user);
}
}
package com.youhui.sboot.s03;
import com.alibaba.fastjson.JSONObject;
/**
* User:youHui
* JSONData:主要是一些提示信息
*/
public class JSONData {
public static final Integer SUCCESS = 0;
public static final Integer FAILURE = 1;
public static String success(Object data){
JSONObject jsonObject = new JSONObject();
jsonObject.put("error",SUCCESS);
jsonObject.put("data",data);
return jsonObject.toJSONString();
}
public static String failure(String message){
JSONObject jsonObject = new JSONObject();
jsonObject.put("error",FAILURE);
jsonObject.put("message",message);
return jsonObject.toJSONString();
}
}
package com.youhui.sboot.s03;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.Date;
/**
* User:youHui
*/
public class User {
private String name;
private String sex;
private Integer age;
private String pwd;
@JSONField(format="yyy-MM-dd hh:mm:ss")
private Date time;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
}
9.SpringBoot整合FreeMarker -在pom.xml中添加FreeMarke依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> -在application.yml文件添加FreeMarker配置 # FreeMarker配置 spring: freemarker: cache: false checkTemplateLocation: true contentType: text/html suffix: .html templateEncoding: UTF-8 templateLoaderPath: classpath:templates
package com.youhui.sboot.s04;
import com.youhui.sboot.s03.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.Date;
/**
* User:youHui
*/
@Controller
@RequestMapping("/s04")
public class S04Controller {
@RequestMapping("/index")
public ModelAndView index(){
ModelAndView mv = new ModelAndView("s04");
User user = new User();
user.setName("张三");
user.setSex("男");
user.setAge(18);
user.setPwd("123456");
user.setTime(new Date());
//把User类中的数据放入Model中
mv.addObject("user",user);
return mv;
}
}
package com.youhui.sboot.s03;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.Date;
/**
* User:youHui
*/
public class User {
private String name;
private String sex;
private Integer age;
private String pwd;
@JSONField(format="yyy-MM-dd hh:mm:ss")
private Date time;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>Model中的数据展示 </p>
<span>姓名:${user.name}</span><br>
<span>性别:${user.sex}</span><br>
<span>年龄:${user.age}</span><br>
<span>密码:${user.pwd}</span><br>
<span>时间:${user.time ?string('yyyy-MM-dd HH:mm:ss')}</span>
</body>
</html>
10.FreeMarker的基本用法
package com.youhui.sboot.s05;
import com.youhui.sboot.s03.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* User:youHui
*/
@Controller
@RequestMapping("/s05")
public class S05Controller {
@RequestMapping("/index")
public ModelAndView index(){
ModelAndView mv = new ModelAndView("/s05");
User user = new User();
user.setName("张三");
user.setAge(18);
mv.addObject("user",user);
String address = "火星";
mv.addObject("address",address);
List<User> user1List = new ArrayList<User>();
Map<String,User> user1Map = new HashMap<String,User>();
for(int i=0;i<10;i++){
User user1 = new User();
user1.setName("李四" + i);
user1.setSex("男");
user1.setAge(19);
user1.setPwd("456789");
user1List.add(user1);
user1Map.put("user"+i,user1);
}
mv.addObject("user1List",user1List);
mv.addObject("user1Map",user1Map);
return mv;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>FreeMarker基于语法的使用</p>
<div>
<!--取值和非空处理-->
<p>姓名:${user.name}</p>
<p>性别:${user.sex!}</p>
<p>地址:${address}</p>
<!--遍历 -->
<div>
<!--list遍历 -->
<p>list遍历</p>
<#list user1List as item>
${item.name}--${item.age}--${item.sex}<br>
</#list>
<br>
<!--list遍历 -->
<span>Map遍历</span>
<#list user1Map?keys as key>
${key}:${user1Map[key].name}<br>
</#list>
<br>
<!--list遍历 -->
<p>条件判断</p>
<#if user.address??>
${user.address}
<#else>
用户地址不存在
</#if>
</div>
</div>
</body>
</html>
11.SpringBoot实现国际化 -SpringBoot实现国际化就根据浏览器使用语言加载相应语言的配置文件。 -在resources目录下创建国际化配置文件即可,命名为message messages.properties(默认) messages_zh_CN.properties(中文) messages_en_US.properties(英文) -application.yml中的配置 spring: messages: basename: i18n/messages encoding: UTF-8 -使用FreeMarker在Html文件中添加以下代码即可 $ 在html头部添加<#import "spring.ftl" as s> $ 使用<@s.message code="welcome" />即可 $ 添加拦截器,根据我们选择的语言切换国际化:I18nLocaleConfig.java
package com.youhui.sboot.s03;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import java.util.Locale;
@Configuration
public class I18nLocaleConfig {
//默认解析器,设置为汉语
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver resolver = new SessionLocaleResolver();
resolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
return resolver;
}
//拦截器:请求参数为“lang”
@Bean
public WebMvcConfigurer localeInterceptor() {
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
interceptor.setParamName("lang");
registry.addInterceptor(interceptor);
}
};
}
}
12.SpringBoot整合MySQL连接驱动 -在pom.xml文件中添加数据驱动依赖 <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency> <!-- 使用JDBC模板的依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> -在application.yml文件中配数据库连接 spring: datasource: driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/你的数据库名?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai username: root password: 你的数据库密码 -访问数据库的测试用例
package com.youhui.sboot;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* User:youHui
*/
@SpringBootTest
public class S05Test {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void connectionTest(){
String sql = "select name from booklist";
System.out.println("查询结果:"+jdbcTemplate.queryForList(sql,String.class));
}
}
13.SpringBoot整合Mybatis -在pom.xml文件中添加MyBatis依赖 <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> -在application.yml文件中配置Mybatis mybatis: type-aliases-package: com.youhui config-locations: classpath:mybatis/mybatis-config.xml mapper-locations: classpath:mybatis/mapper/*.xml -在resources目录下新建文件夹命名为mybatis $ 在mybatis下新建mybatis-config.xml文件,文件的代码为 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--这个文件的作用是:数据库中的字段名在映射到 Java中时,变为驼峰式--> <settings> <setting name="mapUnderscoreToCamelCase" value="true" /> </settings> </configuration> $ 在mybatis下新建mapper文件夹,文件夹里写数据库对应表的名字的xml文件。 表的名字的xml文件里写SQL代码。 -数据库的操作 Controller--Service--Dao
package com.youhui.sboot.s06;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* User:youHui
*/
@Mapper
public interface BookDao {
// Book已经存储了查询返回的数据
public List<Book> getBookList();
}
Book
package com.youhui.sboot.s06;
/**
* User:youHui
*/
public class Book {
/*
* 这个类与数据库中数据表
* 一 一对应
* */
public String name;
public Integer price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://10.20.91.130/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.youhui.sboot.s06.BookDao">
<select id="getBookList" resultType="com.youhui.sboot.s06.Book">
SELECT * FROM bookList
</select>
</mapper>
package com.youhui.sboot.s06;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* User:youHui
*/
@Service
public class BookService {
/*
* 注入Dao,才能使用其中
* 的接口
* */
@Autowired
BookDao bookDao;
/*
* 返回的是列表,定义方法时
* 需要定义列表集合的方法
* */
public List<Book> getBooks(){
return bookDao.getBookList();
}
}
package com.youhui.sboot.s06;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.GsonBuilderUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
/**
* User:youHui
*/
@Controller
@RequestMapping("/s06")
public class S06Controller {
@Autowired
private BookService bookService;
@RequestMapping("/index")
public ModelAndView index(){
ModelAndView mv = new ModelAndView("/s06");
List<Book> bookList = bookService.getBooks();
mv.addObject("bookList",bookList);
return mv;
}
}
14.SpringBoot整合Shiro -Shiro是权限认证框架 -在pom.xml文件中添加Shiro依赖 <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-web-starter</artifactId> <version>1.7.0</version> </dependency> -创建AuthRealm类:用于登录,设置权限
package com.youhui.sboot.s07;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
/**
* User:youHui
*/
public class AuthRealm extends AuthorizingRealm {
//这个方法用来返回用户的角色和权限
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//设置用户的角色权限
return null;
}
//这个方法用来实现用户登录行为
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//去访问数据库,对用户名、密码等进行校验
return null;
}
}
-创建ShiroConfig类:用来做Shiro的配置,拦截uri、注入sessionSecurity
package com.youhui.sboot.s07;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.mgt.SessionsSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
factoryBean.setSecurityManager(securityManager);
factoryBean.setLoginUrl("/s07/login");//不会拦截
Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>();
filterChainDefinitionMap.put("/", "anon");
filterChainDefinitionMap.put("/s07/login", "anon");//anon
filterChainDefinitionMap.put("/s07/dologin", "anon");//anon
filterChainDefinitionMap.put("/**", "anon");
factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return factoryBean;
}
@Bean
public SessionsSecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(authRealm());
securityManager.setSessionManager(sessionManager());
return securityManager;
}
@Bean
public AuthRealm authRealm() {
return new AuthRealm();
}
@Bean
public DefaultWebSessionManager sessionManager() {
//SessionIdUrlRewritingEnabled的默认值是false
return new DefaultWebSessionManager();
}
}