SpringBoot与Web开发(超详细)【篇一】

1、引入Thymeleaf


Thymeleaf官网

在pom.xml中添加以下依赖:

org.springframework.boot

spring-boot-starter-thymeleaf

2、Thymeleaf的使用


@ConfigurationProperties(prefix = “spring.thymeleaf”)

public class ThymeleafProperties {

private static final Charset DEFAULT_ENCODING = Charset.forName(“UTF-8”);

private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf(“text/html”);

public static final String DEFAULT_PREFIX = “classpath:/templates/”;

public static final String DEFAULT_SUFFIX = “.html”;

只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染。

success.html:

在这里插入图片描述

HelloController:

package com.keafmd.springboot.controller;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

/**

  • Keafmd

  • @ClassName: HelloController

  • @Description:

  • @author: 牛哄哄的柯南

  • @date: 2021-03-04 19:54

*/

@Controller

public class HelloController {

@ResponseBody

@RequestMapping(“/hello”)

public String hello(){

return “Hello World”;

}

@RequestMapping(“/success”)

public String success() {

return “success”;

}

}

访问success的结果:

在这里插入图片描述

1、导入thymeleaf的名称空间

2、使用thymeleaf语法

HelloController:

package com.keafmd.springboot.controller;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**

  • Keafmd

  • @ClassName: HelloController

  • @Description:

  • @author: 牛哄哄的柯南

  • @date: 2021-03-04 19:54

*/

@Controller

public class HelloController {

@ResponseBody

@RequestMapping(“/hello”)

public String hello(){

return “Hello World”;

}

/**

  • 查出一些数据在页面显示

  • @param map

  • @return

*/

@RequestMapping(“/success”)

public String success(Map<String,Object> map) {

map.put(“hello”,“你好”);

return “success”;

}

}

success.html:

Title

成功

运行结果:

在这里插入图片描述

3、Thymeleaf的语法规则


1、th:任意html属性,来替换原生属性的值

th:text — 改变当前元素里面的文本内容

更多参考下图:

在这里插入图片描述

2、表达式

Simple expressions:(表达式语法)

Variable Expressions: ${…}:获取变量值;OGNL;

1)、获取对象的属性、调用方法

2)、使用内置的基本对象:

#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.

${session.foo}

3)、内置的一些工具对象:

#execInfo : information about the template being processed.

#messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.

#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.

#ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).

Selection Variable Expressions: *{…}:选择表达式:和${}在功能上是一样;

补充:配合 th:object="${session.user}:

Name: Sebastian.

Surname: Pepper.

Nationality: Saturn.

Message Expressions: #{…}:获取国际化内容

Link URL Expressions: @{…}:定义URL;

@{/order/process(execId=${execId},execType=‘FAST’)}

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: _

注意内容过多,详细内容参考官方文档

示例:↓

HelloController:

package com.keafmd.springboot.controller;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;

import java.util.Map;

/**

  • Keafmd

  • @ClassName: HelloController

  • @Description:

  • @author: 牛哄哄的柯南

  • @date: 2021-03-04 19:54

*/

@Controller

public class HelloController {

@ResponseBody

@RequestMapping(“/hello”)

public String hello(){

return “Hello World”;

}

/**

  • 查出一些数据在页面显示

  • @param map

  • @return

*/

@RequestMapping(“/success”)

public String success(Map<String,Object> map) {

map.put(“hello”,“你好”);

map.put(“hello1”,“

你好

”);

map.put(“users”, Arrays.asList(“柯南”,“小兰”,“基德”));

return “success”;

}

}

success.html:

Title

成功

这里的内容被覆盖



[[${user}]]

效果:

在这里插入图片描述

在这里插入图片描述

四、SpringMVC自动配置

=========================================================================

1、Spring MVC auto-configuration


参考官方文档:点这里

Spring Boot 自动配置好了SpringMVC

以下是SpringBoot对SpringMVC的默认配置:(WebMvcAutoConfiguration)

  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.

  • 自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染(转发?重定向?))

  • ContentNegotiatingViewResolver:组合所有的视图解析器的。

  • 如何定制:我们可以自己给容器中添加一个视图解析器;自动的将其组合进来。

  • Support for serving static resources, including support for WebJars (see below).静态资源文件夹路径,webjars

  • Static index.html support. 静态首页访问

  • Custom Favicon support (see below). favicon.ico

  • 自动注册了 of Converter, GenericConverter, Formatter beans.

  • Converter:转换器; public String hello(User user):类型转换使用Converter

  • Formatter :格式化器; 2017.12.17===Date

@Bean

@ConditionalOnProperty(prefix = “spring.mvc”, name = “date-format”)//在文件中配置日期格式化的规则

public Formatter dateFormatter() {

return new DateFormatter(this.mvcProperties.getDateFormat());//日期格式化组件

}

自己添加的格式化器转换器,我们只需要放在容器中即可

  • Support for HttpMessageConverters (see below).

  • HttpMessageConverter:SpringMVC用来转换Http请求和响应的;User—Json

  • HttpMessageConverters 是从容器中确定;获取所有的HttpMessageConverter

自己给容器中添加HttpMessageConverter,只需要将自己的组件注册容器中(@Bean,@Component)

  • Automatic registration of MessageCodesResolver (see below):定义错误代码生成规则

  • Automatic use of a ConfigurableWebBindingInitializer bean (see below).

我们可以配置一个ConfigurableWebBindingInitializer来替换默认的(添加到容器)

初始化WebDataBinder

请求数据=====JavaBean

org.springframework.boot.autoconfigure.web:web的所有自动场景

If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (interceptors, formatters, view controllers etc.) you can add your own @Configuration class of type WebMvcConfigurerAdapter, but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter or ExceptionHandlerExceptionResolver you can declare a WebMvcRegistrationsAdapter instance providing such components.

如果你想保持Spring Boot MVC 功能,你只是想添加额外的(MVC配置)(https://docs.spring.io/spring/docs/4.3.14.RELEASE/spring-framework-reference/htmlsingle MVC)(拦截器,格式器,视图控制器等)您可以添加自己的@ configuration类WebMvcConfigurerAdapter类型,但没有@EnableWebMvc。如果你想提供RequestMappingHandlerMapping, RequestMappingHandlerAdapter或ExceptionHandlerExceptionResolver的自定义实例,你可以声明一个WebMvcRegistrationsAdapter实例来提供这样的组件。

If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.

如果你想完全控制Spring MVC,你可以添加你自己的@Configuration注解@EnableWebMvc。

2、扩展SpringMVC


实现如下功能:

<mvc:view-controller path=“/hello” view-name=“success”></mvc:view-controller>

mvc:interceptors

mvc:interceptor

<mvc:mapping path=“/hello”/>

</mvc:interceptor>

</mvc:interceptors>

做法:编写一个配置类(@Configuration),是WebMvcConfigurerAdapter类型;不能标注@EnableWebMvc

特点:既保留了所有的自动配置,也能用我们扩展的配置。

在config包下创建个MyMvcConfig。

在这里插入图片描述

代码实现:

package com.keafmd.springboot.config;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**

  • Keafmd

  • @ClassName: MyMvcConfig

  • @Description:

  • @author: 牛哄哄的柯南

  • @date: 2021-03-17 20:26

*/

@Configuration

public class MyMvcConfig implements WebMvcConfigurer {

@Override

public void addViewControllers(ViewControllerRegistry registry) {

//浏览器发送 /keafmd 请求 来到success页面

registry.addViewController(“/keafmd”).setViewName(“success”);

}

}

原理

**1、WebMvcAutoConfiguration是SpringMVC的自动配置类。

​ 2、在做其他自动配置时会导入,@Import(EnableWebMvcConfiguration.class)。**

@Configuration

public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {

private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();

//从容器中获取所有的WebMvcConfigurer

@Autowired(required = false)

public void setConfigurers(List configurers) {

if (!CollectionUtils.isEmpty(configurers)) {

this.configurers.addWebMvcConfigurers(configurers);

//一个参考实现;将所有的WebMvcConfigurer相关配置都来一起调用;

@Override

// public void addViewControllers(ViewControllerRegistry registry) {

// for (WebMvcConfigurer delegate : this.delegates) {

// delegate.addViewControllers(registry);

// }

}

}

}

最后

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。

因此收集整理了一份《2024年Web前端开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点!不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
dWebMvcConfigurers(configurers);

//一个参考实现;将所有的WebMvcConfigurer相关配置都来一起调用;

@Override

// public void addViewControllers(ViewControllerRegistry registry) {

// for (WebMvcConfigurer delegate : this.delegates) {

// delegate.addViewControllers(registry);

// }

}

}

}

最后

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。

因此收集整理了一份《2024年Web前端开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

[外链图片转存中…(img-gMVHtWFI-1714955391846)]

[外链图片转存中…(img-wpXREHS5-1714955391847)]

[外链图片转存中…(img-1UJXRupm-1714955391847)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点!不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

  • 21
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 是一个快速构建基于 Spring 框架的应用程序的工具。它为 Spring 应用程序开发提供了一种简单的方法,无需繁琐地配置 XML,只需要使用注解即可实现常见的业务逻辑。 下面是一个基本的 Spring Boot Web 应用程序的步骤: 1. 创建一个 Maven 项目,并添加 Spring Boot 的依赖。 2. 创建一个 Controller 类,并添加处理请求的方法。 3. 配置应用程序的入口点,并启动应用程序。 以下是一个简单的示例: 1. 创建 Maven 项目 使用 Maven 创建一个新的项目,可以参考以下命令: ``` mvn archetype:generate -DgroupId=com.example -DartifactId=webapp -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false ``` 2. 添加 Spring Boot 依赖 在 pom.xml 文件中添加 Spring Boot Starter Web 依赖: ``` <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> ``` 3. 创建 Controller 类 创建一个 HomeController 类,并添加处理请求的方法: ``` @RestController public class HomeController { @GetMapping("/") public String home() { return "Hello, World!"; } } ``` 4. 配置应用程序的入口点 创建一个 SpringBootWebApplication 类,并使用 @SpringBootApplication 注解标记为应用程序的入口点: ``` @SpringBootApplication public class SpringBootWebApplication { public static void main(String[] args) { SpringApplication.run(SpringBootWebApplication.class, args); } } ``` 5. 启动应用程序 使用以下命令启动应用程序: ``` mvn spring-boot:run ``` 在浏览器中访问 http://localhost:8080/ ,即可看到 "Hello, World!"。 这就是一个简单的 Spring Boot Web 应用程序的开发过程。当然,除了以上步骤,还有很多其他的配置和实现方式,具体可以参考官方文档。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值