在Spring MVC中使用Velocity – Part 1工程中配置velocity

目的

Spring MVC中结合velocity的配置和操作。

简介

我们要显示一个课程列表,需要如下的 Java model类,在 mvc model中分别建立:Course.java、Instructor.java。 在service下创建CourseService.java文件,在controller下建立CourseController.java。其中Course是课程表信息;Instructor是任课教师的信息;CourseService用来列出课程信息,兼有隐含DAO;ListCourse是实现了Controller的控制器,返回ModelAndView。下面分别列出代码:

Java Model

  1. Course.java
package com.simple.mvc;
import java.util.Date;public class Course {private String id;private String name;private Instructor instructor;private Date startDate;private Date endDate;// ... Getter/Setter
}
  1. Instructor.java
package com.simple.mvc;public class Instructor{private String firstName;private String lastName;// getter / setter
}

类 service

  1. CourseService.java
package com.simple.mvc;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class CourseService {public List<Course> getAllCourses(){List<Course> courseList = new ArrayList<Course>();Course course = null;Date date = null;for(int i = 0; i < 8; i++){course = new Course();course.setId("XB2006112-"+i);course.setName("Name-"+i);date = new Date();date.setYear(104-i);course.setStartDate(date);date = new Date();date.setYear(105+i);course.setEndDate(date);Instructor instructor = new Instructor();instructor.setFirstName("firstName-"+i);instructor.setLastName("lastName-"+i);course.setInstructor(instructor);courseList.add(course);}return courseList;}
}

类controller

  1. CourseController.java
package com.simple.mvc;import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Controller
public class CourseController{@Autowiredprivate CourseService courseService;public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {List<Course> courses = courseService.getAllCourses();return new ModelAndView("courseList","courses",courses);}public void setCourseService(CourseService courseService){this.courseService = courseService;}
}
  1. 编写velocity模板的页面
    现在编写Velocity模板,在WEB-INF/velocitly下面建立一个courseList.vm的文件,内容如下:
<html><head><title>Course List</title></head><body><h2>COURSE LIST</h2><table width="600" border="1" cellspacing="1" cellpadding="1"><tr bgcolor="#999999"><td>Course ID</td><td>Name</td><td>Instructor</td><td>Start</td><td>End</td></tr>#foreach($course in $courses)<tr><td><a href="dispalyCourse.htm?id=${course.id}">${course.id}</a></td><td>$course.name</td><td>$course.instructor.lastName</td><td>${course.startDate}</td><td>${course.endDate}</td></tr>#end</table></body>
</html>

配置

这里的配置应该是在工程建立时进行的工作,为方便查看此文档,放在这里;分别配置web.xml及Spring配置文件training-servlet.xml。

先要配置java web工程的web.xml。这里spring mvc的servlet配置

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"><context-param><param-name>log4jConfigLocation</param-name><param-value>/WEB-INF/log4j.properties</param-value></context-param><filter><filter-name>EncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><async-supported>true</async-supported><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>EncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><servlet><servlet-name>training</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>training</servlet-name><url-pattern>*.htm</url-pattern><servlet-mapping><servlet-name>training</servlet-name><url-pattern>*.json</url-pattern></servlet-mapping><error-page><error-code>500</error-code><location>/common/500.jsp</location></error-page><error-page><error-code>404</error-code><location>/common/404.jsp</location></error-page></web-app>

接着Spring MVC的配置文件

<?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"xmlns:context="http://www.springframework.org/schema/context"xmlns:beans="http://www.springframework.org/schema/beans" xmlns:task="http://www.springframework.org/schema/task"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"><context:component-scan base-package="com.simple.mvc" /><!-- 定时器任务注解驱动 --><task:annotation-driven /><beans:import resource="training-servlet.xml" /><!--<beans:import resource="dataAccessContext.xml" /><beans:import resource="spring-security.xml" />-->
</beans>

还有 spring 的配置 training-servlet.xml,其中的velocityConfigurer为velocity 引擎配置。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" >
<beans><bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"><property name="mappings"><props><prop key="listCourse.htm">listCourse</prop></props></property></bean> <bean id="velocityConfigurer" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"><property name="resourceLoaderPath"><value>WEB-INF/velocity</value></property></bean><bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"><property name="suffix"><value>.vm</value></property></bean></beans>

运行

启动服务,并测试。
建立工程时,保证WEB-INF/lib下有如下包:
spring MVC相关的jar包,还有velocity-1.4.jar、commons-collections.jar、commons-logging.jar、log4j-1.2.13.jar等。

同时,视需要配置log4j.properties放在WEB-INF下。

然后运行工程,在浏览器中访问:

http://localhost:8080/velocity/listCourse.htm

总结

在spring MVC中配置velocity模板引擎

在Spring MVC中使用Velocity – Part 2 使用velocity 模板的布局layout

简介

现在,不支持布局功能的模板无法得到用户的青睐。velocity自然添加了对布局的支持。

配置

在velocity中加入布局的支持,使用的解析器引擎不是VelocityViewResolver,变成了VelocityLayoutViewResolver

请看下面的spring-mvc 配置文件
Spring mvc 配置文件(引入velocity相关配置spring-mvc.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"  xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->  <context:component-scan base-package="com.simple.controller" />  <!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->  <bean id="mappingJacksonHttpMessageConverter"  class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  <property name="supportedMediaTypes">  <list>  <value>text/html;charset=UTF-8</value>  </list>  </property>  </bean>  <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->  <bean  class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  <property name="messageConverters">  <list>  <ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->  </list>  </property>  </bean>  <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 p:prefix中模板放置路径 -->  <bean id="velocityConfig"  class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">  <property name="resourceLoaderPath" value="/WEB-INF/view/" />  <property name="velocityProperties">      <props>      <prop  key="input.encoding">UTF-8</prop>      <prop  key="output.encoding">UTF-8</prop>        </props>      </property>   </bean>  <bean id="viewResolver"  class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">  <property name="cache" value="true" />  <property name="prefix" value="" />  <property name="layoutUrl" value="layout.vm" />  <property name="suffix" value=".vm" />  <property name="contentType"><value>text/html;charset=UTF-8</value></property>    </bean>  <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"   p:prefix="/WEB-INF/view/" p:suffix=".jsp" /> -->  <!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">   <property name="defaultEncoding"> <value>UTF-8</value> </property> <property   name="maxUploadSize"> <value>32505856</value>上传文件大小限制为31M,31*1024*1024 </property>   <property name="maxInMemorySize"> <value>4096</value> </property> </bean> -->  </beans>

在检查一下web.xml工程配置

web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  id="WebApp_ID" version="3.0">  <display-name>mybatis</display-name>  <context-param>  <param-name>contextConfigLocation</param-name>  <param-value>classpath:config/applicationContext-user.xml</param-value>  </context-param>  <filter>  <description>字符集过滤器</description>  <filter-name>encodingFilter</filter-name>  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  <init-param>  <description>字符集编码</description>  <param-name>encoding</param-name>  <param-value>UTF-8</param-value>  </init-param>  </filter>  <filter-mapping>  <filter-name>encodingFilter</filter-name>  <url-pattern>/*</url-pattern>  </filter-mapping>  <listener>  <description>spring监听器</description>  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <!-- 防止spring内存溢出监听器 -->  <listener>  <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  </listener>  <!-- spring mvc servlet -->  <servlet>  <description>spring mvc servlet</description>  <servlet-name>springMvc</servlet-name>  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  <init-param>  <description>spring mvc 配置文件</description>  <param-name>contextConfigLocation</param-name>  <param-value>classpath:config/spring-mvc.xml</param-value>  </init-param>  <load-on-startup>1</load-on-startup>  </servlet>  <servlet-mapping>  <servlet-name>springMvc</servlet-name>  <url-pattern>*.do</url-pattern>  </servlet-mapping>  <welcome-file-list>  <welcome-file>/index.jsp</welcome-file>  </welcome-file-list>  <!-- 配置session超时时间,单位分钟 -->  <session-config>  <session-timeout>15</session-timeout>  </session-config>
</web-app>  

velocity及布局模板文件

在上面的配置中,velocity的文件multi为/WEB-INF/view/

  1. 模板文件layout.vm
<html>  <head>  <title>Spring MVC and Velocity</title>  </head>  <body>  <h1>Spring MVC and Velocity</h1>  $screen_content  <hr />  Copyright &copy 2014 lm  </body>
</html>  
  1. 列表页面 list.vm
<h2>List of Feeds</h2>
<ul>  #foreach($user in $users)  <li><a href="user/${user.userId}">${user.email}</a></li>  #end
</ul>  
  1. 详情页面 detail.vm
<h2>Detail of Feed</h2><p>Id: ${user.userId}</p>
<p>Title: ${user.email}</p>  

Spring MVC类

控制层Controller

UserController.java

package com.simple.controller;  import javax.servlet.http.HttpServletRequest;  import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;  import com.simple.entity.UserEntity;
import com.simple.service.UserService;  @Controller
public class UserController {  @Autowired private UserService userService;  @RequestMapping("/userList")  public String list(ModelMap model) {  model.put("users", userService.getUserEntities());  return "list";}  @RequestMapping("/user/{id}")  public String detail(@PathVariable(value = "id") String id, ModelMap model) {  model.put("user", userService.getUserEntityById(id));  return "detail"; }  }  

模型Model类

UserEntity.java

package com.simple.entity;  public class UserEntity {  private String userId;  private String userName;  private String password;  private String sex;  private String email;  // Getter / Setter ...
}

业务逻辑接口(Service)

package com.simple.service;  import java.util.List;  import com.simple.entity.UserEntity;  public interface UserService {  UserEntity getUserEntityById(String userId);  List<UserEntity> getUserEntities();  // UserEntity insertUserEntity(UserEntity userEntity);
}  

接口实现(ServiceImpl)

package com.simple.service.impl;  import java.util.ArrayList;  import org.springframework.beans.factory.annotation.Autowired;  import com.simple.entity.UserEntity;
import com.simple.service.UserService;  public class UserServiceImpl implements UserService {  private List<UserEntity> users;private UserServiceImpl() {//users = new ArrayList<UserEntity>();UserEntity user = new UserEntity();// user.set......users.add(user);//......}@Override  public UserEntity getUserEntityById(String userId) {  return this.users.get(0);  }  @Override  public List<UserEntity> getUserEntities() {  return this.users;  }  }  

总结

使用velocity的布局功能,velocity的resolver要替换为VelocityLayoutViewResolver。然后就可以使用velocity项目的layout相关指令了。

在Spring MVC中使用Velocity相关推荐

  1. 彻底解决Spring mvc中时间的转换和序列化等问题

    彻底解决Spring mvc中时间的转换和序列化等问题 参考文章: (1)彻底解决Spring mvc中时间的转换和序列化等问题 (2)https://www.cnblogs.com/childkin ...

  2. spring mvc中的@propertysource

    在spring mvc中,在配置文件中的东西,可以在java代码中通过注解进行读取了: @PropertySource  在spring 3.1中开始引入 比如有配置文件 config.propert ...

  3. spring_在Spring MVC中使用多个属性文件

    spring 每个人都听说过将单个Web应用程序组合成一个大型Web应用程序的门户. 门户软件的工作原理类似于mashup -来自多个来源的内容是在单个服务中获取的,大部分都显示在单个网页中. 门户软 ...

  4. Spring MVC中处理Request和Response的策略

    前沿技术早知道,弯道超车有希望 积累超车资本,从关注DD开始 作者:码农小胖哥, 图文编辑:xj 来源:https://mp.weixin.qq.com/s/3eFygsiVl8dC2nRy8_8n5 ...

  5. Spring MVC 中的 forward 和 redirect

    Spring MVC 中,我们在返回逻辑视图时,框架会通过 viewResolver 来解析得到具体的 View,然后向浏览器渲染.假设逻辑视图名为 hello,通过配置,我们配置某个 ViewRes ...

  6. Spring MVC中获取当前项目的路径

    Spring MVC中获取当前项目的路径 在web.xml中加入以下内容 <!--获取项目路径--><context-param><param-name>webAp ...

  7. Spring 2.5:Spring MVC中的新特性

    转载说明:infoQ就是牛人多,看人家去年就把Spring2.5注视驱动的MVC写出来了,还是这么详细,我真是自叹不如,今天偶尔看到这篇文章非常认真的拜读了2遍,简直是茅厕顿开啊....\(^o^)/ ...

  8. Spring MVC中的二三事

    HandlerMapping和HandlerAdapter 这个两个组件应该算是spring mvc中最重要的几个组件之一了,当一个请求到达DispatcherSerlvet后,spring mvc就 ...

  9. 在Spring MVC中使用Apache Shiro安全框架

    我们在这里将对一个集成了Spring MVC+Hibernate+Apache Shiro的项目进行了一个简单说明.这个项目将展示如何在Spring MVC 中使用Apache Shiro来构建我们的 ...

最新文章

  1. Java 构造方法与成员方法的区别
  2. 电脑硬件故障的几种简单检查方法
  3. 简单工厂之简单模型(uml)
  4. lua运行外部程序_Lua 协同程序(coroutine)
  5. [Python] np.array() 创建ndarray类型的数组
  6. Matlab之矩阵的特征值与特征向量求解
  7. 2.24小时365天不间断服务 --- 优化服务器及基础设施的拓扑结构(冗余,负载分流,高性能的实现)
  8. Android开发:《Gradle Recipes for Android》阅读笔记(翻译)2.4——更新新版本的Gradle...
  9. 官网jdk8,jdk11下载时需要登录Oracle账号的问题解决
  10. H5唤醒支付宝登录授权
  11. Hive的行列转换(行转多列、多列转行、行转单列、单列转行)
  12. java.lang.IllegalArgumentException: 字符[_]在域名中永远无效。 at
  13. 弘辽科技:淘宝流失率是什么意思?客户流失的原因有哪些?
  14. 华北工控计算机硬件,华北工控 | 嵌入式计算机硬件在卫星导航系统中的应用
  15. Kotlin学习笔记
  16. [单片机框架][drivers层][cw2015] fuelgauge 硬件电量计(二)
  17. 安卓开发学习日记第五天——奇怪的bug出现了(VT-x说没就没)_莫韵乐的欢乐日记
  18. oracle 异常错误 ORA-01555 caused by SQL statement below
  19. css3满天金光飞舞效果,CSS3金光四射的钥匙
  20. 如何把一个苹果卖到100万?

热门文章

  1. myeclipse问题
  2. 魔兽老玩家无需购买《燃烧远征》资料片序列号
  3. 关于测试用例的一些思考
  4. file命令及Linux重要关键路径介绍
  5. Paket:一个面向.NET的包管理器
  6. linux磁盘和文件系统管理
  7. 【转】HTML5第一人称射击游戏发布
  8. mysqldump死住(实际是导致mysqld crash)
  9. java多线程 生产者消费者_java多线程之生产者消费者经典问题 - 很不错的范例
  10. c语言五子棋代码_基于控制台的C语言贪吃蛇