Spring Boot Web开发

Scroll Down

Spring Boot Web开发

静态资源处理

  1. 通过webjars存放静态资源

    if (!registry.hasMappingForPattern("/webjars/**")) {
    				customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
    						.addResourceLocations("classpath:/META-INF/resources/webjars/")
    						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
    			}
    

    WebMvcAutoConfiguration中写出了静态资源可以存放于特点的位置:

    1. /webjars/**
    2. /META-INF/resources/webjars/

    这里面的内容可以直接访问

  2. ResourceProperties中指明了第二个静态资源可以存放的位置

    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
    			"classpath:/resources/", "classpath:/static/", "classpath:/public/" };
    
    1. /META-INF/resources/**
    2. /resources/**
    3. /static/**
    4. /public/**
    5. /**

    静态资源可以存放于这些目录之下

  3. 静态资源的自定义

    spring:
      mvc:
        static-path-pattern: 
    

首页定制

@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));
    return welcomePageHandlerMapping;
}


private Resource getIndexHtml(String location) {
    return this.resourceLoader.getResource(location + "index.html");
}

WebMvcAutoConfiguration中有一个WelcomePageHandlerMapping的Bean,里面是处理首页数据的

WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
ApplicationContext applicationContext, Optional<Resource> welcomePage, String staticPathPattern) {
if (welcomePage.isPresent() && "/**".equals(staticPathPattern)) {
logger.info("Adding welcome page: " + welcomePage.get());
setRootViewName("forward:index.html");
}
else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
logger.info("Adding welcome page template: index");
setRootViewName("index");
}
}

可见mvc 的自动配置是去静态资源路径下找index.html文件

跳转到首页

需要thymeleaf 模板引擎

把首页放到templates文件夹下

编写Controller

@Controller
public class IndexController {
    @RequestMapping("/index")
    public String toIndex()
    {
        return "index";
    }
}

thymeleaf 模板引擎

在pom.xml中引入

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>

在Thymeleaf的配置中写道

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

public static final String DEFAULT_SUFFIX = ".html";

Thymeleaf的文件都在template中,后缀为html

thymeleaf语法

参考:https://www.cnblogs.com/chenlove/p/9375756.html

引用命名空间

<html xmlns:th="http://www.thymeleaf.org"> 

输出内容

<p th:text="#{home.welcome}">Welcome to our grocery store!</p>
  1. 使用th:text使内容输出到标签中
  2. #{}用来引用属性
  3. th:utext不会对转义

访问对象

${param.x} 返回名为x 的 request参数。(可能有多个值)

${session.x} 返回名为x的Session参数。

${application.x} 返回名为 servlet context 的参数。

输出url

<a href="product/list.html" th:href="@{/product/list}">Product List</a>

<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>

设置Attribute

<input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>   --设置单个

<img src="../../images/gtvglogo.png"  th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />  --一次设置多个

循环输出的语法

<tr th:each="prod : ${prods}">
 <td th:text="${prod.name}">Onions</td>
 <td th:text="${prod.price}">2.41</td>
 <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>

自定义配置 mvc

If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.

如果想进一步配置MVC的话,继承 WebMvcConfigurer并且加上@Configuration,但是别加@EnableWebMvc.

@Configuration
public class MVCConfig implements WebMvcConfigurer {
    ...
}

可以去重写里面的某些方法,改变配置

如果加了@EnableWebMvc,原来的自动配置不会生效