Spring Mvc:java template engine Thymeleaf (ii)

Source: Internet
Author: User

This article originally planned to introduce Thymeleaf's view parsing directly, but considering the convenience of learning, we decided to build a SPRING-MVC first.

All of the following procedures are sufficient for just one notepad and jdk.

The first step is to build a web App using Maven.

<span style= "FONT-SIZE:18PX;" >MVN archetype:generate-dgroupid=org.nwpu.chen-dartifactid=spring-mvc-darchetypeartifactid= Maven-archetype-webapp-dinteractivemode=false</span>

It doesn't matter if you've used Maven before, and it's easy to use and configure environment variables after downloading. Here respectively with the parameters given GroupID (organization name), Artifactid (project name), the key is Archetypeartifactid, pointed out that the project type is Maven-archetype-webapp, Finally, it is indicated that interactive mode is not enabled (batch mode is enabled).

When finished, the directory structure is automatically generated.

<span style= "FONT-SIZE:18PX;" >└──spring-mvc   └──src       └──main            └──resouces            └──webapp    pom.xml</span>

WebApp below is part of our web application.


Step two, modify the Pom.xml

With the subsequent changes to the project, the Pom is still to be modified, here first add the compiled plugin, and the Tomcat plugin (meaning you do not need to install Tomcat)

<span style= "FONT-SIZE:18PX;" ><build>    <finalName>spring-mvc</finalName>    <plugins>           <plugin>        <artifactId>maven-compiler-plugin</artifactId>        <configuration>          <source> 1.7</source>          <target>1.7</target>        </configuration>      </plugin>            <plugin>          <groupId>org.apache.tomcat.maven</groupId>          <artifactId> tomcat7-maven-plugin</artifactid>          <version>2.2</version>      </plugin>    < /plugins>  </build></span>

It's as simple as Notepad to build the good one web app, without the use of the IDE (and not even Tomcat installed beforehand).

Run MVN clean tomcat7:run to open the browser again http://localhost:8080/spring-mvc/


The third step is to add SPRING-MVC dependencies

Start using MAVEN to start spring's friends, maybe to add Spring-context, Spring-core, Spring-web, Spring-webmvc ... Confusing, in fact, it is very simple, we can look at similar http://mvnrepository.com/on the site of our added dependency of the direct dependency, of course, you can also use maven inside the command to view.

Take SPRING-WEBMVC, for example, has the following dependencies (of course, dependency has its scope, not discussed here)


Or, run MVN dependency:list,



Note that at this point you are only relying on SRPING-WEBMVC to be sufficient. So, in Pom.xml add,

<span style= "FONT-SIZE:18PX;" >      <DEPENDENCY><GROUPID>ORG.SPRINGFRAMEWORK</GROUPID><ARTIFACTID>SPRING-WEBMVC </artifactId><version>4.0.6.RELEASE</version></dependency></span>


Fourth step, SPRING-MVC configuration

The best tutorial in this area should be http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html.

The process of MVC is actually a process of requesting flow. In spring, the beginning of accepting requests is dispatcherservlet, which can be seen as a front-end controller. Look at the name, it is the role of the allocation, that is, the request to the appropriate controller. The next step is to process the request and return to the view.

So, configuring Dispatcherservlet in Web. XML,


<span style= "FONT-SIZE:18PX;" >  <servlet>    <servlet-name>webmvc</servlet-name>      <servlet-class>        Org.springframework.web.servlet.DispatcherServlet      </servlet-class>      <load-on-startup>1</ Load-on-startup>  </servlet></span>
The servlet-name here is important because, by default, spring will let dispatcherservlet load the context from an XML file of the base name at load time. In this case, we're going to load webmvc-servlet.xml. (since there is a default, you can definitely customize, later articles will be introduced to)

Below we match the URL that the servlet handles, it is generally recommended to use/to match directly,

<span style= "FONT-SIZE:18PX;" >  <servlet-mapping>        <servlet-name>webmvc</servlet-name>        <url-pattern>/ </url-pattern>  </servlet-mapping></span>

At this point, you have to consider a problem, you can't make dispatcherservlet handle static resources (CSS,JS, etc.), Spring 3.0.4, you can use <mvc:resources/> to solve this trouble. Although our current Web project has no resources, be prepared to create a new resource folder in a directory parallel to Web-inf.

Then edit the Webmvc-servlet.xml under Webapp/web-inf,

<span style= "FONT-SIZE:18PX;" ><?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"                    xmlns:mvc= "Http://www.springframework.org/schema/mvc "Xsi:schemalocation="        Http://www.springframework.org/schema/beans         http://www.springframework.org/ Schema/beans/spring-beans.xsd        Http://www.springframework.org/schema/mvc        http://www.springframework.org /schema/mvc/spring-mvc.xsd ">        <mvc:resources mapping="/resources/** "location="/resources/"                  /> </beans></span>


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


As mentioned above, Dispatcherservlet will choose the appropriate controller to dispatch the request, this process is the controller mapping to complete (the details can go to http://docs.spring.io/spring/docs/current/ Spring-framework-reference/html/mvc.html understand). This only uses the Spring MVC annotation feature,

<span style= "FONT-SIZE:18PX;" ><mvc:annotation-driven/></span>

A word is enough.


Fourth step, write the controller

In a directory parallel to WebApp, create a new Java directory,

└──SRC    └──main        └──java        └──webapp
Package name Packages Org.webmvc.controller;
@Controllerpublic class homecontroller{     @RequestMapping ("Home") public     String Showhomepage (model model) {        Model.addattribute ("name", "Spring-mvc");        Return "Home";     }}

In order to realize automatic detection and assembly, we add the following in the configuration file:

<context:component-scan base-package= "Org.webmvc.controller"/>

The following focus is on how logical views are mapped to physical views. In this example, how does the string of home relate to a physical file?


The fifth step, according to the graphic analysis

Since this is about the integration of Thymeleaf and spring, put Thymeleaf-spring4-{version}.jar under Build path, or add the following dependencies:

(Spring4 indicates integration with spring4.0+, also spring3).


<dependency><groupid>org.thymeleaf</groupid><artifactid>thymeleaf-spring4</ Artifactid><version>2.1.2.release</version></dependency>

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

<bean id= "Templateresolver"       class= "Org.thymeleaf.templateresolver.ServletContextTemplateResolver" >  <property name= "prefix" value= "/web-inf/templates/"/>  <property name= "suffix" value= ". html"/>  <property name= "Templatemode" value= "HTML5"/></bean>    <bean id= "Templateengine"      class= "Org.thymeleaf.spring4.SpringTemplateEngine" >  <property name= "Templateresolver" ref= "Templateresolver" /></bean>

While the typical JSP + Jstl view, a typical configuration is:

<bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" >  <property name= " Viewclass "value=" Org.springframework.web.servlet.view.JstlView "/>  <property name=" prefix "value="/ web-inf/jsps/"/>  <property name=" suffix "value=". jsp "/>  <property name=" Order "value=" 2 "/>  <property name= "Viewnames" value= "*jsp"/></bean>

Where Internalresourceviewresolver is an implementation of org.springframework.web.servlet.ViewResolver, while in thymeleaf this work is made by ORG.THYMELEAF.SPRING4.V Iew. Thymeleafviewresolver completed,

<bean class= "Org.thymeleaf.spring4.view.ThymeleafViewResolver" >  <property name= "Templateengine" ref= "Templateengine"/>  <property name= "Order" value= "1"/>  <property name= "Viewnames" value= "*.html , *.xhtml "/></bean>

A complete configuration is as follows,

<!--****************************************************************--<!--thymeleaf-specific              Artifacts-<!--templateresolver <-templateengine <-viewresolver -<!--****************************************************************---<bean id= "templateRe Solver "class=" Org.thymeleaf.templateresolver.ServletContextTemplateResolver "> <property name=" prefix "val Ue= "/web-inf/views/"/> <property name= "suffix" value= ". html"/> <property name= "Templatemode" value= "HT    ML5 "/> </bean> <bean id=" Templateengine "class=" Org.thymeleaf.spring4.SpringTemplateEngine "> <property name= "Templateresolver" ref= "Templateresolver"/> </bean> <bean class= "Org.thymeleaf.spri Ng4.view.ThymeleafViewResolver "> <property name=" templateengine "ref=" Templateengine "/> </bean>

Create a new views directory under Web-inf and create a new home.html with simple content:

<! DOCTYPE html>

Among them, xmlns:th= "http://www.thymeleaf.org" is the introduction of namespaces, also on the use of th tag.


To this, a complete MVC app was created successfully.

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



Spring Mvc:java template engine Thymeleaf (ii)

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.