SSH项目实战二:SSH+EASYUI完美实现CRUD

本文通过实例详细讲解如何使用SSH框架结合EasyUI完成CRUD操作,包括配置文件、模型、DAO、Service、Controller及前端页面的实现,旨在帮助读者理解SSH+EasyUI的集成应用。
摘要由CSDN通过智能技术生成

每次遇到写文章内容比较多的博文都感觉比较麻烦,但是以前也是看着前辈们的博客过来的,所以我也开始分析一下我的博文了,话不多说,就来实现一下SSH+EasyUi完成CRUD

首先我们看一下后台实现的基本效果

那么我就直接上代码吧,这样比较直接,遇到容易出问题的地方就简单说一下

首先是配置文件

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">

	<context-param>
	   <param-name>contextConfigLocation</param-name>
	   <param-value>/WEB-INF/classes/beans.xml</param-value>
	</context-param>
	<listener>
	      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<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>
	
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

bean.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-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	<context:component-scan base-package="com.schoolaround.*"/>
	
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
		<property name="driverClass" value="com.mysql.jdbc.Driver"/>
		
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/schoolaround?useUnicode=true&characterEncoding=UTF-8"/>
		<property name="user" value="root"/>
		<property name="password" value="root"/>
		
		<property name="initialPoolSize" value="3"/>
		<property name="minPoolSize" value="5"/>
		<property name="maxPoolSize" value="20"/>
		<property name="maxIdleTime" value="120"/>
		<property name="acquireIncrement" value="2"/>
		<property name="idleConnectionTestPeriod" value="60"/>
	</bean>
	
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		 <property name="mappingResources">
			    <list>
			     <value>com/schoolaround/pojo/Shop.hbm.xml</value>
			    </list>
		</property>
		 <property name="hibernateProperties">
			 <value>
			      hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
			      hibernate.hbm2ddl.auto=update
			      hibernate.show_sql=true
			      hibernate.format_sql=false
			  </value>
		 </property>
	</bean>
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	
	<tx:annotation-driven transaction-manager="txManager"/>
	
	
</beans>
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.devMode" value="true" />
    
    <constant name="struts.multipart.maxSize" value="2147483648"/>
    
    <constant name="struts.objectFactory" value="spring" />
    
    <package name="shop" namespace="/" extends="struts-default,json-default">
    	
    	<action name="shop" class="com.schoolaround.action.ShopControlAction" method="shop">
    		<result>/admin/shopcontrol.jsp</result>
    	</action>
    	
    	<action name="save" class="com.schoolaround.action.ShopControlAction" method="save">
    		<result type="redirect">/admin/shopcontrol.jsp</result>
    	</action>
    	
    	<action name="list" class="com.schoolaround.action.ShopControlAction" method="list">
    		<result type="json"><param name="root">jsonResult</param></result>
    	</action>
    	<action name="delete" class="com.schoolaround.action.ShopControlAction" method="delete">
    		<result type="redirect">/admin/shopcontrol.jsp</result>
    	</action>
    	<action name="update" class="com.schoolaround.action.ShopControlAction" method="update">
    		<result>/admin/shopcontrol.jsp</result>
    	</action>
    	
    </package> 
   
    
   
</struts>
POJO文件

Shop.java

package com.schoolaround.pojo;

public class Shop {
	
	private int shopid;
	
	private String shopname;
	
	private String shoplocation;
	
	private int shopcid;
	
	private String goodsidlist;
	
	private String shopimage;

	public int getShopid() {
		return shopid;
	}

	public void setShopid(int shopid) {
		this.shopid = shopid;
	}

	public String getShopname() {
		return shopname;
	}

	public void setShopname(String shopname) {
		this.shopname = shopname;
	}

	public String getShoplocation() {
		return shoplocation;
	}

	public void setShoplocation(String shoplocation) {
		this.shoplocation = shoplocation;
	}

	public int getShopcid() {
		return shopcid;
	}

	public void setShopcid(int shopcid) {
		this.shopcid = shopcid;
	}

	public String getGoodsidlist() {
		return goodsidlist;
	}

	public void setGoodsidlist(String goodsidlist) {
		this.goodsidlist = goodsidlist;
	}

	public String getShopimage() {
		return shopimage;
	}

	public void setShopimage(String shopimage) {
		this.shopimage = shopimage;
	}
	

}


Shop.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.schoolaround.pojo">
	<class name="Shop" table="shop">
		<id name="shopid" type="int">
		    <column name="shopid"/>
			<generator class="increment" />
		</id>

		<property name="shopname" length="10"></property>
		<property name="shoplocation" length="10"></property>
		<property name="shopcid" length="10"></property>
		<property name="goodsidlist" length="10"></property>
		<property name="shopimage" length="10"></property>
	</class>
</hibernate-mapping>

dao层:

dao接口:ShopDao.java

package com.schoolaround.dao;

import java.util.List;
import com.schoolaround.pojo.Shop;

public interface ShopDao {
	
	public void add(Shop shop);
	
	public void deleteShop(int id);
	
	public Shop findShopById(int id);
	
	public List<Shop> findAllShop();
	
	public void updateShop(Shop shop);
	
	public List getShopList(String page, String rows);
	
	public int getShopTotal() throws Exception;

}

dao实现:ShopDaoImpl.java

package com.schoolaround.dao.impl;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.schoolaround.dao.ShopDao;
import com.schoolaround.pojo.Shop;

@Service(value="shopDao")
@Transactional
public class ShopDaoImpl implements ShopDao{
	
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
    public void add(Shop shop){
    	this.sessionFactory.getCurrentSession().save(shop);
    }
	
	public void deleteShop(int shopid){
		Shop shop = findShopById(shopid);
		if(shop!=null){
		this.sessionFactory.getCurrentSession().delete(shop);
		}
	}
	
	public Shop findShopById(int shopid){
		return (Shop)sessionFactory.getCurrentSession().get(Shop.class,shopid);	
	}
	
	public List<Shop> findAllShop(){
		return sessionFactory.getCurrentSession().createQuery("from Shop group by shopid").list();	
	}
	
	public void updateShop(Shop shop){
		sessionFactory.getCurrentSession().update(shop);
	}
	
    // 根据第几页获取,每页几行获取数据  
	
    public List getShopList(String page, String rows) {  
          
        //当为缺省值的时候进行赋值  
        int currentpage = Integer.parseInt((page == null || page == "0") ? "1": page);//第几页  
        int pagesize = Integer.parseInt((rows == null || rows == "0") ? "10": rows);//每页多少行  
          
        List list = this.sessionFactory.getCurrentSession().createQuery("from Shop group by shopid")  
                       .setFirstResult((currentpage - 1) * pagesize).setMaxResults(pagesize).list();  
  
        return list;  
    }  
  
    // 统计一共有多少数据  
    public int getShopTotal() throws Exception {  
        return this.sessionFactory.getCurrentSession().find("from Shop").size();  
    }  
	

}

Service层(由于写得比较匆忙所以dao和service层写得不是很规范,建议读者可以在此基础上再抽象一层,方便完成其它实体的操作,以减少代码冗余)

Service接口:

ShopService.java

package com.schoolaround.service;

import java.util.List;

import com.schoolaround.pojo.Shop;

public interface ShopService {
	public void saveShop(Shop shop);
	public List<Shop> shopList();
	public void deleteShop(int shopid);
	public void editShop(Shop shop);
	public List getShopList(String page, String rows);
	public int getShopTotal() throws Exception;
}
Service接口实现

ShopServiceImpl.java

package com.schoolaround.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;

import com.schoolaround.dao.ShopDao;
import com.schoolaround.pojo.Shop;
import com.schoolaround.service.ShopService;

@Service(value="shopService")
public class ShopServiceImpl implements ShopService{
	
	private ShopDao shopDao;

	public ShopDao getShopDao() {
		return shopDao;
	}

	@Resource
	public void setShopDao(ShopDao shopDao) {
		this.shopDao = shopDao;
	}

	public void saveShop(Shop shop){
		this.shopDao.add(shop);
	}
	
	public List<Shop> shopList(){
		return this.shopDao.findAllShop();
	}
	
	public void deleteShop(int shopid){
		this.shopDao.deleteShop(shopid);
	}
	
	public void editShop(Shop shop){
		this.shopDao.updateShop(shop);
	}
	 public List getShopList(String page, String rows) {  
         
	        return this.shopDao.getShopList(page, rows);
	    }  
	  
	    // 统计一共有多少数据  
	    public int getShopTotal() throws Exception{  
	        return this.shopDao.getShopTotal();
	    }  

}

好了,终于到最后一层Action了

ShopControlAction.java

package com.schoolaround.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.schoolaround.tools.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.json.annotations.JSON;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.schoolaround.dao.ShopDao;
import com.schoolaround.pojo.Shop;
import com.schoolaround.service.ShopService;

@Controller
@Scope(value = "prototype")
public class ShopControlAction extends ActionSupport{
	private int shopid;
	private String shopname;
	private String shoplocation;
        private int shopcid;
	private String goodsidlist;
	private String shopimage;
	private ShopService shopService;
	private List<Shop> shopList;
	private Map<String,Object> dataMap = new HashMap<String, Object>();
	private String result = null;
	private String rows;
	private String page;
	private ShopDao shopDao;
	
	public int getShopid() {
		return shopid;
	}

	public void setShopid(int shopid) {
		this.shopid = shopid;
	}

	public ShopService getShopService() {
		return shopService;
	}
	
	@Resource
	public void setShopService(ShopService shopService) {
		this.shopService = shopService;
	}

	public ShopDao getShopDao() {
		return shopDao;
	}

	@Resource
	public void setShopDao(ShopDao shopDao) {
		this.shopDao = shopDao;
	}

	public String getShopname() {
		return shopname;
	}

	public void setShopname(String shopname) {
		this.shopname = shopname;
	}

	public String getShoplocation() {
		return shoplocation;
	}

	public void setShoplocation(String shoplocation) {
		this.shoplocation = shoplocation;
	}

	public int getShopcid() {
		return shopcid;
	}

	public void setShopcid(int shopcid) {
		this.shopcid = shopcid;
	}

	public String getGoodsidlist() {
		return goodsidlist;
	}

	public void setGoodsidlist(String goodsidlist) {
		this.goodsidlist = goodsidlist;
	}

	public String getShopimage() {
		return shopimage;
	}

	public void setShopimage(String shopimage) {
		this.shopimage = shopimage;
	}

	@JSON(serialize = false)
	public List<Shop> getShopList() {
		return shopList;
	}

	@JSON(serialize = false)
	public void setShopList(List<Shop> shopList) {
		this.shopList = shopList;
	}

	public String getRows() {
		return rows;
	}

	public void setRows(String rows) {
		this.rows = rows;
	}

	public String getPage() {
		return page;
	}

	public void setPage(String page) {
		this.page = page;
	}
	
	public String shop() throws Exception{
		return SUCCESS;
	}

       //shop的列表显示
	public String list() throws Exception{
		List shop = shopDao.getShopList(page, rows);
		StringUtil.toBeJson(shop, shopDao.getShopTotal());
		return null;
	}

        //保存shop数据
	public String save() throws Exception{
		Shop shop = new Shop();
		shop.setShopid(1);
		shop.setShopname(shopname);
		shop.setShoplocation(shoplocation);
		shop.setGoodsidlist(goodsidlist);
		shop.setShopcid(shopcid);
		shop.setShopimage(shopimage);
		try{
		this.shopService.saveShop(shop);
		result="{\"success\":true}";
		StringUtil.writeToWeb(result, "html", ServletActionContext.getResponse());
		}catch(Exception e){
			//dataMap.put("msg", "保存失败");
			result="{\"msg\":\"保存失败\"}";
			StringUtil.writeToWeb(result, "html", ServletActionContext.getResponse());
		}
		return SUCCESS;
	}

        //根据id删除shop数据
	public String delete() throws Exception{
		
		try{
		this.shopService.deleteShop(shopid);
		dataMap.put("success", true);
		}catch(Exception e){
			dataMap.put("errorMsg", "删除错误");
		}
		JSONUtils.toJson(ServletActionContext.getResponse(), dataMap);
		return SUCCESS;
	}
	
       //根据id修该shop数据
	public String update() throws Exception{
		Shop shop = new Shop();
		shop.setShopid(shopid);
		shop.setShopname(shopname);
		shop.setShoplocation(shoplocation);
		shop.setGoodsidlist(goodsidlist);
		shop.setShopcid(shopcid);
		shop.setShopimage(shopimage);
		try{
		this.shopService.editShop(shop);
		result="{\"success\":true}";
		StringUtil.writeToWeb(result, "html", ServletActionContext.getResponse());
		}catch(Exception e){
			result="{\"msg\":\"保存失败\"}";
			StringUtil.writeToWeb(result, "html", ServletActionContext.getResponse());
		}
		return SUCCESS;
	}
	
	public String execute() throws Exception{
		return SUCCESS;
	}

}
工具类 
我这里收集了两个工具类,所以读者根据自己需求进行选择

StringUtil.java

package com.schoolaround.tools;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

public class StringUtil {
	
	/**
	 * 本方法封装了往前台设置的header,contentType等信息
	 * @param message       需要传给前台的数据
	 * @param type          指定传给前台的数据格式,如"html","json"等
	 * @param response      HttpServletResponse对象
	 * @throws IOException
	 */
	public static void writeToWeb(String message, String type, HttpServletResponse response) throws IOException{
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/" + type +"; charset=utf-8");
		response.getWriter().write(message);
		response.getWriter().close();
		
	}
	
	/**
	 * 本方法用于分页页面数据json处理
	 * @param list
	 * @param total
	 * @throws Exception
	 */
	public static void toBeJson(List list, int total) throws Exception{
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		
		JSONObject jobj = new JSONObject();
		jobj.accumulate("total", total);
		jobj.accumulate("rows", list);
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(jobj.toString());
		//log.info(jobj.toString());
	}

}

JSONUtils.java

package com.schoolaround.tools;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class JSONUtils {
    public static void toJson(HttpServletResponse response, Object data) 
        throws IOException {
        Gson gson = new Gson();
        String result = gson.toJson(data);
        response.setContentType("text/json; charset=utf-8");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        out.print(result);
        out.flush();
        out.close();
    }
}

好了我们回到前台页面显示吧(前台页面使用的是easyui,所以这里相关的js就自己到官方下载并引入,也可以直接使用它的cdn地址,这里

我是用主页面点击链接引入该页面的,这个就不多说

/admin/shopcontrol.jsp

<%@ page language="java" pageEncoding="utf-8"%>
  <script>
  var url;
   function newShop(){
	    $('#dlg_shop').dialog('open').dialog('setTitle','添加商家');
	    $('#fm_shop').form('clear');
	    url = 'save.action';
	    }
   function editShop(){
	    var row = $('#dg').datagrid('getSelected');
	    if (row){
	    $('#dlg_shop').dialog('open').dialog('setTitle','信息编辑');
	    $('#fm_shop').form('load',row);
	    url = 'update.action?shopid='+row.shopid;
	    }
  }
   function saveShop(){
		$('#fm_shop').form('submit',{
			url: url,
			onSubmit: function(){
				return $(this).form('validate');
			},
			success: function(result){
				var result = eval('('+result+')');
				if (result.success){
					$('#dlg_shop').dialog('close');		// close the dialog
					$('#dg').datagrid('reload');	// reload the user data
				} else {
					$.messager.show({
						title: 'Error',
						msg: result.msg
					});
				}
			}
		});
	}
   function destroyShop(){
	    var row = $('#dg').datagrid('getSelected');
	    if (row){
	    $.messager.confirm('温馨提示','是否删除此行数据?',function(r){
	    if (r){
	    $.post('delete.action',{shopid:row.shopid},function(result){
	    if (result.success){
	    $('#dg').datagrid('reload');	// reload the user data
	    } else {
	    $.messager.show({	// show error message
	    title: 'Error',
	    msg: result.errorMsg
	    });
	    }
	    },'json');
	    }
	    });
	    }
	    }

	/*function saveUser(){
		var shopname = $("#shopname").val();
		//alert(shopname);
		var shoplocation = $("$shoplocation").val();
		$('#fm_shop').submit();
	}*/
   </script>
    <table id="dg" title="商家管理" class="easyui-datagrid" style="width:950px;height:400px"
   data-options="toolbar:'#toolbar_shop',pagination:true,singleSelect:true,collapsible:true,url:'list.action',pageSize:10,pageList:[ 5, 10, 15, 20 ]">
    <thead>
    <tr>
   <th data-options="field:'shopid',width:200">ShopId</th>
<th data-options="field:'shopname',width:200">ShopName</th>
<th data-options="field:'shoplocation',width:200">ShopLocation</th>
<th data-options="field:'shopcid',width:200">ShopCId</th>
    </tr>
    </thead>
    </table>
    <div id="toolbar_shop">
    <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" οnclick="newShop()">添加商家</a>
    <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" οnclick="editShop()">信息编辑</a>
    <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" οnclick="destroyShop()">删除商家</a>
    </div>
        <div id="dlg_shop" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px"
    closed="true" buttons="#dlg_shop-buttons">
    <div class="ftitle">User Information</div>
    <form id="fm_shop" method="post" novalidate>
    <div class="fitem">
    <label>Shop Name:</label>
    <input name="shopname" id="shopname" class="easyui-validatebox" required="true">
    </div>
    <div class="fitem">
    <label>Shop Location:</label>
    <input name="shoplocation" id="shoplocation" class="easyui-validatebox" required="true">
    </div>
    <div class="fitem">
    <label>Shop CId:</label>
    <input name="shopcid" class="easyui-validatebox" required="true">
    </div>
    <div class="fitem">
    <label>Goodslist:</label>
    <input name="goodsidlist" class="easyui-validatebox" required="true">
    </div>
    <div class="fitem">
    <label>Shop Image:</label>
    <input name="shopimage" class="easyui-validatebox" required="true">
    </div>
    </form>
    </div>
    <div id="dlg_shop-buttons">
    <a href="#" class="easyui-linkbutton" iconCls="icon-ok" οnclick="saveShop()">Save</a>
    <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" οnclick="javascript:$('#dlg_shop').dialog('close')">Cancel</a>
    </div>

好了,整合就完成了,整体来讲的确比较罗嗦,但希望能够对读者有用,个人觉得写得有些欠缺,哦,还有查找部分没写,下次有时间补上


虽然代码拙劣,但是却付出了心血,如果有转载的童鞋,请附上转载信息

作者:Hunter_first
出处:http://blog.csdn.net/lsx991947534/article
作品由Hunter_first创作。 欢迎转载,但任何转载必须保留完整文章,在显要地方显示署名以及原文链接。如您有任何疑问,请给我留言




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值