模块:spring-boot-starter-base-web
Web
开发是开发中相当重要的一部分, Web
开发的核心内容主要包括内嵌Servlet
容器和Spring MVC
。更重要的是,Spring Boot``为web
开发提供了快捷便利的方式进行开发,使用依赖jar:spring-boot-starter-web
,提供了嵌入式服务器Tomcat
以及Spring MVC
的依赖,且自动配置web
相关配置,可查看org.springframework.boot.autoconfigure.web
。html
Web
相关的核心功能:git
Thymeleaf
模板引擎Web
相关配置Tomcat
配置Favicon
配置 Spring Boot
提供了大量模板引擎, 包含括FreeMarker
、Groovy
、 Thymeleaf
、 Velocity和Mustache
, Spring Boot
中推荐 使用Thymeleaf
做为模板引擎, 由于Thymeleaf
提供了完美的Spring MVC
的支持。github
在Spring Boot
的org.springframework.boot.autoconfigure.thymeleaf
包下实现自动配置,以下所示:web
ThymeleafAutoConfiguration
源码:spring
@Configuration
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration {
//配置TemplateResolver
@Configuration
@ConditionalOnMissingBean(name = "defaultTemplateResolver")
static class DefaultTemplateResolverConfiguration {
...
}
//配置TemplateEngine
@Configuration
protected static class ThymeleafDefaultConfiguration {
...
}
//配置SpringWebFluxTemplateEngine
@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnProperty(name = "spring.thymeleaf.enabled", matchIfMissing = true)
static class ThymeleafWebMvcConfiguration {
...
}
//配置thymeleafViewResolver
@Configuration
@ConditionalOnWebApplication(type = Type.REACTIVE)
@ConditionalOnProperty(name = "spring.thymeleaf.enabled", matchIfMissing = true)
static class ThymeleafWebFluxConfiguration {
...
}
...
}
复制代码
ThymeleafAutoConfiguration
自动加载Web
所需的TemplateResolver
、TemplateEngine
、SpringWebFluxTemplateEngine
以及thymeleafViewResolver
,并经过ThymeleafProperties
进行Thymeleaf
属性配置。详细细节查看官方源码。tomcat
ThymeleafProperties
源码:服务器
//读取application.properties配置文件的属性
@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";
/**
*Web模板文件前缀路径属性,Spring boot默认路径为classpath:/templates/
*/
private String prefix = DEFAULT_PREFIX;
/**
* Web模板文件后缀属性,默认为html
*/
private String suffix = DEFAULT_SUFFIX;
/**
* Web模板模式属性,默认为HTML
*/
private String mode = "HTML";
/**
* Web模板文件编码属性,默认为UTF_8
*/
private Charset encoding = DEFAULT_ENCODING;
....
}
复制代码
能够从ThymeleafProperties
中看出,Thymeleaf
的默认设置,以及能够经过前缀为spring.thymeleaf
属性修改Thymeleaf
默认配置。app
1).根据默认Thymeleaf
配置,在src/main/resources/
下,建立static
文件夹存放脚本样式静态文件以及templates
文件夹存放后缀为html的页面,以下所示:ide
2)index.html页面spring-boot
<!DOCTYPE html>
<!-- 导入xmlns: th=http://www.thymeleaf.org命名空间 -->
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首面详细</title>
</head>
<body>
<div class="user" align="center" width="400px" height="400px">
message:<span th:text="${user.message}"/><br/>
用户名:<span th:text="${user.username}"/><br/>
密码:<span th:text="${user.password}"/>
</div>
</body>
</html>
复制代码
3).controller
配置:
@Controller
public class LoginController {
@Autowired
private LoginService loginService;
/**
* 将首页设置为登录页面login.html
* @return
*/
@RequestMapping("/")
public String startIndex() {
return "login";
}
/**
* 登录验证
* @param username
* @param password
* @param model
* @return
*/
@RequestMapping("/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model) {
UserDTO userDTO = loginService.login(username, password);
model.addAttribute("user", userDTO);
return "index";
}
}
复制代码
web
相关配置根据WebMvcAutoConfiguration
以及WebMvcProperties
理解Spring Boot
提供的自动配置原理。
ViewResolver
以及静态资源Spring boot
自动配置ViewResolver
:
ContentNegotiatingViewResolver
(最高优先级Ordered.HIGHEST_PRECEDENCE
)BeanNameViewResolver
InternalResourceViewResolver
静态资源:
addResourceHandlers
方法默认定义了/static
、 /public
、 /resources
和/METAINF/resources
文件夹下的静态文件直接映射为/**
addFormatters
方法会自动加载Converter
、GenericConverter
以及Formatter
的实现类、并注册到Spring MVC中,所以自定义类型转换器只需继承其三个接口便可。
自定义Formatter
:
/**
* 将格式为 ccww:ccww88转为UserDTO
*
* @Auther: ccww
* @Date: 2019/10/4 16:25
* @Description:
*/
public class StringToUserConverter implements Converter<String, UserDTO> {
@Nullable
public UserDTO convert(String s) {
UserDTO userDTO = new UserDTO();
if (StringUtils.isEmpty(s))
return userDTO;
String[] item = s.split(":");
userDTO.setUsername(item[0]);
userDTO.setPassword(item[1]);
return userDTO;
}
}
复制代码
HttpMessageConverters
(HTTP request
(请求)和response
(响应)的转换器)configureMessageConverters
方法自动配置HttpMessageConverters:
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
this.messageConvertersProvider.ifAvailable((customConverters) -> converters
.addAll(customConverters.getConverters()));
}
复制代码
经过加载由HttpMessageConvertersAutoConfiguration
定义的HttpMessageConverters
,会自动注册一系列HttpMessage Converter
类,好比Spring MVC
默认:
ByteArrayHttpMessageConverter
StringHttpMessageConverter
ResourceHttpMessageConverter
SourceHttpMessageConverter
AllEncompassingFormHttpMessageConverter
自定义HttpMessageConverters
,只须要在自定义的HttpMessageConverters
的Bean
注册自定义HttpMessageConverter
便可。 以下:
注册自定义的HttpMessageConverter
:
@Configuration
public class CustomHttpMessageConverterConfig {
@Bean
public HttpMessageConverters converter(){
HttpMessageConverter<?> userJsonHttpMessageConverter=new UserJsonHttpMessageConverter();
return new HttpMessageConverters(userJsonHttpMessageConverter);
}
}
复制代码
自定义HttpMessageConverter
:
public class UserJsonHttpMessageConverter extends AbstractHttpMessageConverter<UserDTO> {
private static Charset DEFUALT_ENCODE=Charset.forName("UTF-8");
public UserJsonHttpMessageConverter(){
super(new MediaType("application", "xxx-ccww", DEFUALT_ENCODE));
}
protected boolean supports(Class aClass) {
return UserDTO.class == aClass;
}
protected UserDTO readInternal(Class aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
String message = StreamUtils.copyToString(httpInputMessage.getBody(), DEFUALT_ENCODE);
String[] messages = message.split("-");
UserDTO userDTO = new UserDTO();
userDTO.setUsername(messages[0]);
userDTO.setMessage(messages[1]);
return userDTO;
}
protected void writeInternal(UserDTO userDTO, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
String out = "ccww: " + userDTO.getUsername() + "-" + userDTO.getMessage();
httpOutputMessage.getBody().write(out.getBytes());
}
}
复制代码
同理,能够将Servlet、Filter以及Listener相对于的注册便可。
自定义的MVC配置类上加@EnableWebMvc
将废弃到Spring boot
默认配置,彻底由本身去控制MVC
配置,但一般是Springboot
默认配置+所需的额外MVC
配置,只须要配置类继承WebMvcConfigurerAdapter
便可
Tomcat
配置可使用两种方式进行Tomcat
配置属性
application.properties
配置属性便可,Tomcat
是以"server.tomcat
"为前缀的特有配置属性,通用的是以"server
"做为前缀;WebServerFactoryCustomizer
接口自定义属性配置类便可,同理其余服务器实现对应的接口便可。application.properties
配置属性:
#通用Servlet容器配置
server.port=8888
#tomcat容器配置
#配置Tomcat编码, 默认为UTF-8
server.tomcat.uri-encoding = UTF-8
# Tomcat是否开启压缩, 默认为关闭off
server.tomcat.compression=off
复制代码
实现WebServerFactoryCustomizer
接口自定义:
/**
* 配置tomcat属性
* @Auther: ccww
* @Date: 2019/10/5 23:22
* @Description:
*/
@Component
public class CustomTomcatServletContainer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
public void customize(ConfigurableServletWebServerFactory configurableServletWebServerFactory) {
((TomcatServletWebServerFactory)configurableServletWebServerFactory).addConnectorCustomizers(new TomcatConnectorCustomizer() {
public void customize(Connector connector) {
Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
protocol.setMaxConnections(200);
protocol.setMaxThreads(200);
protocol.setSelectorTimeout(3000);
protocol.setSessionTimeout(3000);
protocol.setConnectionTimeout(3000);
protocol.setPort(8888);
}
});
}
}
复制代码
替换spring boot
默认Servle
t容器tomcat
,直接在依赖中排除,并导入相应的Servlet
容器依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starterweb</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-startertomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starterjetty</artifactId>
</dependency
复制代码
Favicon
自定义Favicon
只须要则只需将本身的favicon.ico
( 文件名不能变更) 文件放置在类路径根目录、 类路径META-INF/resources/
下、 类路径resources/
下、 类路径static/
下或类路径public/
下。