日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

在Spring MVC中使用Velocity

發(fā)布時間:2023/12/15 javascript 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 在Spring MVC中使用Velocity 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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

目的

Spring MVC中結(jié)合velocity的配置和操作。

簡介

我們要顯示一個課程列表,需要如下的 Java model類,在 mvc model中分別建立:Course.java、Instructor.java。 在service下創(chuàng)建CourseService.java文件,在controller下建立CourseController.java。其中Course是課程表信息;Instructor是任課教師的信息;CourseService用來列出課程信息,兼有隱含DAO;ListCourse是實現(xiàn)了Controller的控制器,返回ModelAndView。下面分別列出代碼:

Java Model

  • 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 }
  • Instructor.java
  • package com.simple.mvc;public class Instructor{private String firstName;private String lastName;// getter / setter }

    類 service

  • 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

  • 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;} }
  • 編寫velocity模板的頁面
    現(xiàn)在編寫Velocity模板,在WEB-INF/velocitly下面建立一個courseList.vm的文件,內(nèi)容如下:
  • <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" /><!-- 定時器任務注解驅(qū)動 --><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

    總結(jié)

    在spring MVC中配置velocity模板引擎

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

    簡介

    現(xiàn)在,不支持布局功能的模板無法得到用戶的青睞。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執(zhí)行AJAX時,返回JSON出現(xiàn)下載文件 --> <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轉(zhuǎn)換器 --> </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監(jiān)聽器</description> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止spring內(nèi)存溢出監(jiān)聽器 --> <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/

  • 模板文件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>
  • 列表頁面 list.vm
  • <h2>List of Feeds</h2> <ul> #foreach($user in $users) <li><a href="user/${user.userId}">${user.email}</a></li> #end </ul>
  • 詳情頁面 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 ... }

    業(yè)務邏輯接口(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); }

    接口實現(xiàn)(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; } }

    總結(jié)

    使用velocity的布局功能,velocity的resolver要替換為VelocityLayoutViewResolver。然后就可以使用velocity項目的layout相關指令了。

    總結(jié)

    以上是生活随笔為你收集整理的在Spring MVC中使用Velocity的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。