一.簡介
最近項目一直在用SpringMVC+ Easyui +FreeMarker,最近比較有時間,重新複習一下,整個的搭建的過程,以及使用。
FreeMarker是模板引擎,是一種基於模板的、用來生成輸出文本的通用工具,是基於Java的開發包和類庫的。FreeMarker被設計用來生成HTML Web頁面,特別是基於MVC(Model View Controller)模式的應用程序,FreeMarker與Web容器無關,即在Web運行時,它並不知道Servlet或HTTP,使用Servlet提供的數據動態地生成 HTML。
FreeMarker跟JSP相比,JSP運行時,需要在被執行的時候編譯成Servlet, FreeMarker模板技術不存在編譯,所以效率上FreeMarker會比較好,而且Freemarker內置了很多web編程中很常用的方法(日期轉換、數字格式化等)方便開發人員操作。
Easyui是一種基於jQuery的用戶界面插件集合,提供了大多數UI控件的使用,如:accordion,combobox,menu,dialog,tabs,validatebox,datagrid,window,tree等。
我們先看一下實現的列表,這樣我們在整合時,就是接下來我們要分析的,這樣思路會比較清晰,如圖所示:
二.FreeMarker、Easyui在SpringMVC整合
1.SpringMVC配置Easyui的配置文件(spring-mvc.xml)
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<!-- 解決JSON中文亂碼問題 -->
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 該類只有org.springframework.web-3.1.2.RELEASE.jar及以上版本纔有 使用該配置後,纔可以使用JSON相關的一些註解-->
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
<property name="objectMapper">
<!-- jackson-databind-2.2.2.jar -->
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd HH:mm:ss" />
</bean>
</property>
</bean>
</property>
</bean>
</list>
</property>
<!-- 啓動Spring MVC的註解功能,完成請求和註解POJO的映射 請求映射-->
<property name="webBindingInitializer">
<bean class="cn.social.card.util.DateBinding" />
</property>
</bean>
說明:AnnotationMethodHandlerAdapter類,通過註解,把一個URL映射到Controller類的方法上。這個類有很多個屬性,如源代碼圖所示:
2)messageConverters是一個列表,列表中有StringHttpMessageConverter、MappingJackson2HttpMessageConverter等都指定了supportedMediaTypes所支持的類型,如果請求頭Accept與某個messageConverter的supportedMediaTypes匹配,那麼將使用此messageConverter向響應體輸出內容。
(1)MappingJackson2HttpMessageConverter:使用 Jackson 的ObjectMapper 讀取/編寫 JSON 數據。它轉換媒體類型爲 application/json 的數據。該類只有org.springframework.web-3.1.2.RELEASE.jar及以上版本纔有使用該配置後,纔可以使用JSON相關的一些註解,並可以配置日期的格式需要引入jackson-databind-2.2.2.jar:如圖所示:
2. webBindingInitializer屬性配置
1)webBindingInitializer是全局的屬性編輯器,我們配置了日期格式化,有可以配置電話等格式。我們自定義全局的屬性編輯器時,需要實現了WebBindingInitializer接口中的initBinder方法,代碼如下:
public class DateBinding implements WebBindingInitializer {
/**
* 表單數據(全部是字符串)通過WebDataBinder進行綁定到命令對象,內部通過PropertyEditor實現
*/
public void initBinder(WebDataBinder binder, WebRequest request) {
//使用spring自帶的CustomDateEditor
//註冊自定義的屬性編輯器(日期)
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
}
日期格式化全局實現好了,我們把這個類AnnotationMethodHandlerAdapter屬性配置對應的,就OK了
2)也可以定義爲局部的屬性編輯器,只在對應的controller類裏有效的
@InitBinder
public void initBinder(WebDataBinder binder)
2.SpringMVC配置FreeMarker的配置文件(spring-mvc.xml)
<!-- 設置freeMarker的配置文件路徑 -->
<bean id="freemarkerConfiguration" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:freemarker.properties" />
</bean>
<bean id="xmlEscape" class="freemarker.template.utility.XmlEscape" />
<!-- freeMarker的模板配置 -->
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<!--視圖解析器會在/WEB-INF/template/路徑下查找-->
<property name="templateLoaderPath">
<value>/WEB-INF/template/</value>
</property>
<property name="freemarkerVariables">
<map>
<entry key="xml_escape" value-ref="xmlEscape" />
</map>
</property>
<property name="freemarkerSettings" ref="freemarkerConfiguration" />
</bean>
<!-- 配置freeMarker視圖解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />
<!--查找對應下所有以ftl結尾的文件-->
<property name="viewNames" value="*.ftl" />
<property name="contentType" value="text/html; charset=utf-8" />
<property name="cache" value="true" />
<property name="prefix" value="" />
<property name="suffix" value="" />
<property name="order" value="1"></property>
<property name="requestContextAttribute" value="rc" />
</bean>
tag_syntax=auto_detect
template_update_delay=2
default_encoding=UTF-8
output_encoding=UTF-8
locale=zh_CN
date_format=yyyy-MM-dd
time_format=HH:mm:ss
datetime_format=yyyy-MM-dd HH\:mm\:ss
number_format=#
三.SpringMVC的Controller代碼的實現
@Controller
@RequestMapping(value="/admin/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 用戶信息首頁
* @param session
* @param request
* @param map
* @return
*/
@RequestMapping(value="/index")
public String showRootLayer(HttpSession session, HttpServletRequest request, ModelMap map) {
String contextPath = request.getContextPath();
User user=(User) session.getAttribute("user");
map.put("contextPath", contextPath);
map.put("user", user);
return "/user/index.ftl";
}
/**
* 獲取用戶信息列表
* @param session
* @param page
* @param rows
* @return
*/
@ResponseBody
@RequestMapping(value="/listData", method=RequestMethod.POST)
public EUDGPagination detailDataList(HttpSession session, @RequestParam(value="page") int page, @RequestParam(value="rows") int rows, @RequestParam(value="yhm",required=false) String yhm, @RequestParam(value="rymc",required=false) String rymc, @RequestParam(value="rybh",required=false) String rybh) {
if(page<=0) page=1;
if(yhm!=null){yhm=yhm.trim();}
if(rymc!=null){rymc=rymc.trim();}
if(rybh!=null){rybh=rybh.trim();}
Map<String, Object> params = new HashMap<String, Object>();
params.put("yhm", yhm);
params.put("rymc", rymc);
params.put("rybh", rybh);
User user=(User) session.getAttribute("user");
params.put("user",user);
EUDGPagination pagination = userService.findUserPagination(page, rows, params);
return pagination;
}
/**
<span style="white-space:pre"> </span> * 詳情頁面
<span style="white-space:pre"> </span> * @param session
<span style="white-space:pre"> </span> * @param id
<span style="white-space:pre"> </span> * @param request
<span style="white-space:pre"> </span> * @param map
<span style="white-space:pre"> </span> * @return
<span style="white-space:pre"> </span> */
@RequestMapping(value="/detail")
public String detail(HttpSession session,@RequestParam(value="id") Long id, HttpServletRequest request, ModelMap map) {
String contextPath = request.getContextPath();
User user=userService.findUserById(id);
map.put("contextPath", contextPath);
User userSession=(User) session.getAttribute("user");
map.put("user", user);
map.put("userSession", userSession);
return "/user/detail.ftl";
}
}
四.Easyui列表的實現
<!DOCTYPE html PUBLIC "-/W3C/DTD XHTML 1.0 Transitional/EN" "http:/www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http:/www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>請假管理</title>
<link rel="stylesheet" type="text/css" href="${contextPath}/css/main_new.css" />
<link rel="stylesheet" type="text/css" href="${contextPath}/css/easyui.css">
<link rel="stylesheet" type="text/css" href="${contextPath}/css/icon.css">
<link rel="stylesheet" type="text/css" href="${contextPath}/css/demo.css">
<script type="text/javascript" src="${contextPath}/js/formatDate.js"></script>
<script type="text/javascript" src="${contextPath}/js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="${contextPath}/js/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${contextPath}/js/locale/easyui-lang-zh_CN.js"></script>
</head>
<body class="easyui-layout">
<div id="careRoadContentDiv" region="center" title=" 請假管理" border="false" style="overflow:hidden;">
<table id="list"></table>
</div>
<div id="jqueryToolbar" style="padding:5px;height:auto">
<div style="margin-top:5px; padding-bottom:8px; border-bottom:1px solid #ccc;">
人員名稱:<input type="text" id="rymc" style="width:120px" />
人員編號:<input type="text" id="rybh" style="width:120px" />
<a href="#" class="easyui-linkbutton" iconCls="icon-search" οnclick="searchData()">查詢</a>
<a href="#" class="easyui-linkbutton" iconCls="icon-reload" οnclick="resetCondition()">重置</a>
</div>
<div style="margin-top:5px;">
<a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" οnclick="create()">新增</a>
</div>
</div>
<script type="text/javascript">
$(function(){
$('#list').datagrid({
width:600,
height:600,
nowrap: false,
striped: true,
fit: true,
idField:'id',
url:'${contextPath}/admin/user/listData.json',
columns:[[
{field:'id',title:'',hidden:true},
{field:'rybh',title:'人員編號', align:'center',width:150},
{field:'rymc',title:'人員名稱', align:'center',width:100},
{field:'rylx',title:'人員類型', align:'center',width:100},
{field:'sszhmc',title:'所屬部門名稱', align:'center',width:200},
{field:'sqrybh',title:'授權人員編號', align:'center',width:150},
{field:'czry',title:'操作人員', align:'center',width:120},
{field:'czsj',title:'操作時間', align:'center',width:130},
{field:'opt', title:'操作', width:160, align:'center', formatter:function(value, rec, index){
var e ='';
var d ='';
e='<a href="###" οnclick="editRow('+rec.id+')">編輯</a>';
e += ' | ';
d='<a href="###" οnclick="deleteRow('+rec.id+')">刪除</a>';
d += ' | ';
var f = '<a href="###" οnclick="showRow('+ rec.id +')">詳情</a>';
return e+d+f;
}},
]],
toolbar:'#jqueryToolbar',
pagination:true,
queryParams:{},
onLoadSuccess:function(data){
$('#list').datagrid('clearSelections'); //清除掉列表選中記錄
if(data.total==0){
$('.datagrid-body-inner').eq(0).addClass("l_elist");
$('.datagrid-body').eq(1).append('<div class="r_elist">無數據</div>');
}else{
$('.datagrid-body-inner').eq(0).removeClass("l_elist");
}
}
});
//設置分頁控件
var p = $('#list').datagrid('getPager');
$(p).pagination({
pageSize: 10,//每頁顯示的記錄條數,默認爲
pageList: [10,20,30,40,50],//可以設置每頁記錄條數的列表
beforePageText: '第',//頁數文本框前顯示的漢字
afterPageText: '頁 共 {pages} 頁',
displayMsg: '當前顯示第 {from} 到 {to} 條記錄 共 {total} 條記錄'/*,
onBeforeRefresh:function(){
$(this).pagination('loading');
alert('before refresh');
$(this).pagination('loaded');
}*/
});
})
function searchData() {
var a = new Array();
var yhm = $("#yhm").val();
if(yhm!=null && yhm!="") a["yhm"]=yhm;
var rymc = $("#rymc").val();
if(rymc!=null && rymc!="") a["rymc"]=rymc;
var rybh = $("#rybh").val();
if(rybh!=null && rybh!="") a["rybh"]=rybh;
doSearch(a);
}
function doSearch(queryParams){
$('#list').datagrid('clearSelections');
$("#list").datagrid('options').queryParams=queryParams;
$("#list").datagrid('load');
}
function resetCondition(){
$("#yhm").val("");
$("#rymc").val("");
$("#rybh").val("");
}
function create() {
var url = '${contextPath}/admin/user/create.jhtml';
showMaxJqueryWindow("新增用戶信息", url);
}
function editRow(id) {
var url = '${contextPath}/admin/user/edit.jhtml?id='+id;
showMaxJqueryWindow("編輯用戶信息", url);
}
function showRow(id) {
var url = '${contextPath}/admin/user/detail.jhtml?id='+id;
showMaxJqueryWindow("用戶詳情", url);
}
</script>
</body>
</html>
{"total":4,"rows":[{"id":6,"sszhmc":"5301d","mm":"1","rybh":"test3","sqrybh":"1","rymc":"1 ","rylx":"1","czry":"admin","czsj":"2014-12-27 14:02:31","role":null},{"id":5,"sszhmc":"52k ","mm":"1","rybh":"test2","sqrybh":"1","rymc":"1","rylx":"1 ","czry":"admin","czsj":"2014-12-27 14:02:14","role":null},{"id":4,"sszhmc":"51h","mm":"1","rybh":"test","sqrybh":"1","rymc":"1 ","rylx":"1","czry":"admin ","czsj":"2014-12-27 13:39:25 ","role":null},{"id":3,"sszhmc":"50鄭 ","mm":"123456","rybh":"admin","sqrybh":"","rymc":"","rylx":"","czry":"","czsj":"","role":null}],"footer":null}
五.FreeMarker的實現
<body>
<div id="infoTabs" class="easyui-tabs" fit="true" border="false" style="margin: 0; height:530px;">
<div title="用戶信息" id="editInfo" style="margin:0">
<form id="tableForm" name="tableForm" action="${contextPath}/admin/base/report.jhtml" method="post">
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="border-t">
<tr class="item">
<td class="itemtit"> 人員編號</td>
<td class="border_b" colspan="3">
${user.rybh!''}
</td>
</tr>
<tr class="item">
<td class="itemtit"> 密碼</td>
<td class="border_b" colspan="3">
${user.mm!''}
</td>
</tr>
<tr class="item">
<td class="itemtit"> 授權人員編號</td>
<td class="border_b" colspan="3">
${user.sqrybh!''}
</td>
</tr>
<tr class="item">
<td class="itemtit"> 人員名稱</td>
<td class="border_b" colspan="3">
${user.rymc!''}
</td>
</tr>
<tr class="item">
<td class="itemtit"> 人員類型</td>
<td class="border_b" colspan="3">
${user.rylx!''}
</td>
</tr>
<tr class="item">
<td class="itemtit"> 所屬部門名稱</td>
<td class="border_b" colspan="3">
${user.sszhmc!''}
</td>
</tr>
<tr class="item">
<td class="itemtit"> 操作人員</td>
<td class="border_b" colspan="3">
${user.czry!''}
</td>
</tr>
<tr class="item">
<td class="itemtit"> 操作人員</td>
<td class="border_b" colspan="3">
${user.czsj!''}
</td>
</tr>
</table>
</form>
</div>
</div>