上周写了篇基于spring3.0.5 mvc 简单用户管理实例 ( http://www.iteye.com/topic/1072244 ) ,反应还不错,本周闲来无事(外面又在下 雨 淹了不少地方啊)就试了一下Spring3 MVC + jQuery easyUI 做的ajax版本用户管理,因为之前做过一个项目是struts2 + jQuery easyUI 做的。对比了一下,发现 Spring3 MVC确实是比struts2方便啊,特别是对ajax的支持上,转换JSON内置了jackson,太方便了。还是先把jar包帖出来吧
还是要先配置web.xml文件,如下:
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
-
- <filter>
- <filter-name>Set Character Encoding</filter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- <init-param>
- <param-name>forceEncoding</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter>
-
- <filter-mapping>
- <filter-name>Set Character Encoding</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
-
- <servlet>
- <servlet-name>spring3</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>spring3</servlet-name>
-
- <url-pattern>/</url-pattern>
- </servlet-mapping>
然后在applicationContext.xml中简单配置一下数据源和sessionFactory还有声明一下事务处理,这个和之前那一版是一样的,如下:
- <?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:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"
- 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/tx
- http://www.springframework.org/schema/tx/spring-tx-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/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" default-autowire="byName">
-
-
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
- <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
- <property name="url" value="jdbc:mysql://127.0.0.1:3306/test"></property>
- <property name="username" value="root"></property>
- <property name="password" value="root"></property>
- </bean>
- <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
- <property name="dataSource" ref="dataSource"/>
- <property name="mappingDirectoryLocations">
- <list>
- <value>classpath:com/fsj/spring/model</value>
- </list>
- </property>
- <property name="hibernateProperties">
- <props>
- <prop key="hibernate.dialect">
- org.hibernate.dialect.MySQLDialect
- </prop>
- <prop key="hibernate.show_sql">
- true
- </prop>
- </props>
- </property>
- </bean>
-
-
- <context:component-scan base-package="com.fsj.spring">
- <context:exclude-filter type="regex" expression="com.fsj.spring.web.*"/>
- </context:component-scan>
-
-
- <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
- <property name="sessionFactory" ref="sessionFactory"></property>
- </bean>
-
- <aop:config>
- <aop:advisor pointcut="execution(* com.fsj.spring.service.*Service.*(..))" advice-ref="txAdvice"/>
- </aop:config>
-
- <tx:advice id="txAdvice" transaction-manager="txManager">
- <tx:attributes>
- <tx:method name="get*" read-only="true"/>
- <tx:method name="query*" read-only="true"/>
- <tx:method name="find*" read-only="true"/>
- <tx:method name="load*" read-only="true"/>
- <tx:method name="*" rollback-for="Exception"/>
- </tx:attributes>
- </tx:advice>
-
-
- </beans>
最后需要配置的就是spring mvc的配置文件spring3-servlet.xml了,这个和非ajax的版本稍微有点不一样,加入了对json数据转换的配置,因为我用的数据传输都是json类型的数据,如下:
- <?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:p="http://www.springframework.org/schema/p"
- 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-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" default-autowire="byName">
-
-
-
- <mvc:resources mapping="/img/**" location="/img/"/>
- <mvc:resources mapping="/js/**" location="/js/"/>
- <mvc:resources mapping="/css/**" location="/css/"/>
- <mvc:resources mapping="/html/**" location="/html/"/>
-
-
-
-
- <context:component-scan base-package="com.fsj.spring.web" />
-
-
-
-
- <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
- <property name="interceptors">
- <list>
- <bean class="com.fsj.spring.util.MyHandlerInterceptor"/>
- </list>
- </property>
- </bean>
-
- <!--
- ②:启动Spring MVC的注解功能,完成请求和注解POJO的映射,
- 配置一个基于注解的定制的WebBindingInitializer,解决日期转换问题,方法级别的处理器映射
- -->
- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
- <property name="cacheSeconds" value="0" />
- <property name="webBindingInitializer">
- <bean class="com.fsj.spring.util.MyWebBinding" />
- </property>
- <span style="color: #0000ff;">
- <property name="messageConverters">
- <list>
- <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
- </list>
- </property></span>
-
-
- </bean>
-
- <!--
- ③:对模型视图名称的解析,即在模型视图名称添加前后缀
- InternalResourceViewResolver默认的就是JstlView所以这里就不用配置viewClass了
- -->
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/WEB-INF/view/"></property>
- <property name="suffix" value=".jsp"></property>
- </bean>
-
- </beans>
主页面用了easyui-layout,简单分为了上、左、中三部分,左边的菜单用的easyui-accordion,中间的主页面没有用iframe,就是一个普通的div就可以完成之前要用的iframe的功能哦,还是帖出来吧:
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@ include file="/taglibs.jsp" %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>spring3</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <script type="text/javascript">
- jQuery.ajaxSetup({cache:false});//ajax不缓存
- jQuery(function($){
-
- });
-
- function setmain(title,href){
- $(".combo-panel").parent(".panel").remove(); //<span style="color: #0000ff;">清楚所有class为combo-panel的class为panel的父元素,解决combobox在页面缓存的问题</span>
-
-
- var centerURL = href;
- var centerTitle = title;
- $('body').layout('panel','center').panel({
- title:"所在位置:"+centerTitle,
- href:centerURL
- });
- $('body').layout('panel','center').panel('refresh');
- return false;
- }
-
- //弹出窗口
- function showWindow(options){
- jQuery("#MyPopWindow").window(options);
- }
- //关闭弹出窗口
- function closeWindow(){
- $("#MyPopWindow").window('close');
- }
- </script>
- </head>
-
- <body class="easyui-layout" id="mainBody">
-
- <div region="north" split="false" style="height:100px;text-align: center;" border="false">
- <h1>欢迎: ${userSessionInfo.name}</h1>
- </div>
-
-
- <div region="west" class="menudiv" split="true" title="系统菜单" style="width:200px;overflow:hidden;">
- <div id="menuDiv" class="easyui-accordion" fit="false" border="false" animate="false">
- <div title="用户管理" style="overflow:hidden;">
- <ul>
- <li id="rightLi${child.id}" style="cursor: pointer;"
- onclick="setmain('用户管理','${ctx}/user/list')" >用户管理</li>
- </ul>
- <ul>
- <li id="rightLi${child.id}" style="cursor: pointer;"
- onclick="setmain('用户管理','${ctx}/user/list')" >用户管理</li>
- </ul>
- <ul>
- <li id="rightLi${child.id}" style="cursor: pointer;"
- onclick="setmain('用户管理','${ctx}/user/list')" >用户管理</li>
- </ul>
- </div>
- <div title="部门管理" style="overflow:hidden;">
- <ul>
- <li id="rightLi${child.id}">部门管理</li>
- <li id="rightLi${child.id}">部门管理</li>
- </ul>
- </div>
- <div title="XXX管理" style="overflow:hidden;">
- <ul>
- <li id="rightLi${child.id}">XXX管理</li>
- <li id="rightLi${child.id}">XXX管理</li>
- </ul>
- </div>
- <div title="XXX管理" style="overflow:hidden;">
- <ul>
- <li id="rightLi${child.id}">XXX管理</li>
- <li id="rightLi${child.id}">XXX管理</li>
- <li id="rightLi${child.id}">XXX管理</li>
- </ul>
- </div>
- </div>
- </div>
-
-
- <div region="center" class="maindiv" title="所在位置: 首页" style="overflow-x:hidden;padding: 0px;" <span style="color: #ff0000;">href="${ctx}/html/welcome.html"</span>
-
- ></div>
- <div id="MyPopWindow" modal="true" shadow="false" minimizable="false" cache="false" maximizable="false" collapsible="false" resizable="false" style="margin: 0px;padding: 0px;overflow: auto;"></div>
- </body>
- </html>
这样点击用户管理就可以在center层中打开用户列表了,个人感觉效果还不错,比jQuery UI要漂亮一些,用着也很方便。
中间主页面的代码也很简单,用到了jQeury easyUI的datagrid、combogrid等,用法很简单,关键就是json数据,另外还用到了最好用的日期控件My97DatePicker:
- <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
- <html>
- <head>
- <script type="text/javascript">
- jQuery(function($){
- $('#userTable').datagrid({
- title:'用户列表', //标题
- method:'post',
- iconCls:'icon-edit', //图标
- singleSelect:false, //多选
- height:360, //高度
- fitColumns: true, //自动调整各列,用了这个属性,下面各列的宽度值就只是一个比例。
- striped: true, //奇偶行颜色不同
- collapsible:true,//可折叠
- url:"user/queryList", //数据来源
- sortName: 'user.id', //排序的列
- sortOrder: 'desc', //倒序
- remoteSort: true, //服务器端排序
- idField:'uid', //主键字段
- queryParams:{}, //查询条件
- pagination:true, //显示分页
- rownumbers:true, //显示行号
- columns:[[
- {field:'ck',checkbox:true,width:2}, //显示复选框
- {field:'user.name',title:'名字',width:20,sortable:true,
- formatter:function(value,row,index){return row.user.name;} //需要formatter一下才能显示正确的数据
- },
- {field:'user.age',title:'年龄',width:20,sortable:true,
- formatter:function(value,row,index){return row.user.age;}
- },
- {field:'user.birthday',title:'生日',width:30,sortable:true,
- formatter:function(value,row,index){return row.user.birthday;}
- },
- {field:'user.deptId',title:'部门',width:30,sortable:true,
- formatter:function(value,row,index){
- return row.deptName; //该列的值是deptId,显示的是deptName
- }
- }
- ]],
- toolbar:[{
- text:'新增',
- iconCls:'icon-add',
- handler:function(){
- addrow();
- }
- },'-',{
- text:'更新',
- iconCls:'icon-edit',
- handler:function(){
- updaterow();
- }
- },'-',{
- text:'删除',
- iconCls:'icon-remove',
- handler:function(){
- deleterow();
- }
- },'-'],
- onLoadSuccess:function(){
- $('#userTable').datagrid('clearSelections'); //一定要加上这一句,要不然datagrid会记住之前的选择状态,删除时会出问题
- }
- });
-
- //<span style="color: #0000ff;">下拉表格初始化,这个东西在ajax下要尽量少用,太变态了,每加载一次就会重新创建一次,隐藏在页面上,</span>
-
-
- //<span style="color: #0000ff;">时间一长效率很低,用firebug一看页面上有几十个同样的层保存着下拉框中的内容,只有整个页面全部刷新才清除。</span>
-
-
- //不知道新版本修正了没有,我目前的做法是点击菜单的时候手动清除一下。
- $('#deptCombo').combogrid({
- idField:'id', //ID字段
- textField:'name', //显示的字段
- url:"dept/queryAll",
- fitColumns: true,
- striped: true,
- editable:false,//不可编辑,只能选择
- columns:[[
- {field:'code',title:'编号',width:100},
- {field:'name',title:'名称',width:150}
- ]]
- });
-
- });
- //新增
- function addrow(){
- showWindow({
- title:'增加用户信息',
- href:'user/popWindow',
- width:300,
- height:250,
- onLoad: function(){
- $('#userForm').form('clear');
- }
-
- });
- }
- //更新
- function updaterow(){
- var rows = $('#userTable').datagrid('getSelections');
- //<span style="color: #ff0000;">这里有一个jquery easyui datagrid的一个小bug,必须把主键单独列出来,要不然不能多选</span>
-
-
- if(rows.length==0){
- $.messager.alert('提示',"请选择你要更新的用户",'info');
- return;
- }
- if(rows.length > 1){
- $.messager.alert('提示',"只能选择一位用户进行更新",'info');
- return;
- }
- showWindow({
- title:'更新用户信息',
- href:'user/popWindow',
- width:300,
- height:250,
- onLoad: function(){
- //<span style="color: #ff0000;">自动将数据填充到表单中,无需再查询数据库</span>
-
- ,这里需要注意:
- //<span style="color: #ff0000;">如果用的是struts2,它的表单元素的名称都是user.id这样的,那load的时候不能加.user要.form('load', rows[0]);</span>
-
-
- //而spring mvc中表单元素的名称不带对象前缀,直拉就是id,所以这里load的时候是:.<span style="color: #ff0000;">form('load', rows[0].user)</span>
-
-
- $("#userForm").form('load', rows[0].user);
- }
- });
- }
-
- //删除
- function deleterow(){
- $.messager.confirm('提示','确定要删除吗?',function(result){
- if (result){
- var rows = $('#userTable').datagrid('getSelections');
- var ps = "";
- $.each(rows,function(i,n){
- if(i==0)
- ps += "?uid="+n.uid;
- else
- ps += "&uid="+n.uid;
- });
- $.post('user/delete'+ps,function(data){
- $('#userTable').datagrid('reload');
- $.messager.alert('提示',data.mes,'info');
- });
- }
- });
- }
- //表格查询
- function searchUser(){
- var params = $('#userTable').datagrid('options').queryParams; //先取得 datagrid 的查询参数
- var fields =$('#queryForm').serializeArray(); //自动序列化表单元素为JSON对象
- $.each( fields, function(i, field){
- params[field.name] = field.value; //设置查询参数
- });
- $('#userTable').datagrid('reload'); //设置好查询参数 reload 一下就可以了
- }
- //清空查询条件
- function clearForm(){
- $('#queryForm').form('clear');
- searchUser();
- }
-
- </script>
- </head>
-
- <body>
- <form id="queryForm" style="margin:10;text-align: center;">
- <table width="100%">
- <tr>
- <td>名字:<input name="name" style="width: 200"></td>
- <td>年龄:<input class="easyui-numberspinner" name="age" min="1" max="120" increment="1" style="width:200px;"></input></td>
- <td align="center"><a href="#" onclick="clearForm();" class="easyui-linkbutton" iconCls="icon-search">清空</a></td>
- </tr>
- <tr>
- <td>生日:<input name="birthday" style="width: 200" class="Wdate" onClick="WdatePicker()"></td>
- <td>部门:<input id="deptCombo" name="deptId" style="width: 200"></td>
- <td align="center"><a href="#" onclick="searchUser();" class="easyui-linkbutton" iconCls="icon-search">查询</a></td>
- </tr>
- </table>
- </form>
- <div style="padding:10" id="tabdiv">
- <table id="userTable"></table>
- </div>
- </body>
- </html>
这里不得不说,用spring3 MVC对json的转换直接太方便了,只需要在上面说的spring3-servlet.xml中配置一下就可以,后台只需要@ResponseBody一个注解就OK,可以返回map、list等多种数据类型,spring会自动转换为json对象的,比struts2要方便多了,用struts2要<package name="def" extends="json-default" >,还要用json类型的result:<result name="success" type="json"><param name="root">jsonData</param></result>,还要自己组织jsonData,Controller类如下:
- @Controller
- @RequestMapping("/user")
- public class UserController {
-
- @RequestMapping(value="/list",method=RequestMethod.GET)
- public String list(Model model) throws Exception {
- model.addAttribute("deptList", deptService.getDeptList());
- return "user/list";
- }
-
- @RequestMapping(value="/queryList",method=RequestMethod.POST)
- <span style="color: #0000ff;">@ResponseBody </span>
-
-
- public Map<String, Object> queryList(DataGridModel dgm,TUser user) throws Exception{
-
-
-
-
- return userService.getPageList(dgm, user);
- }
-
- @RequestMapping(value="/popWindow",method=RequestMethod.GET)
- public String popWindow() throws Exception{
- return "user/popWindow";
- }
-
- @RequestMapping(value="/addOrUpdate",method=RequestMethod.POST)
- @ResponseBody
- public Map<String, String> addOrUpdate(TUser user) throws Exception{
-
- Map<String, String> map = new HashMap<String, String>();
- try {
- userService.addOrUpdate(user);
- map.put("mes", "操作成功");
- } catch (Exception e) {
- e.printStackTrace();
- map.put("mes", "操作失败");
- throw e;
- }
- return map;
- }
-
- @RequestMapping(value="/delete",method=RequestMethod.POST)
- @ResponseBody
- public Map<String, String> delete(@RequestParam("uid") <span style="color: #ff0000;">List<Integer> uid</span>
-
- )throws Exception{
-
-
-
- Map<String, String> map = new HashMap<String, String>();
- try {
- userService.deleteUsers(uid);
- map.put("mes", "删除成功");
- } catch (Exception e) {
- e.printStackTrace();
- map.put("mes", "删除失败");
- throw e;
- }
- return map;
- }
-
-
- private IDeptService deptService;
-
- public IDeptService getDeptService() {
- return deptService;
- }
-
- public void setDeptService(IDeptService deptService) {
- this.deptService = deptService;
- }
-
- private IUserService userService;
-
- public IUserService getUserService() {
- return userService;
- }
-
- public void setUserService(IUserService userService) {
- this.userService = userService;
- }
- }
怎么样是不是很方便,下面提供了实例项目的下载,实例中没有jar包,jar请依据图中自己添加。
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
|
- 太阳神喻
- 等级:
- 性别:
- 文章: 47
- 积分: 150
- 来自: 武汉
|
jQuery easyUI所需要的JSON格式必须是这样的:
- {
- "total":239,
- "rows":[
- {"code":"001","name":"Name 1","addr":"Address 11","col4":"col4 data"},
- {"code":"002","name":"Name 2","addr":"Address 13","col4":"col4 data"},
- {"code":"003","name":"Name 3","addr":"Address 87","col4":"col4 data"},
- {"code":"004","name":"Name 4","addr":"Address 63","col4":"col4 data"},
- {"code":"005","name":"Name 5","addr":"Address 45","col4":"col4 data"},
- {"code":"006","name":"Name 6","addr":"Address 16","col4":"col4 data"},
- {"code":"007","name":"Name 7","addr":"Address 27","col4":"col4 data"},
- {"code":"008","name":"Name 8","addr":"Address 81","col4":"col4 data"},
- {"code":"009","name":"Name 9","addr":"Address 69","col4":"col4 data"},
- {"code":"010","name":"Name 10","addr":"Address 78","col4":"col4 data"}
- ]
- }
所以后台只需返回一个map对象包括total和rows两个key即可:
- public Map<String, Object> getPageListByExemple(DataGridModel dgm,TUser user) throws Exception{
- Map<String, Object> result = new HashMap<String, Object>(2);
- List totalList = getHibernateTemplate().findByExample(user);
-
- List pagelist = getHibernateTemplate().findByExample(user, (dgm.getPage() - 1) * dgm.getRows(), dgm.getRows());
-
- result.put("total", totalList == null ? 0 : totalList.size());
- result.put("rows", pagelist);
- return result;
- }
-
-
- public Map<String, Object> getPageList(DataGridModel dgm,TUser user) throws Exception{
-
- Map<String, Object> result = new HashMap<String, Object>(2);
- String countQuery = "select count(*) from TUser user,TDept dept where user.deptId=dept.id ";
- String fullQuery = "select new map(user as user,user.id as uid,dept.name as deptName) from TUser user,TDept dept where user.deptId=dept.id ";
-
- String orderString = "";
- if(StringUtils.isNotBlank(dgm.getSort()))
- orderString = " order by " + dgm.getSort() + " " + dgm.getOrder();
-
- StringBuffer sb = new StringBuffer();
- Map<String,Object> params = new HashMap<String,Object>();
-
- if(user != null) {
- if(StringUtils.isNotBlank(user.getName())) {
- sb.append(" and user.name like :userName");
- params.put("userName", "%"+user.getName()+"%");
- }
- if(user.getAge() != null) {
- sb.append(" and user.age = :age");
- params.put("age", user.getAge());
- }
- if(user.getBirthday() != null) {
- sb.append(" and user.birthday = :birthday");
- params.put("birthday", user.getBirthday());
- }
- if(user.getDeptId() != null) {
- sb.append(" and dept.id = :deptId");
- params.put("deptId", user.getDeptId());
- }
- }
-
-
-
-
-
-
- Query queryTotal = getSession().createQuery(countQuery + sb.toString());
- Query queryList = getSession().createQuery(fullQuery + sb.toString() + orderString)
- .setFirstResult((dgm.getPage() - 1) * dgm.getRows()).setMaxResults(dgm.getRows());
- if(params!=null && !params.isEmpty()){
- Iterator<String> it = params.keySet().iterator();
- while(it.hasNext()){
- String key = it.next();
- queryTotal.setParameter(key, params.get(key));
- queryList.setParameter(key, params.get(key));
- }
- }
- int total = ((Long)queryTotal.uniqueResult()).intValue();
-
- List list = queryList.list();
- result.put("total", total);
- result.put("rows", list);
-
- return result;
- }
|