struts2+spring+mybatis结合easyUI_datagrid开发之显示所有数据

由于在公司实用到datagrid,所以就学习了一下,公司要用的ssm框架,本以为springMVC+Spring+Mybitas,但是一看要求是struts2,其实是一样的。之前没有接触过easyUI,所有设计界面的时候感觉有点吃力,只能一边查资料,一边学习,一边做,先学习一下显示所有数据这一个功能,后续慢慢补全比其他功能。

一.搭建easyUI环境,这个就不在这里具体说了,很容易就能查到
二.搭建ssm工程结构,
三.具体的配置:

1.     web.xml: 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>	
  	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<!-- spring监听器,加载xml文件 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- struts 前端控制器 -->
	<filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

2.applicationContext.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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       					   http://www.springframework.org/schema/beans/spring-beans.xsd
       					   http://www.springframework.org/schema/context 
       					   http://www.springframework.org/schema/context/spring-context.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">
    
<!--     数据源
     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"></property>
        <property name="username" value="vsplat_demo"></property>
        <property name="password" value="root"></property>
    </bean>  -->
   	<context:property-placeholder location="classpath:c3p0.properties"/>

    
    	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
			<property name="driverClass" value="${C3p0_class}"></property>
			<property name="jdbcUrl" value="${C3p0_url}"></property>		
			<property name="user" value="${C3p0_username}"></property>		
			<property name="password" value="${C3p0_password}"></property>	
		</bean> 
    
    
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
        <property name="dataSource" ref="dataSource"></property>

    </bean>
    
    <!-- 事务相关控制 -->
    <bean name="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 通知 -->
    <tx:advice id="tx"
        transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="get*" read-only="true" />
            <tx:method name="select*" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="pc" expression="execution(* com.test.service.*.*(..))" />
        <!--把事务控制在Service层-->
        <aop:advisor pointcut-ref="pc" advice-ref="tx" />
    </aop:config>
    
    <bean id="IJobDao" class="com.test.daoImpl.JobDaoImpl">
        <property name="sqlSessionFactory" ref="sessionFactory"></property>
    </bean>
    
    <bean id="jobService" class="com.test.serviceImpl.JobServiceImpl">
        <property name="iJobDao" ref="IJobDao"></property>
    </bean>
    
    
    <bean id="jobAction" class="com.test.action.JobAction" scope="prototype">
        <property name="jobService" ref="jobService">
        </property>
    </bean>
</beans>

3.sqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
   <typeAliases>
        <typeAlias type="com.test.entity.JobModel" alias="jobModel"></typeAlias>
    </typeAliases>
    <mappers>
        <mapper resource="com/test/serviceImpl/JobMapper.xml"/>
    </mappers>
</configuration>
4.JobMapper.xml(所有功能)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.test.entity.JobModel">
    <sql id="cols">
        id,name,job_name,salary,start_date
    </sql>
    <sql id="ucols">
        name=#{name},job_name=#{job_name},salary=#{salary},start_date=#{start_date}
    </sql>

    <!-- 查询所有记录 -->
    <select id="listAll" resultType="com.test.entity.JobModel">
        select <include refid="cols"/> from test_job
    </select>
    
    <!-- 按条件查询 -->
    <select id="find" parameterType="com.test.entity.JobModel" resultType="com.test.entity.JobModel">
        select * from test_job 
        <where>
        <if test="name!=null">
            and name like "%"#{name}"%"
        </if>
        </where>
    </select>
    
    <!-- 查询一个用户 -->
    <select id="get" parameterType="string" resultType="com.test.entity.JobModel">
        select <include refid="cols"/> from test_job where id=#{id}
    </select>
    
    <!-- 新增 -->
    <insert id="add" parameterType="com.test.entity.JobModel">
        insert into test_job (id,name,job_name,salary,start_date) values(#{id},#{name},#{job_name},#{salary},#{start_date})
    </insert>
    
    <!-- 修改 -->
    <update id="update" parameterType="com.test.entity.JobModel">
        update test_job set  <include refid="ucols"/>
        where id=#{id}
    </update>
    
    <!-- 删除 -->
    <delete id="delete" parameterType="string">
        delete from test_job where id=#{id}
    </delete>
</mapper>
5.struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC    
	"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"   
	"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
 	 <constant name="struts.ui.theme" value="simple"></constant>
     <constant name="struts.devMode" value="true"></constant>
     <constant name="struts.objectFactory" value="spring"></constant>    
     <package name="jobModel" namespace="/" extends="json-default">
        <action name="jobAction_*" class="com.test.action.JobAction" method="{1}">           
                  <result type="json" name="plist">
					<param name="root">result</param>>
				</result>                  
         </action>
     </package>
</struts>


6.实体类(JobModel)


public class JobModel {
	private String id;
	private String name;
	private String job_name;
	private String salary;
	private String start_date;
	public JobModel() {
		// TODO Auto-generated constructor stub
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getJob_name() {
		return job_name;
	}
	public void setJob_name(String job_name) {
		this.job_name = job_name;
	}
	public String getSalary() {
		return salary;
	}
	public void setSalary(String salary) {
		this.salary = salary;
	}
	public String getStart_date() {
		return start_date;
	}
	public void setStart_date(String start_date) {
		this.start_date = start_date;
	}	
}
7.DAO层(只包含实现类的,接口抽取即可)


public class JobDaoImpl extends SqlSessionDaoSupport implements IJobDao{

	@Override
	public List<JobModel> list() {
		return this.getSqlSession().selectList("com.test.entity.JobModel.listAll");
	}

	@Override
	public JobModel get(String id) {
		// TODO Auto-generated method stub
		return (JobModel) this.getSqlSession().selectOne("com.test.entity.JobModel.get",id);
	}

	@Override
	public int insert(JobModel u) {
		// TODO Auto-generated method stub
		return this.getSqlSession().insert("com.test.entity.JobModel.add",u);
	}

	@Override
	public int update(JobModel u) {
		// TODO Auto-generated method stub
		return this.getSqlSession().update("com.test.entity.JobModel.update",u);
	}

	@Override
	public int deleteById(String id) {
		// TODO Auto-generated method stub
		return this.getSqlSession().delete("com.test.entity.JobModel.delete",id);
	}

}

8.service层

public class JobServiceImpl implements JobService {

    private IJobDao iJobDao;
    
    public IJobDao getiJobDao() {
		return iJobDao;
	}

	public void setiJobDao(IJobDao iJobDao) {
		this.iJobDao = iJobDao;
	}

    public int deleteById(String id) {
        int i = iJobDao.deleteById(id);
     
        return i;
    }

    public JobModel get(String id) {
        return iJobDao.get(id);
    }

    public int insert(JobModel u) {
        return iJobDao.insert(u);
    }

    public List<JobModel> list() {
        return iJobDao.list();
    }

    public int update(JobModel u) {
        return iJobDao.update(u);
    }

}
9.action类(所有功能)


public class JobAction extends ActionSupport implements ModelDriven<JobModel> {
    private JobModel model = new JobModel();
    

    private Map<String, Object> result = new HashMap<String, Object>(); // result变量用于传送Json变量的返回值  
    private String page;
	private String rows;
	


	public Map<String, Object> getResult() {
		return result;
	}
	public void setResult(Map<String, Object> result) {
		this.result = result;
	}
	public String getPage() {
		return page;
	}
	public void setPage(String page) {
		this.page = page;
	}
	public String getRows() {
		return rows;
	}
	public void setRows(String rows) {
		this.rows = rows;
	}
	public JobModel getModel() {
        return model;
    }

    private JobService jobService;

    public JobService getJobService() {
		return jobService;
	}
	public void setJobService(JobService jobService) {
		this.jobService = jobService;
	}
	public void setModel(JobModel model) {
		this.model = model;
	}
	
	public String list(){
       <span style="white-space:pre">		</span>List<JobModel> dataList = jobService.list() ;
      <span style="white-space:pre">		</span>result.put("total", dataList.size());//total键 存放总记录数,必须的  
      <span style="white-space:pre">		</span>result.put("rows", dataList);//rows键 存放每页记录 list   
        return "plist";
    }
    	
    public String tocreate(){
        
        return "pcreate";
    }
    
    public String toupdate(){
        JobModel u = jobService.get(model.getId());
        ActionContext.getContext().getValueStack().push(u);
        
        return "pupdate";
    }
    
    public String toview(){
    	 JobModel u = jobService.get(model.getId());
        ActionContext.getContext().getValueStack().push(u);
        
        return "pview";
    }
    
    public String createSave(){
    	
        jobService.insert(model);
        return null;
    }
    
    public String updateSave(){
        jobService.update(model);
        
        return "actlist";
    }
    
    public String delete(){
        jobService.deleteById(model.getId());       
        return "actlist";
    }
}

10.easyUi.jsp页面

<%@ page language="java"  pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
 	 <title>easyUi</title>
 	  <!-- 引入JQuery -->	 	
 	<script type="text/javascript" src="${pageContext.request.contextPath}/easyui-1.4.1/jquery.min.js"></script>
		<!-- 引入EasyUI -->
	<script type="text/javascript" src="${pageContext.request.contextPath}/easyui-1.4.1/jquery.easyui.min.js"></script>
 	<!-- 引入EasyUI的中文国际化js,让EasyUI支持中文 -->
 	<script type="text/javascript" src="${pageContext.request.contextPath}/easyui-1.4.1/locale/easyui-lang-zh_CN.js"></script>
 
  	 	<script type="text/javascript" src="${pageContext.request.contextPath}/js/table.js"></script>  	 	
 		 <script type="text/javascript" src="${pageContext.request.contextPath}/js/index.js"></script>  	 	
 		
 	<!-- 引入EasyUI的样式文件-->  
 	<link rel="stylesheet" href="${pageContext.request.contextPath}/easyui-1.4.1/themes/default/easyui.css" type="text/css"/>
 	 <!-- 引入EasyUI的图标样式文件-->
 	<link rel="stylesheet" href="${pageContext.request.contextPath}/easyui-1.4.1/themes/icon.css" type="text/css"/>
 	 <link rel="stylesheet" href="${pageContext.request.contextPath}/easyui-1.4.1/themes/icon.css" type="text/css"/>		
 	
 	</head>
  <body>      
     <table id="dg"></table> 
	  <body>
     <table id="dg" title="添加界面" class="easyui-datagrid"
      data-options="url:'jobAction_list.action',fitColumns:true,singleSelect:true,fit:true, pageList:[2,5,10,20],pageSize:5,
        pagination:true,toolbar:'#toolbar',rownumbers: true,checkbox:true">
	    <thead>
	      <tr>
  			<th data-options="checkbox:true" ></th> 	        
  			<th data-options="field:'id',width:100">编号</th>
	        <th data-options="field:'name',width:100">姓名</th>
	        <th data-options="field:'job_name',width:100">职位</th>
	        <th data-options="field:'salary',width:100">薪资</th>
	        <th data-options="field:'start_date',width:100">时间</th>	        
	      </tr>
	    </thead>
     </table>
     <div id="toolbar">
        <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true" οnclick="addUser()">添加</a>
        <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-no',plain:true" οnclick="delUser()">删除</a>
        <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-print',plain:true" οnclick="updUser()">修改</a>
     </div>
</html>

上面就是所有的代码部分

四:结果展示


                    


五:总结

其实这个界面还有小问题,每行的单选框显示不出来。主要是由于刚接触easyUi,还有很多的问题,以后慢慢解决,就先实现这个显示功能,那张后续还会有这方面的许多文章,慢慢解决

六;注意

其实这篇文章真正重要的部分一个,就是struts将得到的数据转变成json数据,而datagrid接受的json格式还很特殊

action:

<pre name="code" class="java">    private Map<String, Object> result = new HashMap<String, Object>(); // result变量用于传送Json变量的返回值 
</pre><pre code_snippet_id="1814935" snippet_file_name="blog_20160807_13_7151123" name="code" class="java"> public String list(){
<span style="white-space:pre">	</span> List<JobModel> dataList = jobService.list() ;
      <span style="white-space:pre">	</span> result.put("total", dataList.size());//total键 存放总记录数,必须的  
       <span style="white-space:pre">	</span> result.put("rows", dataList);//rows键 存放每页记录 list   
         return "plist";
}

 

struts.xml:

 <package name="jobModel" namespace="/" extends="json-default">
        <action name="jobAction_*" class="com.test.action.JobAction" method="{1}">           
                  <result type="json" name="plist">
<span style="white-space:pre">					</span><param name="root">result</param>>
<span style="white-space:pre">			</span></result>                   
          </action>
 </package>

<result type="json"> 这句说明返回类型为json,所以extends设置为"json-default"。

<param name="root">result</param> responseJson对应返回数据的根


datagrid接受json的格式:

{"total":28,"rows":[
	{"productid":"FI-SW-01","unitcost":10.00,"status":"P","listprice":36.50,"attr1":"Large","itemid":"EST-1"},
	{"productid":"K9-DL-01","unitcost":12.00,"status":"P","listprice":18.50,"attr1":"Spotted Adult Female","itemid":"EST-10"},

],}
必须 又total和rows关键字,这一点要注意

后续我会把分页,以及增删改等功能陆续加上,敬请期待<T-T>

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值