编程知识 cdmana.com

Springboot Episode 9: integrating JSP and template engine FreeMarker / thymeleaf

SpringBoot Episode 9 : Integrate JSP And template engine (2020 Up to date and easy to understand )

   When a customer submits a request through the front page , How we used to do it ? The back end receives the request data , Processing requests , Pass the response results to the template engine JSP, Finally, the rendered JSP To HTML, The response is displayed to the client .JSP The advantage of this is that when we find out that some data is forwarded to JSP After the page , We can use JSP Easy to achieve data display , And interaction .JSP Support very powerful features , Including being able to write Java Code .

   But what? , The situation we are in now is , First of all :SpringBoot This project starts with jar The way , No war. second : We still use embedded Tomcat( A simplified version of , That is not supported JSP), So ,SpringBoot Not supported by default JSP Of . If we use the pure static page directly , That will bring us a lot of trouble in development , So we have to choose , except JSP Other template engines .

   The role of template engine is , Let's write a page template , For example, some values , Is dynamic , We're writing some expressions , To dynamically display these values , As we used to do earlier JSP. The role of template engines is actually the same , It's just , Between different template engines , They may have different grammar .Spring Boot Support FreeMarker、Groovy、Thymeleaf and Mustache Four template parsing engines , Official recommendation Thymeleaf.

   For a template engine ,SpringBoot The default path for storing template files is src/main/resources/templates, Of course, you can also modify it through the configuration file .

   Yes, of course , Use JSP It's OK, too , But the official has not recommended the use of JSP, This article will also explain SpringBoot Next JSP Supported by , Because a lot of old projects still use JSP Template Mostly .( It is not recommended to use JSP It is also because JSP Need to compile and transform , Other template engines do not need to compile and transform )

1.SpringBoot Integrate Java Server Page

  JSP( Full name Java Server Page), yes web Develop the earliest template engine products , With the renewal of the times , It's getting old , Of course, it has not yet completely withdrawn from the market .SpringBoot Microservice architecture , All projects are based on jar File mode package deployment , Embedded Tomcat( Simplified edition , I won't support it JSP), therefore SpringBoot Not supported by default JSP Of , So if you want to integrate JSP, We need to introduce integration dependency independently , And basic configuration .

   SpringBoot The default path for storing template files is src/main/resources/templates, But because of SpringBoot Not supported by default JSP Of , So we can't JSP Files in templates Under the table of contents .

  1. introduce JSP The core engine
     1 <!-- SpringBoot Integrate JSP:SpringBoot Default Integration Tomcat, So there's no need to specify JSP edition  -->
     2 <dependency>
     3     <groupId>org.apache.tomcat.embed</groupId>
     4     <artifactId>tomcat-embed-jasper</artifactId>
     5 </dependency>
     6 <!-- JSP rely on JSTL -->
     7 <dependency>
     8     <groupId>javax.servlet</groupId>
     9     <artifactId>jstl</artifactId>
    10 </dependency>
  2. establish JSP Integrate catalog webapp as well as WEB-INF
    stay Java,resources New in the same directory webapp Directory and subdirectories WEB-INF

     

      as for web.xml The configuration file , Yes, but not anymore .

  3. modify yml file , To configure MVC Trying to parse
    1 spring:
    2   #  Configuration integration JSP
    3   mvc:
    4     view:
    5       #  Configure view parser prefix 
    6       prefix: /WEB-INF/
    7       #  Configure view parser suffix 
    8       suffix: .jsp
  4. establish Controller Visit JSP
     Because it's back to the page   So it can't be @RestController
    // @RestController   The annotation takes any return value as JSON expose , Without the view parser   
    @Controller    // SpringBoot Integrate JSP, Out of commission @RestController
    public class PersonController {
        
        @RequestMapping({"/indexJSP","/listJSP"})
        public String getIndexJSP() {
            System.out.println("JSP Access test .....");
            return "index";
        }
    }
  5. start-up SpringBoot The main program , Access test
    http://localhost:8080/indexJSP

1. explain : After completing the above steps , Run the project and you can access jsp Interface , But don't be happy too early , When you hit a jar When the package , You'll find that you can't access jsp 了 , as a result of SpringBoot When the packaging , Will not take the initiative to pack webapp The directory , You need to be in yours pom File manual configuration handle webapp We'll pack it in . Please refer to the appendix for details .
2. Common mistakes : No manual server restart ! Cause unable to parse , Error code 500, display information :template might not exist or might not be accessible by any of the configured Template Resolvers( The template may not exist , Or any configured template resolver cannot access )
3. If it's just Integration JSP, The use of other templates is not integrated , Then don't introduce other template dependencies , There is no need to configure other template information , Otherwise it will be wrong !!!(SpringBoot Template engine supported by default , Naturally, there is a default configuration , Once you add the corresponding dependency ,SpringBoot Will follow conventions greater than configuration , Automatic injection , What about your JSP You can't access ).

2.SpringBoot Integrate Freemarker

  FreeMarker Is a template engine : It's based on the template and the data to be changed , And used to generate output text (HTML Webpage , E-mail , The configuration file , Source code, etc ) General tools for . It's not for end users , It is a Java Class library , It's a component that programmers can embed in their products . Official website reference

    stay Spring Boot Use in FreeMarker  Just in pom Add FreeMarker  Of starter that will do .

  1. modify pom The file import FreeMarker  Of starter
    1 <!-- SpringBoot Integrate Freemarker -->
    2 <dependency>
    3     <groupId>org.springframework.boot</groupId>
    4     <artifactId>spring-boot-starter-freemarker</artifactId>
    5 </dependency>
  2. modify yml File configuration FreeMarker
    ( Can not worthy ,SpringBoot This template is supported by default )
     1 spring:  
     2   # Freemarker Configuration details ( Both have default configurations )
     3   freemarker:
     4     #  Template loading path ( The default configuration is templates Next , You can configure it manually , Multi value use “,” Division )
     5     template-loader-path:
     6     - classpath:/templates/
     7     #  Configure the cache , The development phase should be configured as false  Because it often changes , After deployment, it is recommended to open 
     8     cache: false
     9     #  Configure encoding settings 
    10     charset: UTF-8
    11     #  Whether the suggested template exists 
    12     check-template-location: true
    13     # Content-Type  value 
    14     content-type: text/html
    15     #  Template suffix : The default is ftlh( Here the test changes to html), If you set the template suffix , Then the new template file must be the specified suffix 
    16     # suffix: .html
    17     #  Is it enabled? Freemarker
    18     enabled: true 
    19     #  You can view the configuration in detail FreeMarkerProperties class 

    Configuration instructions : Here is an overview of / For example, common configurations , Not all of them need ,SpringBoot With default configuration , Details refer to org.springframework.boot.autoconfigure.freemarker.FreeMarkerProperties class , In the above configuration , Actually, you can only configure to turn off the cache .

  3. newly build FreeMarker Templates
       stay src/main/resources/templates/ Next, create a new template engine .

      FreeMarker The default suffix of the template is ftlh, If there is no custom configuration , Follow the original intention of convention greater than configuration , Create a new template with the suffix set to .ftlh. If there is a custom configuration , Then the new template suffix is user-defined . for example : The suffix specified in the current case configuration is .html, Then the new template suffix is .html, Don't worry about , Will you not support FreeeMarker The problem of grammar .( The template engine will eventually convert to HTML Of )
    Feemarker grammar : Refer to the official website , Refer to the Chinese website
     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4 <meta charset="UTF-8">
     5 <title>Insert title here</title>
     6 </head>
     7 <body>
     8     Hello Freemarker!!!
     9     <#-- FreeMarker notes : Get the value ( Be careful : there ${} yes FreeMarker grammar , Be similar to EL, Make sure it's not EL expression , And the value here is not null, Otherwise, an error will be reported ) -->
    10     ${name }
    11 </body>
    12 </html>
  4. To write Controller controller , Realize jump access
     1 @Controller //  Because it's back to the page   So it can't be @RestController
     2 public class FreemarkerController {
     3     
     4     @RequestMapping("/indexFtlh")
     5     private String freemarkerShowIndex(String name, Model model) {
     6         //  Pass the accepted parameters through model share ( Actually saved in request in )
     7         model.addAttribute("name", name);
     8         return "indexFtlh";
     9     }
    10 }
  5. Start the main program test
    visit :http://localhost:8080/indexFtlh?name=xsge
    Common mistakes : No, Manually restart the server ! Cause unable to parse , Error code 500, display information :template might not exist or might not be accessible by any of the configured Template Resolvers( The template may not exist , Or any configured template resolver cannot access )

3.SpringBoot Integrate Thymeleaf

  Thymeleaf It's a XML/XHTML/HTML5 template engine , Can be used for Web And non Web Application development in the environment .Thymeleaf The main goal is to provide a browser can be correctly displayed 、 Well formed template creation , So it can also be used as static modeling . stay Spring Boot Use in Thymeleaf Just in pom Add Thymeleaf Of starter that will do .
  Thymeleaf Official website ,GitHup(Thymeleaf)

  1. modify pom, introduce Thymeleaf Of starter rely on
    1 <!-- SpringBoot Integrate Thymeleaf -->
    2 <dependency>
    3     <groupId>org.springframework.boot</groupId>
    4     <artifactId>spring-boot-starter-thymeleaf</artifactId>
    5 </dependency>
    default Thymeleaf Version is 2.x.x.RELEASE edition , It is recommended to use 3.0 Above version . It is suggested that pom Lieutenant general Thymeleaf The version of is modified to 3.0.x.RELEASE above .( Many people on the Internet say it needs to be changed , Of course, I haven't changed , If you want to change the higher version , You can refer to —— I really don't think it's necessary to change , It should follow your project situation , Is it possible to develop SpringBoot Are you stupid ?)
    1 <properties>  
    2   <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>  
    3   <thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>  
    4 </properties>  
  2. modify yml File configuration basic information
    ( Can not worthy ,SpringBoot This template is recommended by default )
     1 Spring:
     2   # Enable template cache ( The default value is :true 3   thymeleaf:
     4     cache: false 
     5     #  Check if the template exists before rendering the effect .
     6     check-template: true 
     7     #  Check whether the formwork position is correct ( The default value is :true 8     check-template-location: true
     9     # Content-Type Value ( The default value is :text/html)
    10     servlet:
    11       content-type: text/html
    12     #  Turn on MVC Thymeleaf View resolution ( The default value is :true13     enabled: true
    14     #  Template encoding 
    15     encoding: UTF-8
    16     #  List of view names to be excluded from resolution 
    17     # excluded-view-names: 
    18     #  The template pattern to apply to the template . See also StandardTemplate-ModeHandlers( The default value is :HTML5)
    19     mode: HTML5
    20     #  In the build URL Prefix before view name ( Template loading path : The default value is :classpath:/templates/21     prefix: classpath:/templates/
    22     #  In the build URL The suffix after the view name ( The default value is :.html)
    23     suffix: .html
    24     # Thymeleaf The order of the template parsers in the parser chain . By default , It comes first . Order from 1 Start , Only when the definition of extra TemplateResolver Bean You need to set this property .
    25     # template-resolver-order: 
    26     #  List of resolvable view names 
    27     # view-names:
    28     # - 
  3. New template
     1 <!DOCTYPE html>
     2 <html xmlns:th="http://www.thymeleaf.org">
     3 <head>
     4 <meta charset="UTF-8">
     5 <title>Insert title here</title>
     6 </head>
     7 <body>
     8     <div th:text="${url}"></div>
     9 </body>
    10 </html>

    stay html Page in thymeleaf Namespace , namely , At this time in html Dynamic attributes in template files use th: Namespace modifiers .( avoid thymeleaf Grammatical errors , Label warning and other issues )
    Here's a simple idea : Please refer to blog template grammar notes for details .

    th attribute

    html Some properties ,Thymeleaf Have a basic , There are about seven or eight common attributes . among th The priority of property execution is from 1~8, The lower the number, the higher the priority .

    1. th:text : Set the text content of the current element , And the same thing th:utext, The difference between the two is that the former does not translate html label , The latter will . The priority is not high :order=7

    2. th:value: Set the... Of the current element value value , Similar to modifying the specified properties, there are th:src,th:href. The priority is not high :order=6

    3. th:each: Traversing loop elements , and th:text or th:value Use it together . Note the position of the tag , Look back in detail . High priority :order=2

    4. th:if: conditional , Similar to that th:unless,th:switch,th:case. High priority :order=3

    5. th:insert: Code blocks introduce , Similar to that th:replace,th:include, There is a big difference between them , Improper use will destroy html structure , Commonly used in common code block extraction scenarios . The highest priority :order=1

    6. th:fragment: Define code blocks , Convenient to be th:insert quote . The lowest priority :order=8

    7. th:object: Declare variables , In general, and *{} Used together , To achieve the effect of laziness . The priority is average :order=4

    8. th:attr: Modify any property , Less used in actual development , Because there are plenty of other th Attributes help , Similar to that th:attrappend,th:attrprepend. The priority is average :order=5

  4. Write controller
     1 @Controller
     2 public class HtmlController {
     3 
     4     @RequestMapping("/indexHtml")
     5     public String indexHtml(Model model) {
     6         model.addAttribute("url","XSGE Personal website :http://www.xsge123.com");
     7         System.out.println("ceshi");
     8         return "indexHtml";
     9     }
    10 }
  5. Test access
    start-up SpringBoot The main program , Single browser access :http://localhost:8080/indexHtml
    Common mistakes : No, Manually restart the service device ! Cause unable to parse , Error code 500, display information :template might not exist or might not be accessible by any of the configured Template Resolvers( The template may not exist , Or any configured template resolver cannot access )

appendix   

   SpingBoot Integrate JSP, Packing problem : Two conclusions

1. A lot of online saying is , stay pom.xml Configure the package address in ( This method works ) The implementation is as follows :

  A, modify pom file , Configure... In the plug-in JSP Resource path .

  B, modify SpringBoot Package plug-in version is (1.4.2.RELEASE)

  C, function Mavne Command packaging

 1 <!-- SpringBoot Packaging plug-in  -->
 2     <build>
 3         <plugins>
 4             <plugin>
 5                 <groupId>org.springframework.boot</groupId>
 6                 <artifactId>spring-boot-maven-plugin</artifactId>
 7                 <version>1.4.2.RELEASE</version>
 8                 <executions>
 9                         <execution>
10                             <goals>
11                                 <goal>repackage</goal>
12                             </goals>
13                         </execution>
14                 </executions>
15             </plugin>
16         </plugins>
17         
18         <resources>
19             <resource>
20                 <directory>src/main/java</directory>
21                 <includes>
22                     <include>**/**</include>
23                 </includes>
24             </resource>
25             <resource>
26                 <directory>src/main/resources</directory>
27                 <includes>
28                     <include>**/**</include>
29                 </includes>
30                 <filtering>false</filtering>
31             </resource>
32             <!--  When packing, you will jsp File copy to META-INF Under the table of contents -->
33             <resource>
34                 <!--  Appoint resources Which directory does the plug-in handle the resource files  -->
35                 <directory>src/main/webapp</directory>
36                 <includes>
37                     <include>**/**</include>
38                 </includes>
39                 <!-- Note that this must be placed in this directory to be accessed -->
40                 <targetPath>META-INF/resources</targetPath>
41                 <filtering>false</filtering>
42             </resource>
43         </resources>        
44     </build>

Many people may have seen similar configurations on the Internet , But there is almost no definitive version ! However , This configuration way in SpringBoot After version upgrade , The official said that it was not recommended to use , stay SpringBoot1.4.x After the version , Recommend Integration JSP When packed as war package ,SpringBoot Project integration built in Tomcat plug-in unit , So we packed it war file , No need to think about installing the server , Think of it as a jar Just run the file as well
Java   -jar    file name .jar/war

2. No need to pom Too many configurations in , Change the packing method to war that will do .

  A, Change the packing method to war

  B, function Maven Command packaging

  C, start-up jar Test access

<packaging>war</packaging>

 

版权声明
本文为[Net weight 21g]所创,转载请带上原文链接,感谢

Scroll to Top