您的位置:首页 > Web前端 > JQuery

Spring3 MVC + jQuery easyUI 做的ajax版本用户管理

2015-01-22 14:56 676 查看
闲来无事(外面又在下 雨 淹了不少地方啊)就试了一下Spring3 MVC + jQuery easyUI 做的ajax版本用户管理,因为之前做过一个项目是struts2 + jQuery easyUI 做的。对比了一下,发现 Spring3 MVC确实是比struts2方便啊,特别是对ajax的支持上,转换JSON内置了jackson,太方便了。还是先把jar包帖出来吧



还是要先配置web.xml文件,如下:

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>

<!-- 默认所对应的配置文件是WEB-INF下的{servlet-name}-servlet.xml,这里便是:spring3-servlet.xml -->

<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>

<!-- 这里可以用 / 但不能用 /* ,拦截了所有请求会导致静态资源无法访问,所以要在spring3-servlet.xml中配置mvc:resources -->

<url-pattern>/</url-pattern>

</servlet-mapping>

然后在applicationContext.xml中简单配置一下数据源和sessionFactory还有声明一下事务处理,这个和之前那一版是一样的,如下:

Xml代码


<?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">

<!-- 注意上面的default-autowire="byName",如果没有这个声明那么HibernateDaoSupport中的sessionFactory不会被注入 -->

<!-- 约定优于配置,约定优于配置 -->

<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><!-- 这里直接映射的pojo类所在的包,简单方便不用没次加一个pojo类都需要到这里来添加 -->

<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>

<!-- 自动扫描组件,这里要把web下面的 controller去除,他们是在spring3-servlet.xml中配置的,如果不去除会影响事务管理的。-->

<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代码


<?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">

<!-- default-autowire="byName",约定优于配置,约定优于配置 -->

<!-- 配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理,3.04新增功能,需要重新设置spring-mvc-3.0.xsd -->

<mvc:resources mapping="/img/**" location="/img/"/>

<mvc:resources mapping="/js/**" location="/js/"/>

<mvc:resources mapping="/css/**" location="/css/"/>

<mvc:resources mapping="/html/**" location="/html/"/>

<!--

①:对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能

-->

<context:component-scan base-package="com.fsj.spring.web" />

<!--

②:启动Spring MVC的注解功能,完成请求和注解POJO的映射,添加拦截器,类级别的处理器映射

-->

<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;"><!-- 配置一下对json数据的转换 -->

<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的功能哦,还是帖出来吧:

Html代码


<%@ 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>

<!-- easyui-layout 可分上下左右中五部分,中间的是必须的,支持href,这样就可以不用iframe了 -->

<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:

Html代码


<%@ 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类如下:

Java代码


@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{

//<span style="color: #ff0000;">spring太给力了,可以自动装配两个对象 会自动的装返回的Map转换成JSON对象</span>

//return userService.getPageListByExemple(dgm, user);

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{

//spring会利用jackson自动将返回值封装成JSON对象,比struts2方便了很多

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{

//<span style="color: #ff0000;">spring mvc 还可以将参数绑定为list类型</span>

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请依据图中自己添加。

spring3.zip (549.8 KB)
下载次数: 11251

查看图片附件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: