1.定义父模块micro,在该pom中引入依赖包:以依赖引用的形式进行SpringBoot依赖库的配置
<properties> <spring-boot.version>2.1.6.RELEASE</spring-boot.version> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>${spring-boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
2.【micro-base】定义一个基本的 SpringBoot项目模块: micro-base,并修改子pom文件
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
3.【micro-base】在src/main/com.yootk.action编写action类,方法以及使用注释
● @ResponseBody:标记在控制层方法上面,如果方法返回值类型为String则使用此注解
● @RestController:标记在控制类上面,如果使用Rest风格(Json)返回数据信息则使用此注解
4.【micro-base】在com.yootk包中创建程序启动主类
package com.yootk;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class StartBootMain {
public static void main(String[] args) {
SpringApplication.run(StartBootMain.class,args);
}
}
● 注:@SpringBootApplication注解=@EnableAutoConfiguration + @ComponentScan("com.yootk")
5.说明:经过长期的 Spring开发,很多的开发者发现都必须在 Spring里面设置明确的扫描路径才可以正常使用 SpringMVC开发框
架,于是在 SpringBoot里面,为了简化这一概念,明确的使用了一个子包的形式。
即com.yootk.StartBootMain启动主类要比控制层的包com.yootk.action和配置类的包com.yootk.config同级或更高。
6.【micro-base】在 SpringBoot里面执行,实际上也可以加载一些自定义的 spring配置文件,那么这些配置文件就需要在启动
类编写的时候使用“@Import”注解导入(此注解主要面试的时候用,因为SpringBoot中追求的是零配置即不要编写任何的xml配置文件);
@Import("classpath:spring/spring-xx.xml")
7.SpringBoot程序测试:
●【micro-base】修改pom配置文件,引入测试相关的依赖库
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
● 编写测试程序类:需要在测试类头上写下面三个注解
● @RunWith(SpringJUnit4ClassRunner.class)
● @WebAppConfiguration//表示需要启动web配置才可以进行测试
● @SpringBootTest(classes = StartBootMain.class) //定义要测试的启动类
package com.yootk.test;
import com.yootk.StartBootMain;
import com.yootk.action.MessageAction;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration//表示需要启动web配置才可以进行测试
@SpringBootTest(classes = StartBootMain.class) //定义要测试的启动类
public class TestMessageAction {
@Autowired
private MessageAction messageAction;
@Test
public void testEcho(){
System.err.println(messageAction.echo());
}
}
8.控制层参数传递的两种方式:
● 地址重写的方式(推荐): @RequestMapping("/") public String echo(String msg){...} 执行路径:http://localhost:8080?msg=hello
● 基于Rest风格进行参数的传递:@RequestMapping("/{message}") public String echo(@PathVariable("message") String msg){...} 执行路径:http://localhost:8080/hello就意思是赋的参数值为hello
9.在 SpringBoot里面支持的配置文件有两种风格:“ *.properties”、“*.yml”。在springBoot中*.properties配置文件比*.yml配置文件优先级高,如果两个同时写,springBoot会以*.properties为准,开发的时候推荐使用*.yml风格。在src/main/resources/文件夹写创建application.yml配置文件
#值前面要加一个空格,下面8081和/message前面都有一个空格
server: port: 8081 #接口 servlet: context-path: /test #访问路径
10.配置资源文件:在src/main/resources/下创建一个i18n文件夹,所有需要读取的资源文件都写在此文件夹下(该文件夹下一共有三个文件,Message.properties,Message_en_US.properties,Message_zh_CN.properties)
11.模板渲染:在以后的项目中将不再出现jsp文件,因为jsp文件属于java文件,要实现前后端分离所以不再写jsp文件,直接使用html文件,如果需要动态页面的支持,则需要使用thymeleaf模板语法。
● thymeleaf模板语法依赖包:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
● 【micro-base】建立一个action,这个action类不进行任何的数据输出,只是将数据传递到View层
package com.yootk.action; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Locale; @Controller public class MessageAction { @Autowired private MessageSource messageSource; @RequestMapping("/info") public String info(Model model) { // 此时表示跳转 String enMsg = this.messageSource.getMessage("welcome.info",new Object[]{}, Locale.US); ;//读取英文资源文件 String zhMsg = this.messageSource.getMessage("welcome.info",new Object[]{}, Locale.getDefault()); ;//读取中文资源文件 model.addAttribute("zh",zhMsg) ; model.addAttribute("en",enMsg) ; return "message/message_show" ;//此文件的完整路径为src/main/view/templates/message/message_show.html:不需要写前缀和后缀 } }
● 注意:所有的 thymeleaf语法默认所有的html文件都要求保存在“src/main/view/templates”父目录之中;
● message_show.html文件:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"><!--要想使用thymeleaf语法,必须导入此包--> <head> <meta charset="UTF-8"> <title>SpringBoot模版渲染</title> </head> <body> <h1 th:text="'中文信息:' + ${zh}"></h1> <h1 th:text="'英文信息:' + ${en}"></h1> </body> </html>
12.配置错误页
●【micro-base】所有的错误页实际上都属于静态页面,所有的静态资源文件(例如:图片,css,js文件等)都放在src/main/view/static文件夹下,这次创建两个错误页文件,分别为error-404.html,error-500.html
●【micro-base】如果现在希望SpringBoot可以认可这些错误页,就需要创建一个配置类,一定要在启动类的子包中创建,这次在src/main/java/com.yootk.config/文件夹下创建配置类ErrorPageConfig.java。
package com.yootk.config; import org.springframework.boot.web.server.ErrorPage; import org.springframework.boot.web.server.ErrorPageRegistrar; import org.springframework.boot.web.server.ErrorPageRegistry; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; @Configuration // Bean配置注解 public class ErrorPageConfig { @Bean public ErrorPageRegistrar getErrorPageRegister() { return new ErrorPageRegistrar() { @Override public void registerErrorPages(ErrorPageRegistry registry) { ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND,"/error-404.html") ; ErrorPage errorPage500 = new ErrorPage(HttpStatus.NOT_FOUND,"/error-500.html") ; registry.addErrorPages(errorPage404,errorPage500); } } ; } }
13.全局异常
●【micro-base】在src/main/view/templates目录下创建一个plugins/error-page.html页面,主要功能是显示异常产生的路径以及具体的异常信息。
<h1 th:text="'异常产生路径:'+${url}"></h1> <h1 th:text="'异常信息:'+${exception}"></h1>
●【micro-base】 创建全局异常的配置程序类src/main/java/com.yootk.config.GlobalExceptionHandler.java
package com.yootk.config; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; @RestControllerAdvice // 使用Rest风格就表示返回的数据类型为JSON public class GlobalExceptionHandler {
public static final String DEFAULT_ERROR_PAGE="plugins/error-page";//没有后缀 @ExceptionHandler(Exception.class) // 编写可以处理的异常 public ModelAndView defaultErrorHandler(HttpServletRequest request,Exception e) { ModelAndView mav=new ModelandView(DEFAULT_ERROR_PAGE);
mav.addObject("url",request.getRequestUrl());//错误路径
mav.addObject("exception",e);
return result ; } }
● 当代码出现异常时就会往此全局异常页跳转,如:1/0