文章目录
第一个Spring Boot程序
创建一个SpringBoot项目
这里的包名默认会在后面自动拼接项目名,但这是没有必要的,这会让包结构中多了一个以项目名为名的子包,因此可以手动删除拼接的项目名.
在SpringBoot中不需要了SpringMVC的繁琐的配置,项目创建出来就可以运行,运行的入口是SpringbootApplication
类中的main
方法,这是SpringBoot自动生成的,以后的各层代码都需要在这个类的同级目录中创建才能被该类扫描到.
可以直接应用注解创建各种层,如下面的controller层
@RestController
public class MyController {
@RequestMapping("hello")
public String hello() {
return "hello";
}
}
代码是跟SpringMVC相同的,只是缺少了配置.
修改banner
只需要在resources
目录下创建banner.txt
文件,并将自己喜欢的banner复制进去即可.
像这样
这样,以后启动SpringBoot的banner就会是自己的了.
像这样
yaml
yaml的语法
server:
port: 8082
# 普通键值对
name: fisher
# 对象
user:
name: fisher
age: 17
# 对象的行内写法
user2: {
name: fisher, age: 17}
# 数组
hobite:
- SpringBoot
- Mybatis
- SpringMVC
# 数组的行内写法
hobite2: [SpringBoot, Mybatis, SpringMVC]
SpringBoot官方推荐使用yaml文件作为配置文件,因为yaml更加轻巧
yaml可以表示普通键值对/对象/数组
yaml给类赋值
yaml的功能十分强大,甚至可以直接给实体类赋值
在yaml中写类的赋值语句,在类中通过@ConfigurationProperties(prefix = "")
注解直接导入yaml中的类,就可以通过yaml对类复制,具体代码如下
实体类User.java
@Component //注册
@ConfigurationProperties(prefix = "user")//指定配置文件中的类
public class User {
private String name;
private int age;
private boolean isMan;
private List<String> hobby;
private Map<String, String> map;
private Dog dog;//这个Dog也是一个实体类.里面有name和age属性
}
配置文件application.yaml
user:
name: Fisher
age: 17
isMan: true
hobby: [Java, Java, Java]
map: {
kay1: hello, kay2: word}
dog:
name: Tom
age: 3
yaml中类的属性与实体类中的属性一一对应就可以通过这种方式给类赋值.
yaml还支持松散绑定,也就是在给类赋值的时候,yaml写is-man与isMan是相同的
JSR303校验
JSR303校验是用来校验类属性赋值数据的合法性
常用校验如下
Bean Validation 中内置的 constraint
Hibernate Validator 附加的 constraint
JSR303校验的使用
@Validated //数据校验
public class Dog {
@Email
private String name;
private int age;
}
JRS校验的使用很简单,只需要在该类注解
@Validated
,并在字段中注解需要的校验即可,如这时,该属性赋值时就要遵守JRS校验,否则程序就会报错
yaml多环境配置
多环境配置
在yaml中可以配置多个环境,通过用
---
分割,通过默认环境的spring:profiles:active
选择所用的配置
server:
port: 8081
spring:
profiles:
active: dev #所选环境名
---
server:
port: 8082
spring:
profiles: dev #该环境名
---
server:
port: 8083
spring:
profiles: test
SpringBoot的静态资源与首页
Springboot访问静态资源有两种方式
- webjars, 通过
localhost:8080/webjars...
访问 - 存放在public, static,recoureces中,通过
localhost:8080/...
即可直接访问- 这三者的优先级是recoureces>static>public
SpringBoot首页存放在静态资源目录下的idnex.html
,也就是在public/resources/static这三个目录下的任意一个.
thymeleaf模板引擎
导入依赖
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
thymeleaf初体验
thymeleaf的视图解析器路径为
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
因此需要把资源文件放在/templates
目录下
Controller层代码
@Controller
public class MyController {
@RequestMapping("/hello")
public String hello(Model model) {
model.addAttribute("text", "word");
return "hello"; //跳转到classpath:/templates/hello.html中
}
}
资源文件hello.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
hello
<div th:text="${text}"></div>
</body>
</html>
使用thymeleaf需要在头文件中导入
xmlns:th="http://www.thymeleaf.org
thymeleaf的几个表达式
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${text}"></div>
<div th:utext="${text}"></div>
<div th:each="user:${users}" th:text="${user}"></div>
</body>
</html>
th:text
文字转义,比如,如果text的值为<h1>word</h1>
那他会原样输出这个字符串
th:utext
文字不转义,上面的字符串会输出成word标题
th:each="user:${users}"
遍历,遍历的结果存放在user中
url:@{}
国际化提取信息:#{}
SpringBoot项目案例
首页问题
首页由于需要走thymeleaf模板而不能放在静态资源目录中,只能放在tmplates目录中,因此要在地址栏中访问到首页就需要自定义一个视图解析器,当使用url访问/
或/index.html
就跳转到index.html
自定义配置文件的类需要由@Configration注解,并且实现WebMvcConfigurer接口,代码如下
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
//自定义视图解析器
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//访问'/'时跳转到index,这里index走了SpringBoot的视图解析器
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
}
国际化
-
配置文件
配置文件结构如下
其中
login.properties
为默认语言,login_en_US.properties
为英文配置,login_zh_CN.properties
为中文配置在任意打开一个配置文件,下部会有Resource Bunlde选项卡,点击,即可进行可视化文件配置,如图
-
在配置文件中配置国际化配置文件的位置
application.properties
中# 国际化配置文件的位置 spring.messages.basename=i18n.login
-
页面资源文件中引用国际化配置文件
就是在需要国际化的文字部分使用#{国际化文件字段名},例如
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
注意,要使用#{}
-
自定义语言解析类,即实现
LocaleResolver
接口,该接口位于org.springframework.web.servlet
包下MyLocaleResolver.java
中public class MyLocaleResolver implements LocaleResolver { //解析语言请求 @Override public Locale resolveLocale(HttpServletRequest request) { //获取请求中的语言 String lang = request.getParameter("lang"); Locale locale = Locale.getDefault();//取一个默认的Locale,如果没有参数就用这个默认的 // 有lang参数时进行国际化 if (!StringUtils.isEmpty(lang)) { String[] split = lang.split("_"); locale = new Locale(split[0], split[1]); } return locale; } @Override public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) { } }
-
注册自定义的国际化类
在
MyMvcConfig
类中// 在容器中注册自定义国际化组件 @Bean public LocaleResolver localeResolver() { return new MyLocaleResolver(); }
现在,只要请求中包含lang
参数,解析类就会解析,并根据lang的参数内容显示不同的语言.
拦截器
-
拦截器类需要实现
HandlerInterceptor
接口LoginHandlerInterceptor
类中public class LoginHandlerInterceptor implements HandlerInterceptor { //请求前拦截 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Object username = request.getSession().getAttribute("username"); //没有登录 if (username == null) { request.getRequestDispatcher("/index.html").forward(request, response); return false; } return true; } }
-
拦截器配置
MyMvcConfig
类中//配置自定义拦截器 <