标签:
一、Hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 数据库连接url地址 -->
<property name="connection.url">
jdbc:mysql://localhost:3306/spring
</property>
<!-- 数据库连接的用户名 -->
<property name="connection.username">root</property>
<!-- 数据库连接的用户密码 -->
<property name="connection.password">root</property>
<!-- 数据库连接驱动 -->
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- 数据库方言 -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!-- c3p0的配置 -->
<!-- hibernate4.org.hibernate.c3p0.internal.C3P0ConnectionProvider -->
<property name="hibernate.connection.provider_class">
org.hibernate.c3p0.internal.C3P0ConnectionProvider
</property>
<!-- 最小数量 -->
<property name="hibernate.c3p0.min_size">3</property>
<!-- 最大数量 -->
<property name="hibernate.c3p0.max_size">10</property>
<!--设定数据库连接的过期时间,以秒为单位, 如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 -->
<property name="hibernate.c3p0.timeout">120</property>
<!--每3000秒检查所有连接池中的空闲连接 以秒为单位 -->
<property name="hibernate.c3p0.idle_test_period">3000</property>
<!-- 当连接池耗尽并接到获得连接的请求,则新增加连接的数量 -->
<property name="hibernate.c3p0.acquire_increment">5</property>
<!-- 缓存 Statement 对象的数量 -->
<property name="hibernate.c3p0.max_statements">100</property>
<!-- 是否每次连接都验证连接是否可用 -->
<property name="hibernate.c3p0.validate">true</property>
<!-- 显示sql语句 -->
<property name="hibernate.show_sql">true</property>
<!-- hbm2ddl -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 映射文件 -->
<mapping resource="com/buslines/domain/Admin.hbm.xml" />
</session-factory>
</hibernate-configuration>
二、Spring相关配置
(1)applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- hibernate c3p0 sessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>
<!-- 创建模板对象 -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 封装dao对象 -->
<bean id="hibernateDaoSupport"
class="org.springframework.orm.hibernate4.support.HibernateDaoSupport"
abstract="true">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<!--事务管理器 -->
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 事务管理器的通知 -->
<tx:advice id="txAdvice" transaction-manager="hibernateTransactionManager">
<tx:attributes>
<tx:method name="save*" isolation="DEFAULT" propagation="REQUIRED" />
<tx:method name="update*" isolation="DEFAULT" propagation="REQUIRED" />
<tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!-- aop配置 -->
<aop:config>
<aop:pointcut expression="execution(* com.buslines.service..*.*(..))"
id="txpoint" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="txpoint" />
</aop:config>
<import resource="spring-dao.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-action.xml"/>
</beans>
(2)spring-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置dao对象 -->
<bean id="baseDaoImpl" class="com.buslines.dao.impl.BaseDaoImpl" parent="hibernateDaoSupport"/>
<bean id="adminDaoImpl" class="com.buslines.dao.impl.AdminDaoImpl" parent="baseDaoImpl"/>
</beans>
(3)spring-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置dao对象 -->
<bean id="baseServiceImpl" class="com.buslines.service.impl.BaseServiceImpl">
<property name="baseDao" ref="baseDaoImpl" />
</bean>
<bean id="adminServiceImpl" class="com.buslines.service.impl.AdminServiceImpl" parent="baseServiceImpl">
<property name="adminDao" ref="adminDaoImpl" />
</bean>
</beans>
(4)spring-action.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="baseAction" class="com.buslines.action.BaseAction">
<property name="baseService" ref="baseServiceImpl"/>
</bean>
<bean id="adminAction" class="com.buslines.action.AdminAction" parent="baseAction" scope="prototype">
<property name="adminService" ref="adminServiceImpl"/>
</bean>
</beans>
三、struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.objectFactory" value="spring" />
<package name="admins" extends="json-default" namespace="/hytc">
<interceptors>
<!-- 定义一个自己的拦截器栈 -->
<interceptor-stack name="mydefaultStack">
<!-- 引入拦截器栈 -->
<interceptor-ref name="paramsPrepareParamsStack">
<!-- 修改prepare拦截器栈的属性 -->
<param name="prepare.alwaysInvokePrepare">false</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 让自己的action采用自己定义的拦截器栈 -->
<default-interceptor-ref name="mydefaultStack" />
<action name="adminAction_*" class="adminAction" method="{1}">
<result name="login" type="json"></result>
<result name="init">/WEB-INF/index.jsp</result>
<result name="go">/WEB-INF/page/admin_select.jsp</result>
<result name="select" type="json">
<!-- 忽略配置 -->
<param name="ignoreHierarchy">false</param>
<param name="root">pagination</param>
</result>
<result name="save" type="json">
<!-- 忽略配置 -->
<param name="ignoreHierarchy">false</param>
<param name="root">data</param>
</result>
<result name="update" type="json">
<!-- 忽略配置 -->
<param name="ignoreHierarchy">false</param>
<param name="root">data</param>
</result>
<result name="delete" type="json">
<!-- 忽略配置 -->
<param name="ignoreHierarchy">false</param>
<param name="root">data</param>
</result>
</action>
</action>
</package>
</struts>
四、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"
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>ssh</display-name>
<!-- 延迟关闭session 的顺序位于struts2过滤之上 否则延迟关闭session不起作用 -->
<filter>
<filter-name>opensession</filter-name>
<filter-class>
org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
</filter-class>
<init-param>
<param-name>flushMode</param-name>
<param-value>AUTO</param-value>
</init-param>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>opensession</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 启动struts的配置 -->
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 监听器来加载spring的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
五、相关接口和实现
(一)Dao
(1)BaseDao
public interface BaseDao {
/**
* 保存实体对象
* @param entity
* @return
*/
Serializable save(Object entity);
/**
* 保存或者更新实体对象
* @param entity
*/
void saveOrUpdate(Object entity);
/**
* 更新实体对象
* @param entity
*/
void update(Object entity);
/**
* 删除实体对象
* @param entity
*/
void delete(Object entity);
/**
* 根据id删除实体对象
* @param clazz
* @param id
*/
void deleteById(final Class clazz,Integer id);
/**
* 更具id查询实体对象
* @param id
* @return
*/
Object getObject(Class clazz,Integer id);
/**
* 查询所有实体对象
* @param clazz
* @return
*/
List getObjects(final Class clazz);
/**
* 分页查询实体对象
* @param clazz
* @param firstResult
* @param MaxResults
* @return
*/
List getObjects(final Class clazz, final int firstResult,
final int maxResults);
/**
* 获取总记录数
* @param clazz
* @return
*/
Integer getCount(final Class clazz);
/**
* 条件查询分页实体对象
* @param clazz
* @param whereSql
* @param firstResult
* @param MaxResults
* @return
*/
List getObjects(final Class clazz, final String whereSql,
final int firstResult, final int maxResults);
/**
* 条件的获取总记录数
* @param clazz
* @return
*/
Integer getCount(final Class clazz,final String whereSql);
/**
* 条件查询分页实体对象并且有排序的字段
* @param clazz
* @param whereSql
* @param firstResult
* @param MaxResults
* @return
*/
List getObjects(final Class clazz, final String whereSql,
final int firstResult, final int maxResults,final String sort,final String order);
//boolean checkColumn(final Class clazz,final String value);
}
(2)AdminDao
public interface AdminDao extends BaseDao{
}
(3)BaseDaoImpl
public class BaseDaoImpl extends HibernateDaoSupport implements BaseDao {
@Override
public Serializable save(Object entity) {
return getHibernateTemplate().save(entity);
}
@Override
public void saveOrUpdate(Object entity) {
getHibernateTemplate().saveOrUpdate(entity);
}
@Override
public void update(Object entity) {
getHibernateTemplate().update(entity);
}
@Override
public void delete(Object entity) {
getHibernateTemplate().delete(entity);
}
@Override
public void deleteById(final Class clazz, final Integer id) {
delete(getHibernateTemplate().get(clazz, id));
}
/**
* hql QBC 本定sql 等
*/
@Override
public List getObjects(final Class clazz) {
return getHibernateTemplate().execute(new HibernateCallback<List>() {
@Override
public List doInHibernate(Session session)
throws HibernateException {
return session.createCriteria(clazz).list();
}
});
}
@Override
public List getObjects(final Class clazz, final int firstResult,
final int maxResults) {
return getHibernateTemplate().execute(new HibernateCallback<List>() {
@Override
public List doInHibernate(Session session)
throws HibernateException {
return session.createCriteria(clazz)
.setFirstResult(firstResult).setMaxResults(maxResults)
.list();
}
});
}
@Override
public Integer getCount(final Class clazz) {
return getHibernateTemplate().execute(new HibernateCallback<Integer>() {
@Override
public Integer doInHibernate(Session session)
throws HibernateException {
return Integer.valueOf(session
.createQuery(
" select count(e) from " + clazz.getName()
+ " as e ").uniqueResult().toString());
}
});
}
@Override
public List getObjects(final Class clazz, final String whereSql,
final int firstResult, final int maxResults) {
return getHibernateTemplate().execute(new HibernateCallback<List>() {
@Override
public List doInHibernate(Session session)
throws HibernateException {
return session
.createQuery(
" from " + clazz.getName() + " as e "
+ whereSql).setFirstResult(firstResult)
.setMaxResults(maxResults).list();
}
});
}
@Override
public Integer getCount(final Class clazz, final String whereSql) {
return getHibernateTemplate().execute(new HibernateCallback<Integer>() {
@Override
public Integer doInHibernate(Session session)
throws HibernateException {
return Integer.valueOf(session
.createQuery(
" select count(e) from " + clazz.getName()
+ " as e " + whereSql).uniqueResult()
.toString());
}
});
}
@Override
public List getObjects(final Class clazz, final String whereSql,
final int firstResult, final int maxResults, final String sort,
final String order) {
return getHibernateTemplate().execute(new HibernateCallback<List>() {
@Override
public List doInHibernate(Session session)
throws HibernateException {
return session
.createQuery(
" from " + clazz.getName() + " as e "
+ whereSql + " order by " + sort + " "
+ order).setFirstResult(firstResult)
.setMaxResults(maxResults).list();
}
});
}
@Override
public Object getObject(Class clazz, Integer id) {
return getHibernateTemplate().get(clazz, id);
}
}
(4)AdminDaoImpl
public class AdminDaoImpl extends BaseDaoImpl implements AdminDao{
}
(二)Service
(1)BaseService
public interface BaseService {
/**
* 保存实体对象
* @param entity
* @return
*/
Serializable save(Object entity);
/**
* 保存或者更新实体对象
* @param entity
*/
void saveOrUpdate(Object entity);
/**
* 更新实体对象
* @param entity
*/
void update(Object entity);
/**
* 删除实体对象
* @param entity
*/
void delete(Object entity);
/**
* 根据id删除实体对象
* @param clazz
* @param id
*/
void deleteById(final Class clazz,Integer id);
/**
* 更具id查询实体对象
* @param id
* @return
*/
Object getObject(Class clazz,Integer id);
/**
* 查询所有实体对象
* @param clazz
* @return
*/
List getObjects(final Class clazz);
/**
* 分页查询实体对象
* @param clazz
* @param firstResult
* @param MaxResults
* @return
*/
List getObjects(final Class clazz, final int firstResult,
final int MaxResults);
/**
* 获取总记录数
* @param clazz
* @return
*/
Integer getCount(final Class clazz);
/**
* 条件查询分页实体对象
* @param clazz
* @param whereSql
* @param firstResult
* @param MaxResults
* @return
*/
List getObjects(final Class clazz, final String whereSql,
final int firstResult, final int maxResults);
/**
* 条件的获取总记录数
* @param clazz
* @return
*/
Integer getCount(final Class clazz,final String whereSql);
/**
* 条件查询分页实体对象并且有排序的字段
* @param clazz
* @param whereSql
* @param firstResult
* @param MaxResults
* @return
*/
List getObjects(final Class clazz, final String whereSql,
final int firstResult, final int maxResults,final String sort,final String order);
/**
* 批量删除实体bean
* @param ids
*/
void deleteObjects(Class clazz,String ids);
}
(2)AdminService
public interface AdminService extends BaseService {
}
(3)BaseServiceImpl
public class BaseServiceImpl implements BaseService {
private BaseDao baseDao;
public void setBaseDao(BaseDao baseDao) {
this.baseDao = baseDao;
}
@Override
public Serializable save(Object entity) {
// TODO Auto-generated method stub
return baseDao.save(entity);
}
@Override
public void saveOrUpdate(Object entity) {
baseDao.saveOrUpdate(entity);
}
@Override
public void update(Object entity) {
baseDao.update(entity);
}
@Override
public void delete(Object entity) {
baseDao.delete(entity);
}
@Override
public void deleteById(Class clazz, Integer id) {
baseDao.deleteById(clazz, id);
}
@Override
public List getObjects(Class clazz) {
return baseDao.getObjects(clazz);
}
@Override
public List getObjects(Class clazz, int firstResult, int maxResults) {
return baseDao.getObjects(clazz, firstResult, maxResults);
}
@Override
public Integer getCount(Class clazz) {
return baseDao.getCount(clazz);
}
@Override
public List getObjects(Class clazz, String whereSql, int firstResult,
int maxResults) {
return baseDao.getObjects(clazz, whereSql, firstResult, maxResults);
}
@Override
public Integer getCount(Class clazz, String whereSql) {
return baseDao.getCount(clazz, whereSql);
}
@Override
public List getObjects(Class clazz, String whereSql, int firstResult,
int maxResults, String sort, String order) {
return baseDao.getObjects(clazz, whereSql, firstResult, maxResults,
sort, order);
}
@Override
public Object getObject(Class clazz, Integer id) {
// TODO Auto-generated method stub
return baseDao.getObject(clazz, id);
}
@Override
public void deleteObjects(Class clazz, String ids) {
// 拆分ids的字符串1,2,13
String idarr[] = ids.split(",");
if (idarr.length == 1) {
baseDao.delete(baseDao.getObject(clazz, Integer.valueOf(idarr[0])));
} else {
for (int i = 0; i < idarr.length; i++) {
baseDao.delete(baseDao.getObject(clazz,
Integer.valueOf(idarr[i])));
}
}
}
}
(4)AdminServiceImpl
public class AdminServiceImpl extends BaseServiceImpl implements AdminService{
private AdminDao adminDao;
public void setAdminDao(AdminDao adminDao) {
this.adminDao = adminDao;
}
}
六、action实现
(1)BaseAction
public class BaseAction extends ActionSupport implements ServletContextAware,
ServletRequestAware, SessionAware {
// 封装servlet有关的api
public ServletContext application;
public HttpServletRequest request;
public Map session;
// 分页对象
public Pagination pagination;
public BaseService baseService;
// 当前页
public int page;
// 每页显示的记录数
public int rows;
public Serializable data;
public Integer id;
public String ids;
public void setIds(String ids) {
this.ids = ids;
}
public void setId(Integer id) {
this.id = id;
}
public Serializable getData() {
return data;
}
public void setPage(int page) {
this.page = page;
}
public void setRows(int rows) {
this.rows = rows;
}
public Pagination getPagination() {
return pagination;
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
@Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
@Override
public void setServletContext(ServletContext application) {
this.application = application;
}
public void setBaseService(BaseService baseService) {
this.baseService = baseService;
}
/**
*转发界面
*/
public String go(){
return "go";
}
}
(2)AdminAction
public class AdminAction extends BaseAction implements ModelDriven<Admin>,Preparable{
private AdminService adminService;
private String name;
private Admin entity;
public void setEntity(Admin entity) {
this.entity = entity;
}
public void setName(String name) {
this.name = name;
}
public void setAdminService(AdminService adminService) {
this.adminService = adminService;
}
public String save(){
data = adminService.save(entity);
return "save";
}
public String update(){
System.out.println(entity.toString());
adminService.update(entity);
System.out.println("update");
return "update";
}
public String delete(){
adminService.deleteObjects(Admin.class,ids);
return "delete";
}
public String select() {
// 组合sql语句的操作
String sql = spliceWhereSql();
// 获取总记录数
// 调用baseDao中的baseService
long total = adminService.getCount(Admin.class, sql);
// 创建分页对象
pagination = new Pagination(page, rows, total);
// 获取开始的记录数
int firstResult = (int) pagination.getStartSize();
// 获取每页显示的记录数
int maxResults = rows;
// 查询当前页中的信息
List rows = adminService.getObjects(Admin.class, sql, firstResult,
maxResults);
// 设置查询出来信息 赋值给当前页对象
pagination.setRows(rows);
return "select";
}
/**
* 组合拼接sql语句的 版权归redarmychen所有 hj
*
* @return
*/
private String spliceWhereSql() {
// 定义sql语句
String whereSql = " where 1=1 ";
// 拼接sql语句
if (name != null && !"".equals(name)) {
whereSql = whereSql + " and name like ‘%" + name + "%‘ ";
}
// 返回sql语句
return whereSql;
}
/**
* 登录操作
*
* @return
*/
public String login() {
return SUCCESS;
}
/**
* 登录成功的初始化操作
*
* @return
*/
public String init() {
return "init";
}
@Override
public void prepare() throws Exception {
// TODO Auto-generated method stub
}
public void prepareSave() throws Exception {
entity = new Admin();
}
public void prepareUpdate() throws Exception {
// 如果页面中传入的参数与数据库中的字段完全一致,则只需要new一个新的对象,否则调用
// adminService.getObject(Category.class, id)这个方法查询数据,返回这个对象即可
entity = (Admin) adminService.getObject(Admin.class, id);
}
@Override
public Admin getModel() {
// TODO Auto-generated method stub
return entity;
}
}
七、页面显示
admin_select.jsp
<!-- easyui的样式文件 -->
<link rel="stylesheet" type="text/css"
href="./themes/default/easyui.css">
<!-- 图标样式的文件 -->
<link rel="stylesheet" type="text/css"
href="${pageContext.request.contextPath }/themes/icon.css">
<!-- 引入jquery easyui文件 -->
<!-- jQuery文件 -->
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/easyui/jquery.min.js"></script>
<!-- jQuery easyui的文件 -->
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/easyui/jquery.easyui.min.js"></script>
<!-- 自定义js文件 -->
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/admin/admin.js"></script>
</head>
<body class="easyui-layout" data-options="fit:true">
<div data-options="region:‘north‘" style="height:40px">
<div style="margin-top: 5px">
用户名:<input type="text" id="aname"/>
<input type="button" id="searchBtn" value="搜索"/>
</div>
</div>
<div data-options="region:‘center‘,fit:true">
<table id="dg"></table>
</div>
<!-- 用户的添加对话框开始 -->
<div id="adddlg" style="width:400px">
<div style="padding:10px 60px 20px 60px">
<form id="addff" class="easyui-form" method="post"
data-options="novalidate:false">
<table cellpadding="5">
<tr>
<td>用户名:</td>
<td><input class="easyui-textbox" type="text" name="name"
data-options="required:true,validType:{checkName:[]}" ></input></td>
</tr>
<tr>
<td>密码:</td>
<td><input class="easyui-textbox" name="pass"
data-options="required:true" ></input></td>
</tr>
</table>
</form>
</div>
</div>
<!-- 用户的添加对话框结束 -->
<!--用户的更新对话框开始 -->
<div id="updatedlg" style="width:400px">
<div style="padding:10px 60px 20px 60px">
<form id="updateff" class="easyui-form" method="post"
data-options="novalidate:false">
<table cellpadding="5">
<input type="hidden" name="id"/>
<tr>
<td>用户名:</td>
<td><input class="easyui-textbox" type="text" name="name"
data-options="required:true"></input></td>
</tr>
<tr>
<td>密码:</td>
<td><input class="easyui-textbox" name="pass"
data-options="required:true" ></input></td>
</tr>
</table>
</form>
</div>
</div>
<!-- 类别的更新对话框结束 -->
</body>
admin.js
// 搜索的地址
var searchUrl = "./hytc/adminAction_select.action"; // page=3
var saveUrl = "./hytc/adminAction_save.action";
var deleteUrl = "./hytc/adminAction_delete.action";
var updateUrl = "./hytc/adminAction_update.action";
//查询条件
var queryParams = null;
// 当文档加载完毕,然后触发该匿名函数
$(document).ready(function() {
initDialog();
// 初始化数据
initData();
//获取按钮对象
var $searchBtn=$("#searchBtn");
//注册事件
$searchBtn.click(function(){
//获取输入的条件值
var value=$("#aname").val();
//查询条件
queryParams={name:value};
//重新初始化数据
initData();
});
});
/**
* 初始化对话框
*/
function initDialog() {
$(‘#adddlg‘).dialog({
title : ‘添加用户‘,
width : 400,
closed : true,
cache : false,
modal : true,
buttons : [ {
text : ‘添加‘,
iconCls : ‘icon-ok‘,
handler : function() {
// 调用添加的方法
submitAddForm();
}
}, {
text : ‘取消‘,
iconCls : ‘icon-cancel‘,
handler : function() {
// 取消添加,关闭对话框
$(‘#adddlg‘).dialog(‘close‘);
}
} ]
});
//更新用户
$(‘#updatedlg‘).dialog({
title : ‘更新用户‘,
width : 400,
closed : true,
cache : false,
modal : true,
buttons : [ {
text : ‘更新‘,
iconCls : ‘icon-ok‘,
handler : function() {
// 调用更新的方法
submitUpdateForm();
}
}, {
text : ‘取消‘,
iconCls : ‘icon-cancel‘,
handler : function() {
// 取消更新,关闭对话框
$(‘#updatedlg‘).dialog(‘close‘);
}
} ]
});
}
/**
* 初始化数据
*/
function initData() {
// 显示数据
$(‘#dg‘).datagrid({
url : searchUrl, // 请求的url地址 每次请求都会附带 page:当前页,page=3&rows=10;
// rows:每页显示记录数
queryParams : queryParams,
method : "post", // 请求的方式
//height:300,
pageSize : 3, // 每页显示的数量
pageList : [ 3, 5, 10, 15 ], // 可选的每页显示的数量的集合
pagination : true, // 添加分页效果
loadMsg : "正在加载数据,请稍候",
singleSelect : false, // 可以选择多行
columns : [ [ {
field : ‘cbk‘,
title : "全选",
width : 100,
checkbox : true
}, {
field : "id",
title : "序号",
width : 100
}, {
field : "name",
title : "用户名称",
width : 100
},
{
field : "pass",
title : "密码",
width : 100,
align : "right"
} ] ],
toolbar : [ {
iconCls : "icon-add",
text : "添加用户",
handler : function() {
// 调用添加用户的函数
newObject();
$(‘#selectrole‘).combobox({
url :selectRoleUrl,
valueField : ‘id‘,
textField : ‘name‘,
loadFilter:function(data){
return data.roles;
}
});
}
}, {
iconCls : "icon-edit",
text : "编辑用户",
handler : function() {
editObject();// 调用编辑方法
}
},
{
iconCls : "icon-remove",
text : "删除用户",
handler : function() {
deleteObject();
}
}, {
iconCls : "icon-help",
text:"帮助",
handler : function() {
alert("帮助按钮");
}
} ],
});
// 通过getPager方法 获取分页的对象
var pager = $("#dg").datagrid("getPager");
// 重新设置分页对象的值
pager.pagination({
pageSize : 3,// 每页显示的数量
pageList : [ 3, 5, 10, 15 ],// 可选的每页显示的数量的集合
beforePageText : "当前页", // 文本
afterPageText : "共{pages}页", // 文本
displayMsg : "当前页从{from}到{to}共{total}记录"// 文本
});
}
// 添加用户
function newObject() {
// 清空form表单
$(‘#addff‘).form(‘clear‘);
// 打开添加的对话框
$(‘#adddlg‘).dialog(‘open‘);
}
// 提交对话框中的form表单,完成用户的添加
function submitAddForm() {
$(‘#addff‘).form({
url : saveUrl,
onSubmit : function() {
// do some check
// return false to prevent submit;
return $(this).form(‘validate‘);
},
success : function(data) {
if (data > 0) {
// 添加成功,关闭对话框
$(‘#adddlg‘).dialog(‘close‘);
$("#dg").datagrid("reload");
show("用户添加成功");
} else {
show("用户添加失败");
}
}
});
// submit the form
$(‘#addff‘).submit();
}
// 提交对话框中的form表单,完成用户的更新
function submitUpdateForm() {
$(‘#updateff‘).form({
url : updateUrl,
onSubmit : function() {
return $(this).form(‘validate‘);
},
success : function() {
// 更新成功,关闭对话框
$(‘#updatedlg‘).dialog(‘close‘);
$("#dg").datagrid("reload");
show("用户更新成功");
}
});
// submit the form
$(‘#updateff‘).submit();
}
// 获取多行
function getSelections() {
var ids = [];
// 获取选中的行
var rows = $(‘#dg‘).datagrid(‘getSelections‘);
// 遍历选中的行
for (var i = 0; i < rows.length; i++) {
// 得到具体的行对象
var row = rows[i];
// 得到该行的id值,存入到ids数组中
ids.push(row.id);
}
return ids;
}
// 删除用户
function deleteObject() {
// 获取要删除行对应id的集合
var ids = getSelections();
if (ids.length == 0) {
show("请选择要删除的用户");
} else {
$.messager.confirm(‘确认‘,‘你确定要删除该用户信息吗?‘,function(r){
if(r){
// 发送ajax请求
$.post(deleteUrl, {
ids : ids.join(",")
}, function(data) {
// 重新加载datagrid数据
$("#dg").datagrid("reload");
show("用户删除成功");
}, "json");
}else{
show("取消删除操作");
}
});
}
}
// 编辑用户
function editObject() {
// 获取选中的所有的行
var rows = $(‘#dg‘).datagrid(‘getSelections‘);
// 判断rows大小
if (rows.length == 0) {
show("请选择要编辑的用户");
} else if (rows.length == 1) {
var row = rows[0];// 获取选中行的对象
// 重新加载form表单数据
loadLocal(row);
$(‘#updatedlg‘).dialog(‘open‘);
} else {
show("请选择单行");
}
/* var row = $(‘#dg‘).datagrid(‘getSelected‘);
if (row){
$(‘#dlg‘).dialog(‘open‘).dialog(‘setTitle‘,‘Edit User‘);
$(‘#fm‘).form(‘load‘,row); url = ‘update_user.php?id=‘+row.id; }*/
}
/**
* 重新加载方法
* @param row
*/
function loadLocal(row) {
$(‘#updateff‘).form(‘load‘, {
id : row.id,
name : row.name,
pass : row.pass,
});
}
//弹出消息框
function show(msg) {
$.messager.show({
// 高度
height : 80,
// 消息框的标题
title : "信息提示",
msg : msg,
// 消息框弹出的样式
showType : ‘slide‘,
// 居中弹出消息框
style : {
right : ‘‘,
top : document.body.scrollTop + document.documentElement.scrollTop
+ 200,
bottom : ‘‘
},
// 设置消息框的过期时间
timeout : 600
});
}
标签:
原文地址:http://www.cnblogs.com/ly-radiata/p/4609787.html