Spring Boot入门

时间:2022-04-24
本文章向大家介绍Spring Boot入门,主要内容包括Spring Boot简介、Spring Boot使用、导入Web模块:、引入Thymeleaf模板引擎开发web项目、Controller类及HTML页面、Thymeleaf模板、Spring Boot整合Spring Security权限、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

Spring Boot简介

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。 用一句话:不用自己做配置,搭建速度快,降低学习门槛。

Spring Boot 在 Spring 生态中的位置:

Spring Boot的特点

  • 为所有Spring开发者更快的入门
  • 不用看那么一坨xml真的很神清气爽
  • 嵌入的Tomcat,无需部署WAR文件
  • 开箱即用,提供各种默认配置来简化项目配置

如:快速在 Java 代码中测试和使用 Spring Boot 的方法:

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*;

@RestController
@EnableAutoConfiguration
public class Example {

    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Example.class, args);
    }

}

Spring Boot使用

打开网址:http://start.spring.io/,按照图中填写信息。

点击Generate Project下载项目压缩包,解压项目包,并用IDE以Maven项目导入

导入Web模块:

在pom.xml中添加:

<dependency>	<groupId>org.springframework.boot</groupId>	<artifactId>spring-boot-starter-web</artifactId> </dependency>

编写Controller类:

publicclassHelenController{ 
@RequestMapping("/hello") 
publicStringindex()
{
return"hello world";
} 
}

这样一个入门的hello 就搭建好了。打开浏览器:http://localhost:8080/hello,你会发现输出:hello word 接下来我们要说说Thymeleaf模板。

引入Thymeleaf模板引擎开发web项目

引入Maven依赖

Controller类及HTML页面

如上页面,直接打开html页面展现Hello World,但是启动程序后,访问http://localhost:8080/,则是展示Controller中host的值:从很小就坏,做到了不破坏HTML自身内容的数据逻辑分离。

Thymeleaf模板

Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可,由Daniel Fernández创建,该作者还是Java加密库Jasypt的作者。 Thymeleaf提供了一个用于整合Spring MVC的可选模块,在应用开发中,你可以使用Thymeleaf来完全代替JSP或其他模板引擎,如Velocity、FreeMarker等。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。接下来,这些标签属性就会在DOM(文档对象模型)上执行预先制定好的逻辑。

Spring Boot整合Spring Security权限

整合Spring Security需要在pom.xml添加依赖

Spring Security配置:

  1. 通过@EnableWebSecurity注解开启Spring Security的功能
  2. 继承WebSecurityConfigurerAdapter,并重写它的方法来设置一些web安全的细节
  3. configure(HttpSecurity http)方法通过authorizeRequests()定义哪些URL需要被保护、哪些不需要被保护。例如以上代码指定了/和/home不需要任何认证就可以访问,其他的路径都必须通过身份验证。
  4. 通过formLogin()定义当需要用户登录时候,转到的登录页面。
  5. configureGlobal(AuthenticationManagerBuilderauth)方法,在内存中创建了一个用户,该用户的名称为user,密码为password,用户角色为USER。

然后在Controller做拦截操作。

结果页面

最后启动http://localhost:8080/就可以啦

附:thymeleaf 中文文档 thymeleaf 基础教程