总结1
来源:互联网 发布:数组转为字符串 编辑:程序博客网 时间:2024/05/29 05:12
Action层处理:
1、首先为了公用,得先创建一个公共的处理方法,所以得先创建一个BaseAction,其余的Action都继承与次BaseAction:
import java.io.IOException; import org.apache.log4j.Logger; import org.apache.struts2.ServletActionContext; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import com.alibaba.fastjson.JSON; //引入转换工具 @ParentPackage("basePackage") @Namespace("/") public class BaseAction { private static final Logger logger = Logger.getLogger(BaseAction.class); /** * 将对象转换成JSON字符串,并响应回前台 * * @param object * @throws IOException */ public void writeJson(Object object) { try { String json = JSON.toJSONStringWithDateFormat(object, "yyyy-MM-dd HH:mm:ss"); //转换处理 ServletActionContext.getResponse().setContentType("text/html;charset=utf-8"); //往页面传输 ServletActionContext.getResponse().getWriter().write(json); ServletActionContext.getResponse().getWriter().flush(); ServletActionContext.getResponse().getWriter().close(); } catch (IOException e) { e.printStackTrace(); } } }
2、具体、普通的action类
import org.apache.struts2.ServletActionContext; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.Result; import org.springframework.beans.factory.annotation.Autowired; import com.biop.platform.action.base.BaseAction; import com.biop.platform.pageModel.Json; import com.biop.platform.pageModel.Stores; import com.biop.platform.service.StoresServiceI; import com.opensymphony.xwork2.ModelDriven; @Namespace("/") @Action(value = "storesAction", results = {@Result(name = "userEdit", location = "/admin/userEdit.jsp")}) @SuppressWarnings("all") public class StoresAction extends BaseAction implements ModelDriven<Stores> { private Stores stores = new Stores(); //pageModel对象 @Override public Stores getModel() { return stores; } @Autowired private StoresServiceI storesService; //service 引用,注解 //查询方法 public void datagrid() { writeJson(storesService.datagrid(stores)); } //添加方法 public void add(){ storesService.add(stores); Json j = new Json(); j.setSuccess(true); j.setMsg("门店添加成功"); writeJson(j); } //编辑方法 public void edit() { storesService.edit(stores); Json j = new Json(); j.setSuccess(true); j.setMsg("门店修改成功"); writeJson(j); } //删除方法 public void delete() { storesService.delete(stores); Json j = new Json(); j.setSuccess(true); j.setMsg("门店删除成功"); writeJson(j); } //easyui有个combox控件,他通过这个方法来加载数据 public void combobox() { writeJson(storesService.combobox(stores)); } }
#########################################################################################################################################################################################################################
Service层处理:
//action类调用service的入口方法,action通过调用这个方法来获取页面要显示的数据集合,在action中
//通过fastjson工具将这个方法返回的数据集合转换成json数据,然后写入到页面中去。具体参考--------------------------
public DataGrid datagrid(Stores stores)
{
DataGrid dg = new DataGrid(); //创建一个easyui的datagrid数据格式的对象,用于封装datagrid显示需要的数据
dg.setRows(this.changeModel(this.find(stores))); //将数据库中查到的数据set到datagrid中 ,find是查数据,changeModel是将数据库映射model转换为pageModel,利于显示。
dg.setTotal(this.total(stores)); //设置数据总条数,用于分页
return dg;
}
//根据pagemodel对象的条件查询数据
public List<TStores> find(Stores stores)
{
SessionInfo sessionInfo = SessionInfo)ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName()); //权限控制,获取当前登录账户的信息和id号
String merchant_id = sessionInfo.getMerchant_id();
String hql = " from TStores ts where 1=1 and ts.tmerChant.id = '" + merchant_id + "' "; //根据当前登陆账号的id组织sql语句。
List<Object> values = new ArrayList<Object>(); //创建一个用于存储查询条件的数据集合对象 ,引用传递,where方法里面改变了,此处同样改变
hql = addWhere(stores, hql, values); //添加where条件
if (stores.getSort() != null && stores.getOrder() != null)
{
hql += " order by ts." + stores.getSort() + " " + stores.getOrder(); //根据什么、按什么顺序进行排序
}
return storesDao.find(hql, values, stores.getPage(), stores.getRows()); //调用dao层,进行分页查询
}
//添加where查询条件的方法
private String addWhere(Stores stores, String hql, List<Object> values)
{
if (stores.getName() != null && !stores.getName().trim().equals(""))
{
hql += " and ts.name like ? ";
values.add("%" + stores.getName().trim() + "%");
}
if (stores.getCreatedatetimeStart() != null)
{
hql += " and createdatetime >= ?";
values.add(stores.getCreatedatetimeStart());
}
if (stores.getCreatedatetimeEnd() != null)
{
hql += " and createdatetime <= ?";
values.add(stores.getCreatedatetimeEnd());
}
if (stores.getModifydatetimeStart() != null)
{
hql += " and modifydatetime >= ?";
values.add(stores.getModifydatetimeStart());
}
if (stores.getModifydatetimeEnd() != null)
{
hql += " and modifydatetime <= ?";
values.add(stores.getModifydatetimeEnd());
}
return hql;
}
//find方法查询出来的数据集合里是放的与数据库映射的model,而传到前端展示的是pageModel,虽然说这两个model基本相同,但是还是有些差别,比如页面状态展示不能用数据库中保存的0、1等数字展示,所以要将两个model进行
//转换,并且在pagemodel中做一些处理和调整。
private List<Stores> changeModel(List<TStores> tstores)
{
List<Stores> list = new ArrayList<Stores>();
if (tstores != null && tstores.size() > 0)
{
for (TStores tstore : tstores)
{
Stores stores = new Stores();
BeanUtils.copyProperties(tstore, stores); //将原对象tstore的属性复制到目的对象stores中去,
stores.setUserid(tstore.getCreatorUser().getId()); //调整pagemodel
stores.setMerchant_id(tstore.getTmerChant().getId()); // 设置商户ID到pageModel
list.add(stores);
}
}
return list;
}
//计算查询数据的总条数,条件与find方法一样。
private Long total(Stores stores)
{
SessionInfo sessionInfo = (SessionInfo)ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
String creator_id = sessionInfo.getUserId();
String hql = "select count(*) from TStores ts where 1=1 and ts.creatorUser.id='" + creator_id + "' ";
List<Object> values = new ArrayList<Object>();
hql = addWhere(stores, hql, values);
return storesDao.count(hql, values);
}
#########################################################################################################################################################################################################################
Dao层处理:
package com.biop.platform.dao;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
//基础数据库操作类的接口
public interface BaseDaoI<T> {
//保存一个对象
public Serializable save(T o);
//删除一个对象
public void delete(T o);
//更新一个对象
public void update(T o);
//保存或更新对象
public void saveOrUpdate(T o);
public List<T> find(String hql);
public List<T> find(String hql, Object[] param);
//根据sql语句查询
public List<T> findBySql(String sql);
public List<T> find(String hql, List<Object> param);
//查询集合(带分页)
public List<T> find(String hql, Object[] param, Integer page, Integer rows);
//根据当前ID便利查询,其旗下所有子数据
public List<T> sqlMapFind(String hql, List<Object> param, Integer page,Integer rows,String entityName,Class className);
//查询集合(带分页)
public List<T> find(String hql, List<Object> param, Integer page,Integer rows);
//获得一个对象
public T get(Class<T> c, Serializable id);
//获得一个对象
public T get(String hql, Object[] param);
//获得一个对象
public T get(String hql, List<Object> param);
// select count(*) from 类
public Long count(String hql);
// 根据SQL 递归
public Long countSql(String hql, List<Object> param);
//select count(*) from 类
public Long count(String hql, Object[] param);
//select count(*) from 类
public Long count(String hql, List<Object> param);
//执行HQL语句
public Integer executeHql(String hql);
//执行HQL语句
public Integer executeHql(String hql, Object[] param);
//执行HQL语句
public Integer executeHql(String hql, List<Object> param);
public T getObject(String hql,Map<String, Object> params);
public List<T> find(String hql,Map<String, Object> params);
public List<T> find(String hql,Map<String, Object> params,int page,int rows);
public List<T> find(String hql,int page,int rows);
public Long count(String hql,Map<String, Object> params);
/**
* 根据原生sql语句执行增加,删除,修改操作
* @param sql
* : 原生sql语句
* @return : 受影响的行数
*/
public int executeBySql(String sql) throws Exception;
/**
* 根据sequence,查询出下一个用来插入的id
* @Title: findSequenceNextVal
*/
public BigDecimal findSequenceNextVal(String sequence);
public List excuteQuerySql(String sql);
public void myupdate(T o);
public void mydelete(T o);
public void mysaveOrUpdate(T o);
}
//具体正对某个功能的dao接口
package com.biop.platform.dao;
import com.biop.platform.model.TStores;
public interface StoresDaoI extends BaseDaoI<TStores> //继承公共的basedao接口
{
}
//具体正对某个功能的dao实现类
package com.biop.platform.dao.impl;
import org.springframework.stereotype.Repository;
import com.biop.platform.dao.StoresDaoI;
import com.biop.platform.model.TStores;
@Repository("storesDao")
public class StoresDaoImpl extends BaseDaoImpl<TStores> implements StoresDaoI //继承公共的dao实现类,和继承自己的dao接口 ;继承过来的方法也可以当作实现, BaseDaoI的实现类参考附录3
{
}
#########################################################################################################################################################################################################################
附录:
1、DataGrid.java类,easyUI的datagrid显示的数据集需要,total:用于分页; rows:显示每一行的数据集合,所有service层需要
将从数据库中查到数据进行封装成datagrid对象,然后通过fastjson工具将这个对象转换成json格式字符串
import java.util.ArrayList;
import java.util.List;
public class DataGrid {
private Long total=0L; //用于分页
private List rows=new ArrayList(); //显示每一行的数据集合
private List footer = new ArrayList(); //统计数据显示栏目
public Long getTotal() {
return total;
}
public void setTotal(Long total) {
this.total = total;
}
public List getRows() {
return rows;
}
public void setRows(List rows) {
this.rows = rows;
}
public List getFooter()
{
return footer;
}
public void setFooter(List footer)
{
this.footer = footer;
}
}
-------------------------------------------------------------------------------------------------------------------------
2、Json对象,该对象,主要用于网页面传输一些消息提示。比如添加成功等等提示信息
import java.io.Serializable;
public class Json implements Serializable{
private boolean success=false;
private String msg="";
private Object obj = null;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
}
3、BaseDaoI的实现类
package com.biop.platform.dao.impl;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.biop.platform.dao.BaseDaoI;
@SuppressWarnings("all")
@Repository("baseDao")
public class BaseDaoImpl<T> implements BaseDaoI<T>
{
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory()
{
return sessionFactory;
}
@Autowired
public void setSessionFactory(SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
private Session getCurrentSession()
{
return sessionFactory.getCurrentSession();
}
public Serializable save(T o)
{
return this.getCurrentSession().save(o);
}
public void delete(T o)
{
this.getCurrentSession().delete(o);
}
public void update(T o)
{
this.getCurrentSession().update(o);
}
public void saveOrUpdate(T o)
{
this.getCurrentSession().saveOrUpdate(o);
}
public List<T> find(String hql)
{
return this.getCurrentSession().createQuery(hql).list();
}
public List<T> find(String hql, Object[] param)
{
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.length > 0)
{
for (int i = 0; i < param.length; i++)
{
q.setParameter(i, param[i]);
}
}
return q.list();
}
public List<T> find(String hql, List<Object> param)
{
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.size() > 0)
{
for (int i = 0; i < param.size(); i++)
{
q.setParameter(i, param.get(i));
}
}
return q.list();
}
public List<T> find(String hql, Object[] param, Integer page, Integer rows)
{
if (page == null || page < 1)
{
page = 1;
}
if (rows == null || rows < 1)
{
rows = 10;
}
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.length > 0)
{
for (int i = 0; i < param.length; i++)
{
q.setParameter(i, param[i]);
}
}
return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
}
public List<T> find(String hql, List<Object> param, Integer page, Integer rows)
{
if (page == null || page < 1)
{
page = 1;
}
if (rows == null || rows < 1)
{
rows = 10;
}
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.size() > 0)
{
for (int i = 0; i < param.size(); i++)
{
q.setParameter(i, param.get(i));
}
}
return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
}
/**
* @Title: recFind
* @Description: 根据sql来进行hibernate映射查询
* @param hql
* @param param
* @param page
* @param rows
* @return
* @return List<T>
* @author weizhiqiang
* @Date 2013-6-4 下午6:51:35
*/
public List<T> sqlMapFind(String hql, List<Object> param, Integer page, Integer rows, String entityName,
Class className)
{
if (page == null || page < 1)
{
page = 1;
}
if (rows == null || rows < 1)
{
rows = 10;
}
Query q = this.getCurrentSession().createSQLQuery(hql).addEntity(entityName, className);
if (param != null && param.size() > 0)
{
for (int i = 0; i < param.size(); i++)
{
q.setParameter(i, param.get(i));
}
}
return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
}
public List<T> findBySql(String sql)
{
Query q = this.getCurrentSession().createSQLQuery(sql);
return q.list();
}
public T get(Class<T> c, Serializable id)
{
return (T)this.getCurrentSession().get(c, id);
}
public T get(String hql, Object[] param)
{
List<T> l = this.find(hql, param);
if (l != null && l.size() > 0)
{
return l.get(0);
}
else
{
return null;
}
}
public T get(String hql, List<Object> param)
{
List<T> l = this.find(hql, param);
if (l != null && l.size() > 0)
{
return l.get(0);
}
else
{
return null;
}
}
public Long count(String hql)
{
return (Long)this.getCurrentSession().createQuery(hql).uniqueResult();
}
public List excuteQuerySql(String sql)
{
Query q = this.getCurrentSession().createSQLQuery(sql);
return q.list();
}
public Long count(String hql, Object[] param)
{
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.length > 0)
{
for (int i = 0; i < param.length; i++)
{
q.setParameter(i, param[i]);
}
}
return (Long)q.uniqueResult();
}
public Long countSql(String hql, List<Object> param)
{
Query q = this.getCurrentSession().createSQLQuery(hql);
if (param != null && param.size() > 0)
{
for (int i = 0; i < param.size(); i++)
{
q.setParameter(i, param.get(i));
}
}
BigDecimal bd = (BigDecimal)q.uniqueResult();
return bd.longValue();
}
public Long count(String hql, List<Object> param)
{
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.size() > 0)
{
for (int i = 0; i < param.size(); i++)
{
q.setParameter(i, param.get(i));
}
}
return (Long)q.uniqueResult();
}
public Integer executeHql(String hql)
{
return this.getCurrentSession().createQuery(hql).executeUpdate();
}
public Integer executeHql(String hql, Object[] param)
{
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.length > 0)
{
for (int i = 0; i < param.length; i++)
{
q.setParameter(i, param[i]);
}
}
return q.executeUpdate();
}
public Integer executeHql(String hql, List<Object> param)
{
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.size() > 0)
{
for (int i = 0; i < param.size(); i++)
{
q.setParameter(i, param.get(i));
}
}
return q.executeUpdate();
}
@Override
public T getObject(String hql, Map<String, Object> params)
{
Query q = this.sessionFactory.getCurrentSession().createQuery(hql);
if (params != null && !params.isEmpty())
{
for (String o : params.keySet())
{
q.setParameter(o, params.get(o));
}
}
List<T> l = q.list();
if (l != null && l.size() > 0)
{
return l.get(0);
}
return null;
}
@Override
public List<T> find(String hql, Map<String, Object> params)
{
Query q = this.sessionFactory.getCurrentSession().createQuery(hql);
if (params != null && !params.isEmpty())
{
for (String key : params.keySet())
{
q.setParameter(key, params.get(key));
}
}
return q.list();
}
@Override
public List<T> find(String hql, Map<String, Object> params, int page, int rows)
{
Query q = this.sessionFactory.getCurrentSession().createQuery(hql);
if (params != null && !params.isEmpty())
{
for (String key : params.keySet())
{
q.setParameter(key, params.get(key));
}
}
return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
}
@Override
public List<T> find(String hql, int page, int rows)
{
Query q = this.sessionFactory.getCurrentSession().createQuery(hql);
return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
}
@Override
public Long count(String hql, Map<String, Object> params)
{
Query q = this.getCurrentSession().createQuery(hql);
if (params != null && !params.isEmpty())
{
for (String key : params.keySet())
{
q.setParameter(key, params.get(key));
}
}
return (Long)q.uniqueResult();
}
@Override
public int executeBySql(String sql)
throws Exception
{
try
{
return this.getCurrentSession().createSQLQuery(sql).executeUpdate();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public BigDecimal findSequenceNextVal(String sequence)
{
BigDecimal b = null;
List list = this.getCurrentSession().createSQLQuery("select " + sequence + ".NEXTVAL from dual").list();
for (int i = 0; i < list.size(); i++)
{
b = (BigDecimal)list.get(i);
}
return b;
}
@Override
public void myupdate(T o)
{
this.getCurrentSession().merge(o);
// this.getCurrentSession().update(o);
}
@Override
public void mydelete(T o)
{
this.getCurrentSession().clear();
this.getCurrentSession().delete(o);
}
@Override
public void mysaveOrUpdate(T o)
{
this.getCurrentSession().merge(o);
}
}
- 总结1
- 总结1
- 总结1
- 总结 1
- 总结1
- 总结1
- 总结1
- 总结1
- 总结1
- 总结1
- 总结1
- 总结1
- 总结1
- 总结---1
- 总结1
- 总结1
- 总结1
- 总结1
- Unity3D研究院之Assetbundle的实战(六十三)
- 使用cocos2d-x3.0和物理引擎制作简单的platformer游戏
- Icehouse 安装体验
- BlueTooth: 蓝牙基础知识进阶——Physical channel
- JDBC的封装
- 总结1
- 如何使用cocos2d-x3.0和物理引擎来制作一个Breakout游戏:第一部分
- BlueTooth: 关于蓝牙你不可不知道的几个基础常识
- CentOS 6.3下Samba服务器的安装与配置
- 【动态规划】37回文字符串
- Spring Http Invoker
- 上海激动网络股份有限公司诉被告北京时越网络技术有限公司著作权侵权纠纷一案判决书
- 如何使用cocos2d-x3.0和物理引擎来制作一个Breakout游戏:第二部分
- Docker网络详解