文章目录
前言
基于Spring开发,简化了Spring的配置,是一个快速开发项目的脚手架。核心思想:约定优于配置。
一、SpringBoot简介
SpringBoot优点:
- 构建方便,通过Idea和Maven工具能够快速构建项目。
- 配置简便,参数配置清晰且阅读性好。
- 部署方便,内嵌式web容器可以直接打包成jar运行。
- 文档完善,参考的文档资料比较详细。
SpringBoot缺点:
- 迭代更新比较快。
- 底层源码原理较复杂,不容易理解。
发展历程:
从最初的Servlet到SSH(Spring Struts Hibernate)再到SSM(Spring SpringMVC MyBatis) 再到SpringBoot。
Servlet --> SSH --> SSM --> SpringBoot
构建方式:
- 使用官网提供的地址来生成压缩包,然后解压导入。网址:https://start.spring.io/
- 一般还是主要使用Idea工具来构建项目。
Idea热部署插件JRebel:
当开始开发web项目的时候,需要频繁的修改Web页面,此时如果频繁的重启变得很麻烦,因此可以在Idea中集成JRebel插件,改动代码之后不需要重新启动应用程序。
参考链接:打开链接
SpringBoot中文文档:
参考链接:打开链接
二、构建简单Java项目
1.通过Idea开发工具来构建项目
- 选择Spring Initializr来快速构建一个Spring Boot 项目。本示例使用的JDK1.8。
- 设置项目所属的组、项目名称、选择Maven、Java版本。
- 这里要注意Spring Boot的版本,3.x的需要Java17。这里是用的Jdk1.8所以选择2.x版本。
- 这里点击Finish按钮,项目就构建完成了。
2.新建测试对象和修改配置文件
- 创建实体类对象。
1、如果没有加ConfigurationProperties注解配置前缀,那么需要在属性上面配置@Value注解。
2、@Email注解是Spring Boot框架提供的一个数据校验注解,用于检查给定字符串是否是有效电子邮件地址,如果是,则验证通过,否则抛出异常。需要在类上面添加@Validated注解,还需要在pom.xm配置文件添加如下依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
package com.example.demo.entity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Email;
import java.util.List;
@ConfigurationProperties(prefix = "person")
@Component
@Validated
public class Person {
// @Value("${person.name}")
private String name;
// @Value("#{1+2}")
private Integer age;
private String sex;
@Email
private String email;
private List<String> others;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public List<String> getOthers() {
return others;
}
public void setOthers(List<String> others) {
this.others = others;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", email='" + email + '\'' +
", others=" + others +
'}';
}
}
- 修改配置文件。
新建application.yml文件,配置如下:
1、默认生成的文件是application.properties,可以删掉application.properties文件,然后新建yml、yaml文件。
2、spring.profiles.active为多环境配置。
在Spring Boot中多环境配置文件名需要满足application-{xxx}.yml的格式,其中{xxx}对应你的环境标识,比如:
application.yml: 默认配置
application-dev.yml: 开发环境
application-test.yml: 测试环境
application-pord.yml:生产环境
spring:
profiles:
active: test
新建application-test.yml文件,配置如下:
person:
name: lisi
age: 600
sex: 男
email: akdjfad@163.com
others:
- book
- movie
- 新建测试类。
package com.example.demo;
import com.example.demo.entity.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoApplicationTests {
@Autowired
Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
运行结果:Person{name=‘lisi’, age=600, sex=‘男’, others=[book, movie]}
- 自定义配置控制台打印好玩的Banner信息。
1、在resources文件夹下新建一个banner.txt文件。在线生成艺术图案打开链接。生成好后复制到banner.txt文件中即可。
2、如果启动后没生效,可以右击resources文件夹目录Build Module一下然后再次重启服务就能生效。
3、如果要关闭打印艺术图案可以在yml文件中设置参数属性,如下:
spring:
main:
banner-mode: off
3.补充说明
- 不同目录配置文件读取的优先级。
从高到低。
file: ./config
file:./
classpath(resource):config
classpath:./ - 指定不同环境的配置文件启动命令。
nohup java -jar demo.jar --spring.profiles.active=test >/dev/null 2>&1 &
- @ConfigurationProperties 与 @Value 对比。
@ConfigurationProperties | @Value | |
---|---|---|
功能 | 批量注入配置文件中的属性 | 一个个指定 |
松散绑定(松散语法) | 支持 | 不支持 |
SpEL 文本居中 | 不支持 | 支持 |
JSR303数据校验 | 支持 | 不支持 |
复杂类型封装 | 支持 | 不支持 |
三、构建JavaWeb项目
SpringBoot在开发web项目的时候具备很大的优势,现在的大部分企业级开发都是基于SpringBoot框架。在创建一个项目的时候,只需选择我们需要的模块,默认会将我们的需要的模块自动配置好。让开发人员更加专注编写业务代码,不需要像以前那样一大堆的配置,极大的提高开发效率。
1.通过Idea开发工具来构建Web项目
- 这里要注意Spring Boot的版本,3.x的需要Java17。这里是用的Jdk1.8所以选择2.x版本。选择SpringWeb依赖
- 点击Next按钮,直到创建项目成功
- SpringBoot整合Servlet
最早接触Web开发的时候接触的是Servlet,先使用SpringBoot整合Servlet。
1、创建一个Serlvet类
package com.example.demoweb.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "myServletTest",urlPatterns = "/servletUrl")
public class MyServletTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("servlet start....");
resp.getWriter().write("111111111111");
}
}
2、添加配置注解
第一种方式在启动类上面添加@ServletComponentScan注解。
package com.example.demoweb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication
@ServletComponentScan
public class DemowebApplication {
public static void main(String[] args) {
SpringApplication.run(DemowebApplication.class, args);
}
}
第二种方式在启动类里面添加@Bean并且不能添加@ServletComponentScan注解。
package com.example.demoweb;
import com.example.demoweb.servlet.MyServletTest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import java.util.ArrayList;
@SpringBootApplication
public class DemowebApplication {
public static void main(String[] args) {
SpringApplication.run(DemowebApplication.class, args);
}
@Bean
public ServletRegistrationBean<MyServletTest> getServletRegistrationBean(){
ServletRegistrationBean<MyServletTest> bean = new ServletRegistrationBean<>(new MyServletTest());
ArrayList<String> url = new ArrayList<>();
url.add("/servletUrl22"); //如果和类MyServletTest中urlPatterns不一样,以这里add的为准。
bean.setUrlMappings(url);
bean.setLoadOnStartup(1);
return bean;
}
}
第三种方式自定义配置类实现WebMvcConfigurer接口。
package com.example.demoweb.config;
import com.example.demoweb.servlet.MyServletTest;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
@Configuration
public class MyMvcConfigTest implements WebMvcConfigurer {
@Bean
public ServletRegistrationBean<MyServletTest> getServletRegistrationBean(){
ServletRegistrationBean<MyServletTest> bean = new ServletRegistrationBean<>(new MyServletTest());
ArrayList<String> url = new ArrayList<>();
url.add("/servletUrl33");
bean.setUrlMappings(url);
bean.setLoadOnStartup(1);
return bean;
}
}
3、测试结果
请求地址:http://localhost:8888/servletUrl
页面打印:111111111111
- SpringBoot整合过滤器Filter
1、创建一个Filter类
像注册Servlet一样三种实现方式。
package com.example.demoweb.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(filterName = "MyFilterTest", urlPatterns = "/*")
public class MyFilterTest implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("init....");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {
System.out.println("filter....");
chain.doFilter(request,response);
}
@Override
public void destroy() {
System.out.println("destory....");
}
}
- SpringBoot整合监听器Listener
1、Listener是Servlet规范中定义的一种特殊类。
2、主要用于监听ServletContext,HttpSession和ServletRequest等域对象的创建和销毁事件。
3、监听域对象的属性发生修改的事件,用于在事件发生前和发生后做一些必要的处理。
4、可用于:统计在线人数、系统启动时加载初始化信息、统计网站访问量、记录用户访问路径。
1、创建一个监听器Listener类
package com.example.demoweb.config;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
//@WebListener
public class MyHttpSessionListener implements HttpSessionListener {
public static int online=0;
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("创建session.....");
//设置session有效期单位分钟。
se.getSession().setMaxInactiveInterval(2);
online++;
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("销毁session....");
online--;
}
}
2、注册监听器Listener
package com.example.demoweb.config;
import com.example.demoweb.servlet.MyServletTest;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyMvcConfigTest implements WebMvcConfigurer {
@Bean
public ServletListenerRegistrationBean listenerRegist(){
ServletListenerRegistrationBean srb = new ServletListenerRegistrationBean();
srb.setListener(new MyHttpSessionListener());
System.out.println("listener");
return srb;
}
}
- SpringBoot添加控制层Controller
1、创建一个控制层Controller类
package com.example.demoweb.controller;
import com.example.demoweb.config.MyHttpSessionListener;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Controller
public class TestController {
@RequestMapping("/login")
public String login(HttpServletRequest request) {
HttpSession session = request.getSession(true);
return "login";
}
@RequestMapping("online")
@ResponseBody
public String online(){
return "当前在线人数:"+ MyHttpSessionListener.online +"人";
}
}
2、让login方法返回到指定的login.html页面,在static目录中新增该静态页面。
2、还需要再yml文件中新增配置,否则请求不到login.html页面
spring:
mvc:
view:
prefix: /
suffix: .html
3、测试结果
先请求:http://localhost:8888/login
再请求:http://localhost:8888/online
页面打印:当前在线人数:1
- SpringBoot添加欢迎页面
欢迎页面源码中默认读取index.html页面,会这些从目录中查找,优先级由高到低以此查找:
“classpath:/META-INF/resources/”,
“classpath:/resources/”,
“classpath:/static/”,
“classpath:/public/”
其它查找页面也是按照上面目录顺序。
1、第一种方式配置欢迎页面,直接在指定的目录新建index.html即可
1、第二种方式配置欢迎页面,在Controller类中新建一个方法,这种方式可以自定义页面名称。
@RequestMapping("/")
public String index(HttpServletRequest request){
return "index";
}
2.WebMvcConfigurer接口中方法
1、WebMvcConfigurer配置类采用JavaBean的形式来代替传统的xml配置文件,可以自定义自己的实现方式。创建一个配置类实现WebMvcConfigurer接口中方法。
2、在Spring Boot 1.5版本都是靠重写WebMvcConfigurerAdapter的方法来添加自定义拦截器,消息转换器等。SpringBoot 2.0 后,该类被标记为@Deprecated(弃用)。官方推荐直接实现WebMvcConfigurer或者直接继承WebMvcConfigurationSupport。
方式一实现WebMvcConfigurer接口(推荐)
方式二继承WebMvcConfigurationSupport类
参考链接1:打开链接
参考链接2: 打开链接
1、跳转指定页面重写addViewControllers方法
以前如果访问一个页面,须要在Controller类中再写一个方法跳转到页面,有点麻烦。可以重写WebMvcConfigurer中的addViewControllers方法即可。
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/test").setViewName("hello");
}
2、静态资源配置重写addResourceHandlers方法
默认情况下,Spring Boot将下面目录中查找静态资源。
“classpath:/META-INF/resources/”,
“classpath:/resources/”,
“classpath:/static/”,
“classpath:/public/”
如果我们想自定义静态资源映射目录的话,只需重写addResourceHandlers方法即可。
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("file:F:/");
}
根据上面配置,访问/resources下的文件会被映射到本地F:/下的目录里面的静态资源。
3.前端资源WebJars使用
WebJars是被打包成JAR文件形式的前端资源库(例如:jQuery、Bootstrap、CSS等)。
SpringBoot一般将静态文件放在src/main/resources/static目录下。在Servlet3中,可以直接访问到jar包中的/META-INF/resources目录资源,即xxx.jar/META-INF/resources下的资源。故WebJars将前端的静态文件打包成一个jar包,和其它的jar引入一样,能很好的对前端静态资源进行管理。
优点:
1、可以对前端资源进行统一的依赖管理。传统方式是往静态文件夹下(例如/src/main/resources/static/)放入js、css文件,不便于依赖管理的问题。
2、在前端页面中,对引用路径里省略版本号可防止安全问题。
3、WebJars的JAR包部署在Maven中央仓库上方便获取。
官网:https://www.webjars.org/
1、在配置文件pom.xml添加依赖
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>
直接可以在浏览器访问:http://localhost:8888/webjars/jquery/3.4.1/jquery.js
2、在前端页面直接引用
<script src="/webjars/jquery/3.4.1/jquery.js"></script>
如果需要忽略掉版本号,需要加入依赖:
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
<version>0.34</version>
</dependency>
<script src="/webjars/jquery/jquery.min.js"></script>
2、WebJars目录结构
3.注解@RestController和@Controller的区别
@RestController是Spring4后新增的注解,从RestController类源码可以看出@RestController是@Controller和@ResponseBody两个注解的结合体。
1、@Controller注解使类里面的方法返回到一前端页面。
2、@RestController注解,使类里面的方法将以JSON/XML格式返回数据且打印到前端页面。
1、注释@Controller使用
package com.example.demoweb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
@Controller
public class Test2Controller {
@RequestMapping("/hello")
public String show(HttpServletRequest request) {
return "hello";
}
}
返回到页面hello.html
在方法上面添加@ResponseBody(如果添加到类上就针对所有方法),相当于注解@RestController的作用。
package com.example.demoweb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
public class Test2Controller {
@RequestMapping("/hello2")
@ResponseBody
public String show2(HttpServletRequest request) {
return "hello2";
}
}
浏览器页面会直接打印返回的字符串:hello2
2、注释@RestController使用
package com.example.demoweb.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestRestController {
@RequestMapping("/helloRest")
public String show() {
return "helloRest";
}
}
浏览器页面会直接打印返回的字符串:helloRest
如果需要在@RestController中的方法想跳转页面hello.html,则用ModelAndView进行封装即可。
package com.example.demoweb.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
@RestController
public class TestRestController {
@RequestMapping("/helloRest")
public ModelAndView show() {
ModelAndView mv = new ModelAndView("hello");
return mv;
}
}
总结
本文介绍了SpringBoot通过Idea开发工具快速构建一个项目,通过简单的示例演示它的使用过程及注解的使用。让初学者有个快速的入门和了解。