SpringMVC integrates velocity and introduces the basic syntax of velocity

Introduction to Velocity Template (VM) Language and Integration with MVC

Velocity is a java-based template engine (template engine). It allows anyone to simply use a template language to refer to objects defined by java code.
When Velocity is applied to web development, interface designers and java program developers can simultaneously develop a web site that follows the MVC architecture, that is, page designers can only focus on the display effect of the page, while java program developers focus on business logical coding. Velocity separates the java code from the web page, which facilitates the long-term maintenance of the web site, and also provides us with an optional solution besides JSP and PHP.

Velocity is now very widely used, and now try to integrate the SpringMVC project with Velocity.

1. Integration process

Using the previously integrated [SpringMVC project].
Mainly involved in the changed files:
pom.xml (introducing the velocity jar package)
spring-mvc.xml (view configuration, configure velocity)

velocity.properties (velocity configuration file)

The following is a brief description of the steps to configure velocity in spring mvc: 

1. Introduce the packages required for velocity (additions based on mvc will omit the jar imported by mvc)

<!-- Velocity Template-->  
  <dependency>  
            <groupId>org.apache.velocity</groupId>  
            <artifactId>velocity</artifactId>  
            <version>1.5</version>  
        </dependency>  
        <dependency>  
            <groupId>org.apache.velocity</groupId>  
            <artifactId>velocity-tools</artifactId>  
            <version>2.0</version>  
        </dependency> 
2. Add configuration information (spring-mvc.xml)

<?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:context="http://www.springframework.org/schema/context"
       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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">




    <!--Package scan-->
    <context:component-scan base-package="controller"/>
       


    <!-- new namespace mvc
        Automatically register handler adapters and handler mappers to handle some response-related operations
        Replaces not only the processor mapper but also the processor adapter, but also handles response related operations
        @ResponseBody is to be configured in this namespace when responding to the foreground
    -->
    <mvc:annotation-driven/>
           
    <!--Create handler mapper
    <bean  class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
    Create a processor adapter
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
      -->


  <!-- view resolver
        The result of parsing according to the return value of the controller method is prefix + return return value + suffix
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
 -->
<!-- View mode configuration, velocity configuration file -->
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">  
    <property name="resourceLoaderPath" value="/WEB-INF/views" />  
    <property name="configLocation" value="classpath:velocity.properties" />  
</bean>  


<!-- configuration suffix -->
<bean id="velocityViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">  
    <property name="suffix" value=".vm" />  
    <property name="contentType"><value>text/html;charset=UTF-8</value></property>
</bean>
 


</beans>
3. velocity.properties configuration file
#encoding Setting the encoding format
input.encoding=UTF-8
output.encoding=UTF-8
  
#autoreload when vm changed  
file.resource.loader.cache=false
file.resource.loader.modificationCheckInterval=2
velocimacro.library.autoreload=false  

4. Write TestController after configuration

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/hello")
public class HelloController {
	private static Logger logger = Logger.getLogger(HelloController.class);
	@RequestMapping("/showAllUser")
	public String showAllUser(HttpServletRequest request,Model model){
		//volicaty放入集合
		List<User> list = new ArrayList<User>();
		User user = new User();
		user.setAge(1);
		user.setDate(new Date());
		user.setId("1");
		user.setName("张三");
		User user2 = new User();
		user2.setAge(1);
		user2.setDate(new Date());
		user2.setId("s");
		user2.setName("李四");
		list.add(user);
		list.add(user2);
		logger.info("userList's size==============" +list.size());
		model.addAttribute("userList",list);
		//放入单个数据
		model.addAttribute("user","测试数据");
		return "showAllUser";
	}
}
5.showAllUser.vm模板(放置在WEB-INFO下面添加views文件夹)

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>show all users</title>
</head>
<body>
	<h2>单个名字:$user</h2>
	<hr/>
    <table >遍历集合所得到的数据
        #foreach($user in $userList)
            <tr >
                <td >$user.name</td>
                <td >$user.age</td>
            </tr>
        #end
    </table>
    <hr/>
#set($directoryRoot = "www" )
#set($templateName = "index.vm" )
#set($template = "$directoryRoot/$templateName" )
最终结果:$template
</body>
</html>  
6.访问结果展示:
2. Velocity基本使用语法

1.展示单条数据
	<!--展示单条数据这两种方式都可以推荐第一种-->
		<h2>1.单个名字:$user</h2>
		<hr/>
		<h2>2.单个名字:${user}</h2>
	<hr/>
   2.展示集合数据
		<!--展示集合数据-->
    <table >
        #foreach($user in $userList)
            <tr >
                <td >$user.name</td>
                <td >$user.age</td>
            </tr>
        #end
    </table>
3.在模版中给变量赋值
      <!--前面两个都是给变量赋值,展示的结果为:www/index.vm-->
		#set($directoryRoot = "www" )
		#set($templateName = "index.vm" )
		#set($template = "$directoryRoot/$templateName" )
		结果:$template
4.条件语句使用语法
<!-- 条件语句使用语法-->
		#if (${a}>18) 小学
		#elseif (${a}<15)中学
		#else大学
		#end
5.单行以及多行注释

	<!-- 单行注释-->	
	 	 ## This is a single line comment.
	 	 
	 	 
	<!-- 多行注释-->	
		 #*
		   Thus begins a multi-line comment. Online visitors won’t
		   see this text because the Velocity Templating Engine will
		   ignore it.
	  	*#

6.set语法

#set可以创建一个Velocity的变量,一般用于向一个变量或属性赋值,下面的第一个例子,大概和java中的String name=user.getName();是一个意思.
在Velocity语法树中,#set表达式对应的是一个ASTSetDirective类,"="两边的表达式值,分别对应该类的两个子节点,LHS和RHS.
#set($user.name="zhangsan")   可以理解为     user.setName("zhangsan")
#set(name=user.name)         可以理解为     user.getName();
像上述例子中的第一个:不仅可以表示 user.setName("zhangsan"),还可以表示user.setname("zhangsan"),或者user.put("name","zhangsan"),
这是动态语言的特点,不想java语法那样严格的定义.
注意:#set表达式,结尾不需要#end跟随,其他表达式基本都需要加#end.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324378347&siteId=291194637