Spring MVC: Java template engine Thymeleaf (2)

Source: Internet
Author: User

Spring MVC: Java template engine Thymeleaf (2)

This article was originally designed to directly introduce Thymeleaf's view parsing, but considering the convenience of learning, we decided to build a spring-mvc first.

All the following processes require only one notepad and JDK.

Step 1: Use maven to build a web app.

mvn archetype:generate -DgroupId=org.nwpu.chen -DartifactId=spring-mvc -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

It doesn't matter if you haven't used Maven before. After downloading it, you can configure the environment variables, which is easy to use. The groupId (organization name) and artifactID (project name) are given respectively. The key is archetypeArtifactId. It is pointed out that the project type is maven-archetype-webapp, finally, it indicates that interactive mode is not enabled (batch mode is enabled ).

The directory structure is automatically generated.

└──spring-mvc   └── src       └── main            └── resouces            └── webapp    pom.xml

Below is the part of our web application.


Step 2: Modify pom. xml

As the project changes, the pom still needs to be modified. Add the compiled plug-ins and tomcat plug-ins here (meaning you do not need to install tomcat)

     
  
   spring-mvc
      
             
   
            maven-compiler-plugin        
              
     1.7          
     
      1.7
             
          
               
             
    
     org.apache.tomcat.maven
              tomcat7-maven-plugin          
    
     2.2
          
       
    
 

This is simple. Without IDE (or even without installing tomcat in advance), you can build a web app in notepad.

Run mvn clean tomcat7: run, and then open http: // localhost: 8080/spring-mvc/in the browser/


Step 3: Add spring-mvc Dependencies

A friend who starts to use maven to start spring may add spring-context, spring-core, spring-web, spring-webmvc to the end... it's actually very simple.

Taking spring-webmvc as an example, there are the following dependencies (of course, dependencies have their scope, which will not be discussed here)


Alternatively, run mvn dependency: list,



Note: It is sufficient to rely only on srping-webmvc. Therefore, add in pom. xml,

      
 
  
   org.springframework
  spring-webmvc
  
   4.0.6.RELEASE
  
 


Step 4: Configure spring-mvc

The best tutorial is http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html.

The MVC process is actually a process of request flow. In Spring, the start of request acceptance is DispatcherServlet, which can be viewed as a front-end controller. Let's look at the name. It is the function of dispatching, that is, assigning requests to appropriate controllers. The next step is to process the request and return to the view.

Therefore, configure DispatcherServlet in web. xml,


  
     
  
   webmvc
        
  
           org.springframework.web.servlet.DispatcherServlet      
        
  
   1
    
 
The servlet-name here is very important, because by default, Spring will let DispatcherServlet load the context from an xml file with the base name when loading. In this example, load the webmvc-servlet.xml. (Since there is a default value, it can be customized, and will be introduced in later articles)

Below we match the URL processed by the servlet. We generally recommend that you use/to match the URL,

  
         
  
   webmvc
          
  
   /
    
 

At this time, you have to consider a problem that DispatcherServlet cannot be used to process static resources (css, js, etc.). After Spring 3.0.4, you can use Solve this problem. Although our current Web project has no resources yet, it is ready to use to create a new resources folder in a directory parallel to the WEB-INF.

Then edit the WEB-INF under webapp/webmvc-servlet.xml,

 
         
  
 


The mapping value/resources/** indicates that any sub-path starting with/resouces is matched, and the location indicates the actual directory of the resource.


As mentioned above, DispatcherServlet will select an appropriate controller to dispatch requests. This process is completed by Controller ing (for details, go to http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html ). Here, only the annotation function of Spring MVC is used,

 

One sentence is enough.


Step 4: Write the Controller

In a directory parallel to webapp, create a java directory,

└── src    └── main        └── java        └── webapp
Package org. webmvc. controller;
@Controllerpublic class HomeController{     @RequestMapping("/home")     public String showHomePage(Model model){        model.addAttribute("name","spring-mvc");        return "home";     }}

To achieve automatic detection and assembly, we add the following in the configuration file:

 

The following focuses on how the logical view maps to the physical view. In this example, how is the home string associated with a physical file?


Step 5: View Analysis

Because Thymeleaf and Spring are integrated hereThymeleaf-spring4-{version}. jar is placed under Build Path or the following dependency is added:

(Spring4 indicates integration with spring4.0 + and spring3 ).


 
  
   org.thymeleaf
  thymeleaf-spring4
  
   2.1.2.RELEASE
  
 

First, you need to instantiate a template engine of org. thymeleaf. spring4.SpringTemplateEngine,

   
    
    
  
     
   
  
 

For a typical JSP + JSTL view, a typical configuration is:

   
    
    
    
    
  
 

InternalResourceViewResolver is an implementation of org. springframework. web. servlet. ViewResolver, and Thymeleaf is implemented by org. thymeleaf. spring4.view. ThymeleafViewResolver,

   
    
    
  
 

The complete configuration is as follows,

   
   
   
   
     
      
      
    
       
     
    
      
     
    
     

Create a new viewsdirectory and create home.html under web-inf. the content is simple:

    Spring MVC with thymeleaf    
     


run ok....

Among them, xmlns: th = "http://www.thymeleaf.org" is to introduce the namespace, that is, the use of th labels.


By now, a complete MVC app has been created successfully.

Run mvn tomcat7: run and enter http: // localhost: 8080/spring-mvc/home in the browser,



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.