这个小练习是我到公司实习的第三个模块练习(因为太小,无法称之为项目,只是作为熟悉公司框架的小练习)。实现了基于ssh框架的web应用。可以在浏览器上浏览从数据库中取出的全部学生资料并通过easyUI的dataGrid进行前台展示,同时完成简单的增删改操作。
数据库表:
后台实现:
模块名称:demo
这是比较标准的层次结构,主要注意的命名规范有
1、dao层和service层的接口命名要以大写的字母“I”开头,而其实现类要以字母“Impl”。这样在修改以及使用的时候更容易区分。
2、看到每个文件开头的那个耀眼的“Tf”了吗?这个不是那三只“Tf”。至于是什么,无所谓了。记得dao层,model层,vo层的文件中写上它就好,service层和action的文件其实不需要(这只是我们公司的命名规范,其实你写不写,what ever~~)
我们来看action的代码:
//继承RbacBaseAction是公司封装好的框架
public class TfDemoAction extends RbacBaseAction { private static final long serialVersionUID = 1L; /**学生信息业务层操作对象. */ private ITfDemoService tfDemoService; /**将业务层操作对象 set 进我们的action类中*/ public void setTfDemoService(ITfDemoService tfDemoService) { this.tfDemoService = tfDemoService; } /**这个方法一般都是我们发布到服务器上直接访问的actions*/ public String design(){ return "success"; } // 获取全部学生信息列表分页查询 @SuppressWarnings("unchecked") public void getStuPage() throws IOException { String page = this.getRequestParameter("page"); String rows = this.getRequestParameter("rows"); Integer start = null; //从数据库的第几条数据开始 Integer limit = null; //从数据库取多少条数据 try { if (StringUtils.isEmpty(page)) page = "1"; if (StringUtils.isEmpty(rows)) rows = "20"; limit = new Integer(rows).intValue(); start = (new Integer(page).intValue() - 1) * limit; } catch (Exception e) { } //磊哥的习惯,使用map存取数据很方便。。但是取数据是要注意类型转换 Map<String, Object> params = new HashMap<String, Object>(); params.put("start", start); params.put("limit", limit); // 返回到页面的json对象. JSONObject object = new JSONObject(); JSONArray array = new JSONArray(); JSONObject ob = null; Map<String, Object> result = tfDemoService.getStuPage(params); List<TfDemoVO> tfDemoVOList = (List<TfDemoVO>) result.get("rows"); for (int i = 0; i < tfDemoVOList.size(); i++) { TfDemoVO tfDemoVO = tfDemoVOList.get(i); ob = new JSONObject(); ob.put("stuId", tfDemoVO.getStuId());// 学生编号 ob.put("stuName", tfDemoVO.getStuName());// 学生姓名 ob.put("stuSex", tfDemoVO.getStuSex());// 学生性别 ob.put("stuAge", tfDemoVO.getStuAge());// 学生年龄 ob.put("stuRemark", tfDemoVO.getStuRemark());// 备注 array.add(ob); } object.put("total", result.get("total")); object.put("rows", array); this.writeResponse(object); //object是响应回到前台的Json对象 } //添加学生 public void addStu () throws IOException{ String message = "添加成功!"; /**获取添加学生信息的值*/ String stuId = this.getRequestParameter("stuId"); String stuName = this.getRequestParameter("stuName"); String stuSex = this.getRequestParameter("stuSex"); String stuAge = this.getRequestParameter("stuAge"); String stuRemark = this.getRequestParameter("stuRemark"); Map<String, Object> params = new HashMap<String, Object>(); params.put("stuId", stuId); params.put("stuName", stuName); params.put("stuSex", stuSex); params.put("stuAge", stuAge); params.put("stuRemark", stuRemark); TfDemoDO tfDemoDO = (TfDemoDO)this.tfDemoService.findById(params); JSONObject object = new JSONObject(); if( null != tfDemoDO){ message = "学生编号已存在,无法添加学生信息"; object.put("message", message); object.put("success", false); }else{ tfDemoService.addStu(params); object.put("message", message); object.put("success", true); } this.writeResponse(object); } //删除学生 public void delStu() throws IOException{ String message = "删除成功!"; String stuId = this.getRequestParameter("stuId"); Map<String, Object> params = new HashMap<String, Object>(); params.put("stuId", stuId); JSONObject object = new JSONObject(); TfDemoDO tfDemoDO = (TfDemoDO)this.tfDemoService.findById(params); if( null != tfDemoDO){ try { tfDemoService.delStu(stuId); object.put("message", message); object.put("success", true); } catch (ServiceException e) { message = "删除异常,无法删除"; object.put("message", message); object.put("success", false); } }else{ message = "对象不存在,删除失败"; object.put("message", message); object.put("success", false); } this.writeResponse(object); } //修改学生信息 public void updateStu() throws IOException, ServiceException{ String message = "修改成功!"; /**获取添加学生信息的值*/ String stuId = this.getRequestParameter("stuId"); String stuName = this.getRequestParameter("stuName"); String stuSex = this.getRequestParameter("stuSex"); String stuAge = this.getRequestParameter("stuAge"); String stuRemark = this.getRequestParameter("stuRemark"); Map<String, Object> params = new HashMap<String, Object>(); params.put("stuId", stuId); params.put("stuName", stuName); params.put("stuSex", stuSex); params.put("stuAge", stuAge); params.put("stuRemark", stuRemark); /**检查对象是否存在*/ TfDemoDO tfDemoDO = (TfDemoDO)this.tfDemoService.findById(params); JSONObject object = new JSONObject(); if(null != tfDemoDO){ tfDemoService.updateStu(params); object.put("message", message); object.put("success", true); }else{ message = "对象不存在,修改失败!"; object.put("message", message); object.put("success", false); } this.writeResponse(object); }
}
service层代码:
接口:ITfDemoService.java
public interface ITfDemoService { Map<String, Object> getStuPage(Map<String, Object> params); void addStu(Map<String, Object> params); void delStu(String stuId) throws ServiceException; void updateStu(Map<String, Object> params) throws ServiceException; TfDemoDO findById(Map<String, Object> params) ; }
实现类:TfDemoServiceImpl.java
public class TfDemoServiceImpl implements ITfDemoService { /** * Logger logger. */ private static final Logger logger = Logger .getLogger(TfDemoServiceImpl.class); private ITfDemoDao tfDemoDao; public void setTfDemoDao(ITfDemoDao tfDemoDao) { this.tfDemoDao = tfDemoDao; } @SuppressWarnings("unchecked") @Override public Map<String, Object> getStuPage(Map<String, Object> params) { Map<String, Object> map = this.tfDemoDao.getStuList(params); List<Object[]> listArr = (List<Object[]>) map.get("rows"); List<TfDemoVO> voList = new ArrayList<TfDemoVO>(); TfDemoVO tfDemoVO = null; for (Object[] obj : listArr) { tfDemoVO = new TfDemoVO(); tfDemoVO.setStuId((String) obj[0]); tfDemoVO.setStuName((String) obj[1]); BigDecimal temp1=(BigDecimal) obj[2]; //先强转回BigDecimal tfDemoVO.setStuSex(temp1.intValue()); //这里涉及的是Object[] obj 数组我们遍历的是Object类型的数组,那么其元素当然也是Object类型的。 BigDecimal temp2=(BigDecimal) obj[3]; //所以我们想使用BigDecimal的.intValue()方法,必须先将这里的obj[2]这个Object类型的元素强制转换为BigDecimal tfDemoVO.setStuAge(temp2.intValue()); tfDemoVO.setStuRemark((String) obj[4]); voList.add(tfDemoVO); } Map<String, Object> result = new HashMap<String, Object>(); result.put("rows", voList); result.put("total", map.get("total")); return result; } //添加学生信息的方法 @Override public void addStu(Map<String, Object> params) { TfDemoDO tfDemoDO = new TfDemoDO(); tfDemoDO.setStuId((String)params.get("stuId")); tfDemoDO.setStuName((String)params.get("stuName")); tfDemoDO.setStuSex(Integer.parseInt((String)params.get("stuSex"))); tfDemoDO.setStuAge(Integer.parseInt((String)params.get("stuAge"))); tfDemoDO.setStuRemark((String)params.get("stuRemark")); //这里的update也是dao层继承的封装好的方法
this.tfDemoDao.save(tfDemoDO); } //删除学生信息的方法 @Override public void delStu(String stuId) throws ServiceException { if (null != stuId && !"".equals(stuId)) { TfDemoDO tfDemoDO = (TfDemoDO) this.tfDemoDao.findById(stuId); if (null != tfDemoDO) { try {
//这里的update也是dao层继承的封装好的方法
this.tfDemoDao.deleteById(stuId); } catch (Exception e) { logger.error(e); throw new ServiceException("删除失败."); } } } } //更新学生信息的方法 @Override public void updateStu(Map<String, Object> params) throws ServiceException { try{ TfDemoDO tfDemoDO = (TfDemoDO) this.tfDemoDao.findById((String)params.get("stuId")); if(null != tfDemoDO){ tfDemoDO.setStuId((String)params.get("stuId")); tfDemoDO.setStuName((String)params.get("stuName")); tfDemoDO.setStuSex(Integer.parseInt((String)params.get("stuSex"))); tfDemoDO.setStuAge(Integer.parseInt((String)params.get("stuAge"))); tfDemoDO.setStuRemark((String)params.get("stuRemark")); //这里的update也是dao层继承的封装好的方法 this.tfDemoDao.update(tfDemoDO); }else{ throw new ServiceException("数据异常,未发现原始记录!"); } }catch(Exception e){ logger.error(e); throw new ServiceException("更新客户信息失败!"); } } //通过id值查找其对象的方法此方法并不是我们自己在dao层写的,而是继承自公司封装好的框架~~,如果没有的话,当然也可以自己写一个
//当初我第一次在公司的框架上做这种功能,我在dao里写了一大堆我想用的方法,最后被猛哥骂的狗血喷头。我们好多的方法都已经封装好了,只需要会
//继承,调用就ok。继承的时候要注意,dao的接口继承的是Dao,dao的实现类,继承的是RbacBaseDao。。。(我们公司是这样,别被我误导了s)
@Override public TfDemoDO findById(Map<String, Object> params) { TfDemoDO tfDemoDO = (TfDemoDO)this.tfDemoDao.findById((String)params.get("stuId")); return tfDemoDO; } }
dao层代码:
dao的接口:ITfDemoDao
public interface ITfDemoDao extends Dao{ Map<String, Object> getStuList(Map<String, Object> params); //你没看错,我真的就用这一个自己写的方法,其他的都是用的继承来的方法 }
dao的实现类:TfDemoDaoImpl
public class TfDemoDaoImpl extends RbacBaseDao implements ITfDemoDao { @SuppressWarnings("unused") private static final Logger logger = Logger.getLogger(TfDemoDaoImpl.class); /** * 初始化. * */ public TfDemoDaoImpl() { super(); this.className = TfDemoDO.class.getName(); } @Override public Map<String, Object> getStuList(Map<String, Object> params) { System.out.println("进入Dao"); Integer start = (Integer) params.get("start"); Integer limit = (Integer) params.get("limit"); StringBuffer sql = new StringBuffer(); //这里写的是sql语句,并没有用hql,因为比较简单注意追加以及插入的语法就好了,语句最好一点一点追加
sql.append(" from tf_demo t"); //边判断边追加,最后拼装出想要的sql语句 Query queryC = this.getSession().createSQLQuery( "select count(*) " + sql.toString()); StringBuffer sqlHead = new StringBuffer(); sqlHead.append("select *"); sql.insert(0, sqlHead.toString()); Query query = this.getSession().createSQLQuery(sql.toString()); query.setFirstResult(start); query.setMaxResults(limit); Map<String, Object> result = new HashMap<String, Object>(); result.put("rows", query.list()); result.put("total", queryC.uniqueResult()); return result; } }
后台全部的代码就是以上这些。。下面我们来看一下ssh的配置文件
首先是文件的放置:
hibernate映射文件:TfDemo.hbm.xml
<hibernate-mapping> <class name="com.unistec.demo.model.TfDemoDO" table="TF_DEMO"> <id name="stuId" type="java.lang.String"> <column name="id" length="50"/> <generator class="assigned" /> </id> <property name="stuName" type="java.lang.String"> <column name="stu_name" length="50"> <comment>学生姓名</comment> </column> </property> <property name="stuSex" type="java.lang.Integer"> <column name="stu_sex"> <comment>学生性别</comment> </column> </property> <property name="stuAge" type="java.lang.Integer"> <column name="stu_age"> <comment>学生年龄</comment> </column> </property> <property name="stuRemark" type="java.lang.String"> <column name="stu_remark" length="1000"> <comment>备注</comment> </column> </property> </class> </hibernate-mapping>
Spring-action配置文件:applicationContext-action.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans default-autowire="byName" default-lazy-init="true"> <bean name="tfDemoAction" class="com.unistec.demo.web.TfDemoAction"> </bean> </beans>
Spring-service配置文件:applicationContext-service.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans default-autowire="byName" default-lazy-init="true"> <bean id="tfDemoService" class="com.unistec.demo.service.impl.TfDemoServiceImpl"></bean> </beans>
Spring-dao配置文件:applicationContext-dao.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans default-autowire="byName" default-lazy-init="true"> <bean name="tfDemoDao" class="com.unistec.demo.dao.impl.TfDemoDaoImpl"></bean> </beans>
Struts配置文件: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> <package name="TfDemoActionStr" extends="struts-default-eai" namespace="/demo"> <action name="design" class="tfDemoAction" method="design"> <result name="success">/act/easyUI/easyUI.jsp</result> </action> <action name="getStuPage" class="tfDemoAction" method="getStuPage"> </action> <action name="addStu" class="tfDemoAction" method="addStu"> </action> <action name="delStu" class="tfDemoAction" method="delStu"> </action> <action name="updateStu" class="tfDemoAction" method="updateStu"> </action> </package> </struts>