SpringBoot 学习日志4.使用SpringBoot进行Web开发上(使用IDEA)

参考博客 

Web开发探究

使用SpringBoot的步骤:

1、创建一个SpringBoot应用,选择需要的模块,SpringBoot会默认将需要的模块自动配置好

2、手动在配置文件进行部分配置,项目便可以运行

3、专注编写业务代码,不需要考虑以前那样一大堆的配置了。

要熟悉掌握开发,之前学习的自动配置的原理一定要搞明白!

比如SpringBoot到底帮我们配置了什么?我们能不能修改?我们能修改哪些配置?我们能不能扩展?

  • 向容器中自动配置组件 :xxxAutoconfiguration

  • 自动配置类,封装配置文件的内容:xxxProperties

Web要解决的问题:

  • 导入静态资源(image,css,js)
  • 首页
  • jsp,模板引擎Thymeleaf
  • 配置扩展SpringMVC
  • 增删改查业务编写
  • 拦截器
  • 国际化

静态资源处理

SpringBoot中,SpringMVC的web配置都在 WebMvcAutoConfiguration 配置类里面,WebMvcAutoConfigurationAdapter 中有很多配置方法。

addResourceHandlers 添加资源处理


@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        // 禁用默认资源处理
        logger.debug("Default resource handling disabled");
        return;
    }
    // 缓存控制
    Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
    CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
    // webjars文件夹 
    if (!registry.hasMappingForPattern("/webjars/**")) {
        customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
                                             .addResourceLocations("classpath:/META-INF/resources/webjars/")
                                             .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
    }
    // 静态资源配置
    String staticPathPattern = this.mvcProperties.getStaticPathPattern();
    if (!registry.hasMappingForPattern(staticPathPattern)) {
        customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
                                             .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
                                             .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
    }
}

比如所有 /webjars/**的路径 , 都需要去 classpath:/META-INF/resources/webjars/ 找对应的资源;

什么是webjars ?

Webjars本质就是以jar包的方式引入静态资源 , 以前要导入一个静态资源文件,直接导入即可。

使用SpringBoot需要使用Webjars,网站:https://www.webjars.org

使用jQuery(引入jQuery对应版本的pom依赖即可)


<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.4.1</version>
</dependency>

目录结构:

访问:只要是静态资源,SpringBoot就会去对应的路径寻找改静态资源,我们这里访问:http://localhost:8080/webjars/jquery/3.6.0/jquery.js

其他自动配置的静态资源映射规则

项目中要是使用自己的静态资源该如何导入呢?

			addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
				registration.addResourceLocations(this.resourceProperties.getStaticLocations());
				if (servletContext != null) {
					registration.addResourceLocations(new ServletContextResource(servletContext, SERVLET_LOCATION));
				}
			});
		    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
				"classpath:/resources/", "classpath:/static/", "classpath:/public/" };

由代码可得,在staticPathPattern发现另一种映射规则 :/** , 访问当前项目的任意静态资源,会去找 WebProperties类。

WebProperties可以设置和静态资源有关的参数;这里指明了寻找静态资源的文件夹,即上面数组的内容。

结论:

以下四个目录存放的静态资源可以被我们识别:

"classpath:/META-INF/resources/"
"classpath:/resources/"
"classpath:/static/"
"classpath:/public/"

因此,可以在resources根目录下新建对应的文件夹,来存放静态资源文件。

自定义静态资源路径

可以通过配置文件来指定一下静态资源路径,在application.properties中配置;

spring.resources.static-locations=classpath:/coding/,classpath:/qqa/

注意:一旦自己定义了静态文件夹的路径,原来的自动配置就都会失效了!

首页处理

源代码

		@Bean
		public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
				FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
			WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
					new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
					this.mvcProperties.getStaticPathPattern());
			welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
			welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
			return welcomePageHandlerMapping;
		}

		private Resource getWelcomePage() {
			for (String location : this.resourceProperties.getStaticLocations()) {
				Resource indexHtml = getIndexHtml(location);
				if (indexHtml != null) {
					return indexHtml;
				}
			}
			ServletContext servletContext = getServletContext();
			if (servletContext != null) {
				return getIndexHtml(new ServletContextResource(servletContext, SERVLET_LOCATION));
			}
			return null;
		}

		private Resource getIndexHtml(Resource location) {
			try {
				Resource resource = location.createRelative("index.html");
				if (resource.exists() && (resource.getURL() != null)) {
					return resource;
				}
			}
			catch (Exception ex) {
			}
			return null;
		}

由此可见,欢迎页就是静态资源文件夹下的所有 index.html 页面;映射路径为/**

比如,访问  http://localhost:8080/ ,就会映射到静态资源文件夹下的 index.html。

Thymeleaf

模板引擎

前端请求给后台的页面是html(静态)页面。以前的后端开发,需要转成jsp页面,jsp好处就是当我们在数据库查出一些数据后,转发到JSP页面,可以轻松的实现数据的显示及交互等。

jsp支持非常强大的功能,包括能写Java代码。

但是,目前,第一,SpringBoot是以jar包的方式打包,而不是war包;第二,服务器还是嵌入式的Tomcat,而Tomcat现在不支持jsp的

那不支持jsp,如果直接用纯静态页面的方式,会给开发会带来非常大的麻烦,那怎么办?

SpringBoot推荐使用模板引擎:

模板引擎,我们其实大家听到很多,其实jsp就是一个模板引擎,还有用的比较多的freemarker,包括SpringBoot推荐的是Thymeleaf,模板引擎有非常多,但再多的模板引擎,他们的思想都是一样的,如下图:

图片

模板引擎的作用就是一个页面模板,但其中有些值是动态的,使用表达式表示的。这些值的具体取值,就是后台封装一些数据。将模板(Template)和数据(Data)交给模板引擎,模板引擎会按照数据把表达式解析、填充到我们指定的位置,然后数据最终形成了一个我们想要的内容给我们返回出去,这就是模板引擎。不管是jsp还是其他模板引擎,都是这个思想。只不过,不同的模板引擎之间,语法有点不一样。Thymeleaf模板引擎,是一个高级语言的模板引擎,他的语法更简单,功能更强大。

引入Thymeleaf

对于springboot来说,所有功能场景都是一个starter,在项目中引入一下即可。

        <!--Thymeleaf 模板引擎,基于3.x开发-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

Thymeleaf自动配置及使用

按照SpringBoot的自动装配原理,查看Thymeleaf的自动配置规则,再按照规则进行使用。

源代码:

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

	private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;

	public static final String DEFAULT_PREFIX = "classpath:/templates/";

	public static final String DEFAULT_SUFFIX = ".html";

	/**
	 * Whether to check that the template exists before rendering it.
	 */
	private boolean checkTemplate = true;

	/**
	 * Whether to check that the templates location exists.
	 */
	private boolean checkTemplateLocation = true;

	/**
	 * Prefix that gets prepended to view names when building a URL.
	 */
	private String prefix = DEFAULT_PREFIX;

	/**
	 * Suffix that gets appended to view names when building a URL.
	 */
	private String suffix = DEFAULT_SUFFIX;

	/**
	 * Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
	 */
	private String mode = "HTML";

	/**
	 * Template files encoding.
	 */
	private Charset encoding = DEFAULT_ENCODING;

	/**
	 * Whether to enable template caching.
	 */
	private boolean cache = true;
}

结论:

可以看到默认的前缀和后缀,因此只需要把html页面放在项目路径下的templates文件夹下,thymeleaf就可以帮助我们自动渲染页面了。

总之,使用thymeleaf不需要配置任何东西,只需要将html页面放在指定的文件夹下即可!

Thymeleaf 语法学习

要学习语法,还是参考官网文档最为准确,我们找到对应的版本看一下。Thymeleaf 官网:https://www.thymeleaf.org/ , 简单看一下官网!我们去下载Thymeleaf的官方文档!

前提:使用thymeleaf,需要在html文件中导入命名空间的约束,方便提示。

可以在官方文档的#3中找命名空间:

 xmlns:th="http://www.thymeleaf.org"

1、可以使用任意的 th:attr 来替换Html中原生属性的值,类比jsp。

图片

2、表达式


Simple expressions:(表达式语法)
Variable Expressions: ${...}:获取变量值;OGNL;
    1)、获取对象的属性、调用方法
    2)、使用内置的基本对象:#18
         #ctx : the context object.
         #vars: the context variables.
         #locale : the context locale.
         #request : (only in Web Contexts) the HttpServletRequest object.
         #response : (only in Web Contexts) the HttpServletResponse object.
         #session : (only in Web Contexts) the HttpSession object.
         #servletContext : (only in Web Contexts) the ServletContext object.

    3)、内置的一些工具对象:
      #execInfo : information about the template being processed.
      #uris : methods for escaping parts of URLs/URIs
      #conversions : methods for executing the configured conversion service (if any).
      #dates : methods for java.util.Date objects: formatting, component extraction, etc.
      #calendars : analogous to #dates , but for java.util.Calendar objects.
      #numbers : methods for formatting numeric objects.
      #strings : methods for String objects: contains, startsWith, prepending/appending, etc.
      #objects : methods for objects in general.
      #bools : methods for boolean evaluation.
      #arrays : methods for arrays.
      #lists : methods for lists.
      #sets : methods for sets.
      #maps : methods for maps.
      #aggregates : methods for creating aggregates on arrays or collections.
==================================================================================

  Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;
  Message Expressions: #{...}:获取国际化内容
  Link URL Expressions: @{...}:定义URL;
  Fragment Expressions: ~{...}:片段引用表达式

Literals(字面量)
      Text literals: 'one text' , 'Another one!' ,…
      Number literals: 0 , 34 , 3.0 , 12.3 ,…
      Boolean literals: true , false
      Null literal: null
      Literal tokens: one , sometext , main ,…
      
Text operations:(文本操作)
    String concatenation: +
    Literal substitutions: |The name is ${name}|
    
Arithmetic operations:(数学运算)
    Binary operators: + , - , * , / , %
    Minus sign (unary operator): -
    
Boolean operations:(布尔运算)
    Binary operators: and , or
    Boolean negation (unary operator): ! , not
    
Comparisons and equality:(比较运算)
    Comparators: > , < , >= , <= ( gt , lt , ge , le )
    Equality operators: == , != ( eq , ne )
    
Conditional operators:条件运算(三元运算符)
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)
    
Special tokens:
    No-Operation: _

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
### 回答1: 好的,我可以使用中文回答这个问题。 要在 IntelliJ IDEA使用 Spring Boot 开发框架,需要安装 Spring Boot 插件。以下是在 IntelliJ IDEA 中安装和使用 Spring Boot 插件的步骤: 1. 打开 IntelliJ IDEA,并转到 File > Settings > Plugins。 2. 在搜索栏中输入“Spring Boot”,然后按下回车键。 3. 点击“Install”按钮,等待插件安装完成。 4. 重新启动 IntelliJ IDEA。 现在,您可以创建 Spring Boot 项目。以下是创建 Spring Boot 项目的步骤: 1. 转到 File > New > Project。 2. 选择“Spring Initializr”选项。 3. 选择项目类型、语言和 Spring Boot 版本,然后单击“Next”按钮。 4. 配置项目元数据,如项目名称、包名和项目位置。 5. 单击“Next”按钮,然后配置项目依赖项。 6. 单击“Finish”按钮,创建项目。 现在,您可以在 IntelliJ IDEA使用 Spring Boot 开发框架了。您可以编写 Spring Boot 应用程序,并运行、测试和调试它们。 ### 回答2: Spring Boot开发脚手架Idea插件是一种能够加快Spring Boot项目开发的工具,通过该插件可以在Idea开发环境中更便捷地创建和配置Spring Boot项目。它提供了一些自动化的功能,让开发者能够快速搭建项目骨架和集成常用组件。 首先,脚手架插件可以帮助我们快速创建Spring Boot项目。在Idea中,我们可以通过该插件选择不同的项目模板,包括基础的Spring Boot项目、Web项目、数据库连接等等。这样,我们就不需要从零开始创建项目,只需要根据需求选择对应的模板即可。同时,插件还能自动生成项目的基本结构和配置文件,提供了一种快速启动项目的方式。 其次,脚手架插件能够方便地集成常用组件。在开发过程中,我们经常需要使用到一些常用的依赖,例如数据库连接、缓存、安全等等。而插件可以在创建项目时给我们提供这些常用组件的选项,我们只需要勾选对应的组件即可,插件会自动下载并引入相关的依赖包。这样,我们就不需要手动配置这些依赖,减少了重复劳动,提高了效率。 此外,脚手架插件还能够提供一些自动化的功能。比如,它可以自动帮我们生成一些常见的代码模板,如控制器、服务、实体类等。我们只需要提供一些必要的信息,插件就能快速生成相应的代码,减少了手动编写的工作量。同时,插件还能提供代码优化和检查的功能,帮助我们提高代码质量。 综上所述,Spring Boot开发脚手架Idea插件是一种能够加快项目开发速度的工具。它能够帮助我们快速创建项目、集成常用组件,并提供一些自动化的功能。通过使用该插件,我们可以更加高效地进行Spring Boot项目的开发。 ### 回答3: Spring Boot开发脚手架是一个非常实用的工具,可以帮助我们快速搭建Spring Boot项目的基础结构和所需的配置。而IDEA插件则是为了方便开发人员在开发过程中更快速、高效地使用Spring Boot脚手架提供的功能。 首先,Spring Boot开发脚手架通常包含了一些常用的模块和功能,比如数据库访问、RESTful接口、日志记录等。这些功能在每个新项目中都是必须的,但是手动配置和搭建这些功能会很繁琐。使用IDEA插件可以很方便地创建一个全新的Spring Boot项目,自动集成了这些常用模块和功能,省去了手动配置的麻烦。 其次,IDEA插件还提供了一些便捷的功能,例如自动代码生成、快速导航和调试等。在使用Spring Boot脚手架开发项目的过程中,我们常常需要创建实体类、DAO层、Service层和Controller层等,这些代码的编写是比较繁琐和重复的。通过IDEA插件提供的自动代码生成功能,我们只需要输入相关信息,插件就可以根据模板自动生成所需的代码,大大提高了开发效率。另外,IDEA插件还可以方便地导航项目的各个部分,提供了快速访问工具、类和方法的定位等功能,让开发者更容易理清代码的结构和关系。同时,在调试过程中,IDEA插件提供了一些方便的调试工具和快捷键,可以快速定位和解决问题。 总结来说,Spring Boot开发脚手架IDEA插件在开发过程中可以帮助开发者更快地搭建Spring Boot项目的基础结构和所需的配置,提供了自动代码生成、快速导航和调试等便捷功能,可以大大提高开发效率和代码质量。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值