SpringBoot (static resource)

SpringBoot's mapping rules for static resources
If we need to add css/js/html files to the web project, we will find that there is no webapp directory at this time.
Insert picture description here

Since springboot packs the program in a jar package, there is no webapp directory.
So where should our css/js/html files be stored? ? ?
We need to understand a Java class "WebMvcAuotConfiguration", because the automatic configuration related to web development is done by this class.

spring-boot-autoconfigure-2.4.0.jar---》META-INF--》spring.factories
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
@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();
   if (!registry.hasMappingForPattern("/webjars/**")) {
    
    
      customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/")
            .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)
            .setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
   }
   String staticPathPattern = this.mvcProperties.getStaticPathPattern();
   if (!registry.hasMappingForPattern(staticPathPattern)) {
    
    
      customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
            .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
            .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)
            .setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
   }
}

WebProperties.java

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = 
{
    
     "classpath:/META-INF/resources/",
 "classpath:/resources/", 
"classpath:/static/",
 "classpath:/public/" };

1. The storage location of static resources All “/webjars/**”
webjars: mark the static resources that need to be used into jar packages, and if we need to import the entire jar into this project, it can be used.
Static resources are marked as jar packages to view the location:
https://www.webjars.org/
Insert picture description here

Take JQuery as an example to use the webjars method
1. Import the JQuery jar dependency in the pom.xml file

<!--导入jquery的jar包-->
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.5.1</version>
</dependency>

The result of guiding people
Insert picture description here

2. Test access to the jquery file we imported.
Start the service, and directly access the jquery file in the address bar of the browser
http://localhost:8080/webjars/jquery/3.5.1/jquery.js
Insert picture description here

2. The location of the default static resource file
WebProperties.java

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = 
{
    
     "classpath:/META-INF/resources/",
 "classpath:/resources/", 
"classpath:/static/",
 "classpath:/public/" };

1. "classpath:/META-INF/resources/",
[src/main/resources/META-INF/resources/]-need to be packaged before running
Insert picture description here

2.“classpath:/resources/”=== [src/main/resources/resources]
Insert picture description here

3.”classpath:/static/”==== [src/main/resources/static]
Insert picture description here

4.“classpath:/public/”== [src/main/resources/public]
Insert picture description here

3) Welcome page; all index.html pages under the static resource folder;
Insert picture description here

4) Page icon; all favicon.ico icons under the static resource folder;
Insert picture description here

You can configure and modify the static resource folder path in application.properties.

@ConfigurationProperties(prefix = "spring.web.resources", ignoreUnknownFields = false) 
public class ResourceProperties implements ResourceLoaderAware {
    
     
//可以设置和静态资源有关的参数,缓存时间等
application.properties
spring.web.resources.static-locations=classpath:/test/,classpath:/hello/

Insert picture description here

http://localhost:8080/test.html

Template engine
Because springboot packages programs in jar packages, not web projects, and in springboot we use embedded tomcat server, so springboot projects do not support the operation of dynamic pages, so if we all If the page is processed as a static page, then when the data is loaded, a lot of js will be required to request data from the background to fill in the static page, which will be more troublesome. The springboot used provides us with a template engine.
Common template engines are JSP, Velocity, Freemarker, Thymeleaf
Insert picture description here

SpringBoot recommends Thymeleaf template engine for us; because of its simpler syntax and more powerful functions.
The use of Thymeleaf template engine:
1. Introduce the dependency package of Thymeleaf template engine [Starter]

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

2. Use Thymeleaf
to look at the automatic configuration first

public class ThymeleafProperties {
    
    
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/"; //模板的位置
    private String suffix = ".html"; //静态页面的类型
    private String mode = "HTML";

As long as we put the HTML page in classpath:/templates/, thymeleaf can render automatically;
3. Create a controller

@Controller
public class HelloController {
    
    
    @RequestMapping(value = "/testHello1")
    public  String  testHello1(Map<String,Object> map){
    
    
        map.put("id",1001);
        map.put("name","张三");
        map.put("age",23);
        map.put("address","西安");
        return "test1";
    }

Insert picture description here

@RequestMapping(value = "/testHello2")
    public  String  testHello2(Model model){
    
    
        model.addAttribute("id",1001);
        model.addAttribute("name","张三");
        model.addAttribute("age",23);
        model.addAttribute("address","西安");
        return "test1";
    }

Note: The data value passed to the page is set by the parameters in the
request processing method, the type of the parameters in the request processing method:
1.Map<String,Object> map
2.Model model 4.Create
a template page, the template page defaults Is ".html"

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <ul>
        <li><h1 th:text="${id}"></h1></li>
        <li><h1 th:text="${name}"></h1></li>
        <li><h1 th:text="${age}"></h1></li>
        <li><h1 th:text="${address}"></h1></li>
    </ul>
</body>
</html>

xmlns:th="http://www.thymeleaf.org" – Introduce the thymeleaf namespace to the html page, and we can use the thymeleaf syntax in the html page to display dynamic data.
thymeleaf syntax
Insert picture description here

th: any html attribute; to replace the value of the original html attribute

<span id="span1"></span>
<span th:id="${id}"></span>
例如:
<h1 th:text="${address}"></h1>

th:text—Controls the text attribute value of the h1 element, the text attribute value is the text content of the html element
thymeleaf expression
#{…}: Internationalized message
...: variable value* …: current object/variable value @… :url Expression...: Fragment reference judgment/traversal: th: if − − − th: if = ”{…}: Variable value *{…}: Current object/variable value @{…}: URL expression~{… }: Fragment reference judgment/traversal: th:if ---th:if=”... : variable amount takes a value... : When the front of object / variable amount takes values @ ... : U R & lt L Table of formula ... : plate segment primers with determination OFF / times calendar : T H :ifth:if={id}==1001”
th:unless
th:each --th:each=”user: u s e r s ” − − − t h : t e x t = ” {users}” --- th:text=” usersth:text={user}”
th:switch、th:case
测试th:if / th:each

@RequestMapping(value = "/testHello3")
public  String  testHello3(Model model){
    
    
    List<UserBean> userBeanList=new ArrayList<UserBean>();
    for(int i=1;i<=10;i++){
    
    
        UserBean  userBean=new UserBean();
        userBean.setUserid(1000+i);
        userBean.setUsername("zhangsan_"+i);
        userBean.setUserage(20+i);
        userBean.setUseraddress("address_"+i);
        userBeanList.add(userBean);
    }
    model.addAttribute("userlist",userBeanList);
    return "test2";
}
<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
   <table border="1px">
       <tr align="center">
           <td colspan="4"><h1>用户信息表</h1></td>
       </tr>
       <tr th:if="${userlist.size()} != 0" th:each="user:${userlist}">
           <td th:text="${user.userid}"></td>
           <td th:text="${user.username}"></td>
           <td th:text="${user.userage}"></td>
           <td th:text="${user.useraddress}"></td>
       </tr>
       <tr th:if="${userlist.size()} == 0">
           <td colspan="4">没有用户记录!!!</td>
       </tr>
   </table>
</body>
</html>

Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/guoguo0717/article/details/110948234