Spring MVC與Velocity整合

Velocity簡介

Apache Velocity 是一個基於java的模板引擎(template engine)。它允許任何人僅僅簡單的使用模板語言(template language)來引用由java代碼定義的對象。

當Velocity應用於web開發時,界面設計人員可以和java程序開發人員同步開發一個遵循MVC架構的web站點,也就是說,頁面設計人 員可以只關注頁面的顯示效果,而由java程序開發人員關注業務邏輯編碼。Velocity將java代碼從web頁面中分離出來,這樣爲web站點的長期維護提供了便利,同時也爲我們在JSP和PHP之外又提供了一種可選的方案。

Velocity應用場景

  1. Web 應用:開發者在不使用 JSP 的情況下,可以用 Velocity 讓 HTML 具有動態內容的特性;
  2. 源代碼生成:Velocity 可以被用來生成 Java 代碼、SQL 或者 PostScrip;
  3. 自動 Email:很多軟件的用戶註冊、密碼提醒或者報表都是使用 Velocity 來自動生成的;
  4. 轉換 xml;

SpringMVC+Velocity整合

Velocity現在應用非常廣泛,以下將詳細講解SpringMVC項目與Velocity整合

1. pom.xml文件

引入相關依賴的jar包,主要包含 velocity-1.7.jar和velocity-tools-2.0.jar包

<!-- start velocity -->
<dependency>
	<groupId>org.apache.velocity</groupId>
	<artifactId>velocity</artifactId>
	<version>1.7</version>
</dependency>
      <dependency>
          <groupId>org.apache.velocity</groupId>
          <artifactId>velocity-tools</artifactId>
          <version>2.0</version>
      </dependency>
<dependency>
	<groupId>velocity-tools</groupId>
	<artifactId>velocity-tools-generic</artifactId>
	<version>1.4</version>
</dependency>
<dependency>
	<groupId>velocity-tools</groupId>
	<artifactId>velocity-tools-view</artifactId>
	<version>1.4</version>
</dependency>
<!-- end velocity -->

2. 視圖配置

<!-- 配置velocity引擎  -->
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
	<property name="resourceLoaderPath"
			  value="/WEB-INF/templates/views/,/WEB-INF/templates/,/WEB-INF/templates/decorators"/>
	<property name="configLocation"
			  value="/WEB-INF/classes/config/properties/velocity.properties"/>
</bean>

3. 配置velocity.properties文件

----------------------------------------------------------------------------
runtime.log.logsystem.class = org.apache.velocity.runtime.log.SimpleLog4JLogSystem

runtime.log.logsystem.log4j.category = sys.template
runtime.log = velocity_error_log

runtime.log.error.stacktrace = false
runtime.log.warn.stacktrace = false
runtime.log.info.stacktrace = false
runtime.log.invalid.reference = false

input.encoding=utf-8
output.encoding=utf-8
default.contentType=text/html

directive.foreach.counter.name = velocityCount
directive.foreach.counter.initial.value = 1

directive.include.output.errormsg.start = <!-- include error : 
directive.include.output.errormsg.end   =  see error log -->

directive.parse.max.depth = 10
velocimacro.library = VM_global_library.vm
velocimacro.library.autoreload = true

velocimacro.permissions.allow.inline = true
velocimacro.permissions.allow.inline.to.replace.global = true
velocimacro.permissions.allow.inline.local.scope = true

runtime.interpolate.string.literals = true

resource.manager.class = org.apache.velocity.runtime.resource.ResourceManagerImpl
resource.manager.cache.class = org.apache.velocity.runtime.resource.ResourceCacheImpl

directive.foreach.maxloops = -1

4. 編寫velocity頁面

配置完後,寫一個vm頁面,該頁面的路徑在:WEB-INF/templates/views/下

#set($random=$mathTool.getRandom())
<title>velocity</title>
<!--公共css-->
<link href="${rc.contextPath}/css/reset.css?version=$random" rel="stylesheet">
<link href="${rc.contextPath}/css/public.css?version=$random" rel="stylesheet">
<link href="${rc.contextPath}/css/flight.css?version=$random" rel="stylesheet">
<!--pnrcss-->
<link href="${rc.contextPath}/css/pnr.css?version=$random" rel="stylesheet">
<link href="${rc.contextPath}/css/application.css?version=$random" rel="stylesheet">
<link href="${rc.contextPath}/css/order_new.css?version=$random" rel="stylesheet">
<link href="http://static.solaridc.com/allshared/js/doubledate/blue/doubleDate.css" rel="stylesheet" type="text/css" />
<!--日期選擇開始-->
<script type="text/javascript" src="${rc.contextPath}/js/jquery-1.8.3.min.js"></script>

<script type="text/javascript" src="${rc.contextPath}/js/common/layer/layer.js?version=1.0"></script>
<script type="text/javascript" src="${rc.contextPath}/laydate/laydate.js"></script>
<script type="text/javascript" src="${rc.contextPath}/layui/layui.all.js"></script>
<script type="text/javascript" src="${rc.contextPath}/js/profit/commonProfit.js?version=$random"></script>
<script type="text/javascript" src="${rc.contextPath}/js/profit/tradeOrderInfo.js?version=$random"></script>


<style>
    .sel_btn{
        height: 21px;
        line-height: 21px;
        padding: 0 11px;
        background: #02bafa;
        border: 1px #26bbdb solid;
        border-radius: 3px;
        color: #fff;
        display: inline-block;
        text-decoration: none;
        font-size: 12px;
        outline: none;
    }
    .sel_btn_style{
        text-decoration: underline;
        display: inline-block;
        height: 22px;
        text-align: center;
        line-height: 22px;
        zoom: 1;
        padding: 0 8px;
        text-decoration: none;
        color: #2993d1;
    }
</style>


<div class="main list_main">
    <div class="pnr_import">
        <ul class="tab">
            <li><a href="/trade/velocity.in" style="width: 120px;">velocity</a><b></b></li>
        </ul>
    </div>
        <div class="application_information">
            <form name="tradeOrderInfos" id="tradeOrderInfos" action="/trade/velocity.in" method="post">
                <input type="hidden" name="radioFlag" id="radioFlag" value="$!map.tradeOrderInfoVo.radioFlag">
                <input id="downloadFlag" name="downloadFlag" type="hidden" value="false"/>
                <input type="hidden" id="pageNo" name="pageNo" value="1"/>
                <input type="hidden" id="weekData" name="weekData" value="$!map.tradeOrderInfoVo.weekChoose"/>
                <ul class="mi_application">
                    <li>
                        <label>日期 :</label>
                        <input type="text" readonly="readonly" name="queryDate" class="ipttxt doubledate ipticon idTerm2" value="$!map.tradeOrderInfoVo.queryDate"/>
                    </li>

                    <li style="width: 560px;">
                        <label style="width: 170px;">
                            週期<input type="radio" style="width:15px;" class="radioMonth" checked/><input type="radio" style="width:15px;" class="radioWeek"/><input type="radio" style="width:15px;" class="radioDay"/></label>
                        <select id="monthChoose" class="p_select_a search_platform ipttxt" name="monthChoose">
                            <option value="">全部</option>
                            <option value="1" #if($!map.tradeOrderInfoVo.monthChoose == 1) selected="selected" #end>一月</option>
                            <option value="2" #if($!map.tradeOrderInfoVo.monthChoose == 2) selected="selected" #end>二月</option>
                            <option value="3" #if($!map.tradeOrderInfoVo.monthChoose == 3) selected="selected" #end>三月</option>
                            <option value="4" #if($!map.tradeOrderInfoVo.monthChoose == 4) selected="selected" #end>四月</option>
                            <option value="5" #if($!map.tradeOrderInfoVo.monthChoose == 5) selected="selected" #end>五月</option>
                            <option value="6" #if($!map.tradeOrderInfoVo.monthChoose == 6) selected="selected" #end>六月</option>
                            <option value="7" #if($!map.tradeOrderInfoVo.monthChoose == 7) selected="selected" #end>七月</option>
                            <option value="8" #if($!map.tradeOrderInfoVo.monthChoose == 8) selected="selected" #end>八月</option>
                            <option value="9" #if($!map.tradeOrderInfoVo.monthChoose == 9) selected="selected" #end>九月</option>
                            <option value="10" #if($!map.tradeOrderInfoVo.monthChoose == 10) selected="selected" #end>十月</option>
                            <option value="11" #if($!map.tradeOrderInfoVo.monthChoose == 11) selected="selected" #end>十一月</option>
                            <option value="12" #if($!map.tradeOrderInfoVo.monthChoose == 12) selected="selected" #end>十二月</option>
                        </select>
                        <select id="weekChoose" class="p_select_a search_platform ipttxt" name="weekChoose">

                        </select>

                        <input type="text" id="startDayChoose" readonly="readonly" name="startDate" class="ipttxt doubledate ipticon idTerm2" value="$!map.tradeOrderInfoVo.startDate"/>
                        <span class="dayChoose"></span>
                        <input type="text" id="endDayChoose" readonly="readonly" name="endDate" class="ipttxt doubledate ipticon idTerm2" value="$!map.tradeOrderInfoVo.endDate"/>

                    </li>

                </ul>

                <ul class="mi_application">

                </ul>
                <div class="appBtn">
                    <a class="font_button" style="cursor:pointer;" onclick="searchScreen('tradeOrderInfos')">立即查詢</a>
                    <a class="blue_button" style="cursor:pointer;" onclick="cleanFrom('tradeOrderInfos')">清空條件</a>
                </div>
            </form>
        </div>

        <div class="content_Order">
                    <table class="table bordertable tablecenter">
                        <tr>
                            <th>單號</th>
                            <th>類型</th>
                        </tr>
                        #foreach($tradeOrderInfo in $map.tradeOrderInfos.list)
                        <tr>
                            <td>
                                No$!tradeOrderInfo.objNo
                            </td>
                            <td>
                                $!tradeOrderInfo.paymentType
                            </td>
                        </tr>
                        #end

                    </table>
            </div>


		#page(${map.tradeOrderInfos.pageNum} ${map.tradeOrderInfos.navigatepageNums} ${map.tradeOrderInfos.pages} ${map.tradeOrderInfos.total} ${map.tradeOrderInfos.startRow} ${map.tradeOrderInfos.endRow} "tradeOrderInfos")
    </div>
</div>

5. 控制層代碼

package com.liantuo.finance.web.controller.profit;

import com.github.pagehelper.PageInfo;
import com.liantuo.finance.domain.TradeOrderInfo;
import com.liantuo.finance.service.TradeOrderInfoService;
import com.liantuo.finance.utils.Result;
import com.liantuo.finance.vo.profit.TradeOrderInfoVo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/trade")
public class VelocityController {
    private static final Logger logger = Logger.getLogger(TradeOrderInfoController.class);

    @Autowired
    private TradeOrderInfoService tradeOrderInfoService;

    @RequestMapping(value = "/velocity.in")
    public ModelAndView velocity(HttpServletRequest request,
                                 HttpServletResponse response,
                                 TradeOrderInfoVo tradeOrderInfoVo) {

        Map<String, Object> model = new HashMap<String, Object>();

        Result<PageInfo<TradeOrderInfo>> result = null;
        tradeOrderInfoVo.setPageSize(5);
        try{
            result = tradeOrderInfoService.selectTradeOrderInfoPage(tradeOrderInfoVo);
        }catch (Exception e){
            e.printStackTrace();
            return new ModelAndView("common/Error");
        }

        model.put("tradeOrderInfos", result.getObject());
        model.put("tradeOrderInfoVo", tradeOrderInfoVo);
        return new ModelAndView("/profit/velocity", "map", model);
    }

}

6. 頁面展示

請求路徑:http://127.0.0.1:8083/trade/velocity.in
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章