SSH2中简单封装

1:在Strut2的Action经常要保存数据放到jsp页面中,不如在struts1所用的request.setAttribute(key,value);方法好用,所以可以通过简单的封装来使这种方法来传值:
BaseAction.java
package cn.com.netDragon.base;


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

import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

public abstract class BaseAction extends ActionSupport implements Action{
// 成功常量
public static final String SUCCESS = "success";
public static final int PAGE=20;
//如果session里没有,返回重新登陆
public static final String LOGIN = "login";
public static final String INPUT = "input";
// 失败常量
public static final String ERROR = "error";
public Object getBean(String id){
ServletContext servletContext = ServletActionContext.getServletContext();
WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
return context.getBean(id);
}
public HttpServletRequest request() {
return ServletActionContext.getRequest();
}

public HttpSession session() {
return ServletActionContext.getRequest().getSession();
}

public ServletContext application() {
return ServletActionContext.getServletContext();
}

public HttpServletResponse response() {
return ServletActionContext.getResponse();
}

}
然后在你的action中使用:
HttpServletRequest request = request();
request.setAttribute(key,value);方法了。

**************************************
2:在hibernate中经常对数据要进行添加,修改,删除,及其分页等操作,故简单的封装,直接继承就可以了:
BaseDAO.java
package cn.com.netDragon.base;

import java.sql.SQLException;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import cn.com.netDragon.util.GetID;
import cn.com.netDragon.util.Page;

public class BaseDAO extends HibernateDaoSupport{
public static final int PAGE=20;
public void add(Object o){
getHibernateTemplate().save(o);
/*//
try {
getHibernateTemplate().save(o);
} catch (Exception e) {
//e.printStackTrace();
throw new DataBaseException("数据库插入失败!");
}*/
}
public void update(Object o){
getHibernateTemplate().update(o);
}
public void delete(Object o){
getHibernateTemplate().delete(o);
}
public Object findById(Class clazz,Integer id){
return getHibernateTemplate().get(clazz, id);
}
public List findAll(String hql){
List list = this.getHibernateTemplate().find(hql);
return list;
}
public List findByDeatched(DetachedCriteria dc){
List list = getHibernateTemplate().findByCriteria(dc);
System.out.println(list.size());
return list;
}
//分页,适合无条件查询,参数为类名,页数
public List FenYe(String tableName,int page){
int start = 0;
int end = 0;
start = (page - 1) * PAGE + 1;
end = page * PAGE;
SessionFactory sf = getHibernateTemplate().getSessionFactory();
Session session = sf.openSession();
String sql = "SELECT * FROM (SELECT A.*,rownum RN FROM " +
"(SELECT * FROM "+tableName+") A WHERE ROWNUM <= "
+ end + ") WHERE RN >=" + start;
SQLQuery sqlq = session.createSQLQuery(sql);
sqlq.addEntity(GetID.getClass(tableName));
List list=sqlq.list();
session.close();
sf.close();
return list;
}
//查询总页数,适合无条件查询
public int totalPage(String tableName){
SessionFactory sf = getHibernateTemplate().getSessionFactory();
Session session = sf.openSession();
String sql = "select * from "+tableName;
SQLQuery sqlq = session.createSQLQuery(sql);
List list=sqlq.list();
session.close();
sf.close();
return list.size();
}

// ------------------------ 两种分页方式 ---------------------------

public Page pageByCriteria(final DetachedCriteria dc, int curPage) {
Page p = new Page();

Integer sum = (Integer) getHibernateTemplate().execute(
new HibernateCallback() {

public Object doInHibernate(Session s)
throws HibernateException, SQLException {
Criteria c = dc.getExecutableCriteria(s);
c.setProjection(Projections.rowCount());
return c.uniqueResult();
}
});

int totalPage = (int) Math.ceil(sum
/ Double.parseDouble(PAGE + ""));
p.setTotalPage(totalPage);

final int begin = (curPage - 1) * PAGE;
List list = (List) getHibernateTemplate().execute(
new HibernateCallback() {


public Object doInHibernate(Session s)
throws HibernateException, SQLException {
Criteria c2 = dc.getExecutableCriteria(s);
c2.setFirstResult(begin);
c2.setMaxResults(PAGE);
return c2.list();
}
});

p.setResult(list);
p.setCurrentPage(curPage);
return p;

}

public Page pageByHql(String className, String whereClause, int curPage) {
Page p = new Page();
final String hql = "from " + className + " "
+ whereClause;

// Integer sum = (Integer) getHibernateTemplate().execute(
// new HibernateCallback() {
// public Object doInHibernate(Session s)
// throws HibernateException, SQLException {
// Object obj = s.createQuery(hql).uniqueResult();
// return obj;
// }
// });
int sum = getHibernateTemplate().find(hql).size();

int totalPage = (int) Math.ceil(sum
/ Double.parseDouble(PAGE + ""));
p.setTotalPage(totalPage);

final int begin = (curPage - 1) * PAGE;
final String findHql = "from " + className + " " + whereClause;

List list = (List) getHibernateTemplate().execute(
new HibernateCallback() {


public Object doInHibernate(Session s)
throws HibernateException, SQLException {
Query q2 = s.createQuery(findHql);
q2.setFirstResult(begin);
q2.setMaxResults(PAGE);
return q2.list();
}
});

p.setResult(list);
p.setCurrentPage(curPage);
return p;
}

public Page pageByHql(String hql, int curPage) {
Page p = new Page();
int sum = getHibernateTemplate().find(hql).size();
p.setTotalRecordNum(sum);

int totalPage = (int) Math.ceil(sum
/ Double.parseDouble(PAGE + ""));
p.setTotalPage(totalPage);

final int begin = (curPage - 1) * PAGE;
final String findHql = hql;

List list = (List) getHibernateTemplate().execute(
new HibernateCallback() {


public Object doInHibernate(Session s)
throws HibernateException, SQLException {
Query q2 = s.createQuery(findHql);
q2.setFirstResult(begin);
q2.setMaxResults(PAGE);
return q2.list();
}
});

p.setResult(list);
p.setCurrentPage(curPage);
p.setBeginNum((curPage-1)*PAGE);
return p;
}

/**
* 按HQL查询唯一对象.
* by wjf
*/
public Object findUnique(String hql) {
return this.getSession().createQuery(hql).uniqueResult();
}
}

*********************************
在相应的Dao层和service层调用:
*******************************************
dao层:
*******************************************
/**
* 查找所有新闻发布信息,并分页显示
* @param curPage
* @return page
* @author Li_jian
*/
@SuppressWarnings("unchecked")
public Page findAllNews(int curPage) {
String hql = "from SysNews sn";
Page page = pageByHql(hql, curPage);
return page;
}
******************************************
service层:
******************************************
/**
* 初始化新闻管理,并分页显示
* @param curPage
* @return
* @author Li_jian
*/
@SuppressWarnings("unchecked")
public Page initNews(int curPage){
Page page = adminDaoImpl.findAllNews(curPage);
List result = new ArrayList();
List list = page.getResult();
for(int i=0;i SysNews sn = list.get(i);
SysNewsVO vo = new SysNewsVO();
vo.setSysNews(sn);
result.add(vo);
}
page.setResult(result);
return page;
}
*************************************************
Page.class 中的内容:
************************************************
package cn.com.netDragon.util;

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

public class Page implements Serializable {
private int currentPage;
private int totalRecordNum;
private int totalPage;
private List result;
private int beginNum;

public int getBeginNum() {
return beginNum;
}

public void setBeginNum(int beginNum) {
this.beginNum = beginNum;
}

public int getCurrentPage() {
return currentPage;
}

public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}

public int getTotalPage() {
return totalPage;
}

public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}

public List getResult() {
return result;
}

public void setResult(List result) {
this.result = result;
}

public int getTotalRecordNum() {
return totalRecordNum;
}

public void setTotalRecordNum(int totalRecordNum) {
this.totalRecordNum = totalRecordNum;
}
}
**************************************
Action中的调用:
**************************************
@Override
public String execute() throws Exception {
HttpServletRequest request = request();
try {
//分页显示sysnews
String curpage = request.getParameter("page");
int curPage = 1;
if (curpage != null && curpage.length() > 0) {
curPage = Integer.parseInt(curpage);
}
Page page = adminManage.initNews(curPage);
request.setAttribute("page", page);
request.setAttribute("url", "right.action?2=2");

return SUCCESS;
} catch (Exception e) {
if (Constants.DEBUG) {
e.printStackTrace();
}
return ERROR;
}
}
**************************************************
jsp页面中的显示:
*************************************************








首页  

上页
  下页
  末页



仅供个人学习使用,Thanks。

你可能感兴趣的:(SSH)