2月6日——培训第65天

春节前的最后一天课……班里面现在连一半人都不到了……

BBS逻辑层和数据层封装:

新建Web工程mybbs,加入Struts特性。

加入Hibernate特性:
数据源名称:java:comp/env/jdbc/data
dialect名称:MySQL


meta-inf里面建立一个context.xml:
把数据源的东西拷贝进去
<Context path="/mybbs" docBase="mybbs">
 <Resource name="jdbc/data" auth="" type=""…………………………
 ……………………url="……………………………………">
</Context>


加入Hibernate的特性的过程中可以选择生成Session和SessionFactory的类。
添加show_sql和format_sql属性为true
---------------------------------------
system.properties:

characterEncoding=gbk
---------------------------------------
org.mybbs.util包里面新建SystemConfig:

public class SystemConfig(作用:去读取资源包)
{
 public static ResourceBundle bundle = ResourceBundle
          .getBundle("system");
 public static final String CHARACTER_ENCODING = "characterEncoding";
 //做成静态的,根据属性名得到属性值
 public static String getProperty(String name)
 {
  String s = null ;
  try
  {
   s = bundle.getString(name);
  }
  catch(RuntimeException e)
  {
   e.printStackTrace() ;
  }
  return s ;
 }

 public static String getCharacterEncoding()
 {
  return getProperty(SystemConfig.CHARACTER_ENCODING);
 }
}


BBSActionServlet:
package org.mybbs.action;
public class BBSActionServlet extends ActionServlet
{
 protected void process(HttpServletRequest request,HttpServletResponse response)
 {
  request.setCharacterEncoding(SystemConfig.getCharacterEncoding());
  response.setCharacterEncoding(SystemConfig.getCharacterEncoding());
  super.process(request,response);//这句话一定不能丢!!!
 }

}

既然重写了ActionServlet,那么必须修改ActionServlet中的配置!

<servlet-class>org.mybbs.action.BBSActionServlet</servlet-class>

现在重新实现Action:
package org.mybbs.action;
public class GeneralAction extends Action
{
 //查询返回集合。这里面涉及分页的问题
 protected List query(HttpServletRequest request,Class clazz,boolean needPagination)
 {
  List list = null ;
  if(needPagination)
  {
   Pagination pagination = new Pagination() ;
   list = pagination.getNextPage(request,clazz) ;
  }
  else
  {
   Session session = null ;
   try
   {
    session = HibernateSessionFactory.getSession() ;
    session.beginTransaction() ;
    list = session.createCriteria(clazz).list();
             
    session.getTransaction().commit();
   }
   catch(HibernateException e)
   {
    if(session!=null&&session.getTransaction()!=null)
    {
     session.getTransaction().rollback();
    }
    e.printStackTrace();
   }
   finally
   {
    HibernateSessionFactory.closeSession() ;
   }
  }
  return list ;
 }
 
 //封装插入功能,将异常全部抛给客户端,让struts去处理
 protected void save(Class clazz Map map) throws Exception
 {
  Session session = null;

  Object obj = null ;
  obj = clazz.newInstance() ;
  BeanUtils.populate(obj,map) ;
  
  if(obj!=null)
  {
   try
   {
    session = HibernateSessionFactory.getSession();
    session.beginTransaction();
    session.save(obj);
    session.getTransaction().commit();
   }
   catch(HibernateException e)
   {
    if(session!=null && session.getTransaction()!=null)
    {
     session.getTransaction().rollback() ;
    }
    e.printStackTrace() ;
   }
   finally
   {
    HibernateSessionFactory.closeSession() ;
   }
  }
  
 }

 protected void modify(Object obj) throws Exception
 {
  
 }

 protected void delete(Object obj) throws Exception
 {
 
 }

}


package org.mybbs.util;
//解决分页问题:
public class Pagination
{
 private int perPage = Pagination.defaultPerPage ;//每页显示条目
 private int page = 1; //当前的页数
 
 public static final String PER_PAGE = "org.mybbs.per_page" ;
 public static final String PAGE = "org.mybbs.page" ;
 public static final String TOTAL_PAGE = "org.mybbs.total_page";

 public static int defaultPerPage = 2 ;
 //生成getters和setters方法
 public List getNextPage(HttpServletRequest request,Class clazz)
 {
  List result = null ;

  Session session = null ;
  
  String perPageStr = request.getParameter(Pagination.PER_PAGE);
  String pageStr = request.getParameter(Pagination.PAGE) ;
  
  try
  {
   page = Integer.parseInt(pageStr);
   
   
  }
  catch(NumberFormatException e1)
  {
   
   page = 1 ;
  }

  try
  {
   
   Pagination.defaultPerPage = Integer.parseInt(perPageStr);
   perPage = Pagination.defaultPerPage ;
  }
  catch(NumberFormatException e1)
  {
   perPage = Pagination.defaultPerPage ;
   
  }
  
  
  session = HibernateSessionFactory.getSession();
  //HibernateSessionFactory是myeclipse给你封装好的一个类。
  
  //我们要的是记录的总数目,在HQL中,select count(*) from User
  //就是选出记录数,但是怎么用Criteria来实现选出记录数呢?

  //关系表的三种操作:选取(选行)、连接、投影(选列)
  session.beginTransaction() ;
  Criteria criteria = session.createCriteria(clazz)
           .setProjection(Projections.rowCount());
  //这就得到了记录数
  Integer rowCount = (Integer) criteria.uniqueResult();
  int totalPage = (rowCount.intValue()+perPage-1)/perPage ;//总页数
  
  if(page<1 || page>totalPage)
  {
   page = 1 ;
  }

  result = session.createCriteria(clazz).setFirstResult((page-1)*perPage)
             .setMaxResults(perPage)
             .list() ;
 
  session.getTransaction().commit();
  
  
  request.setAttribute(Pagination.PAGE,new Integer(page));//当前页数
  request.setAttribute(Pagination.TOTAL_PAGE,new Integer(totalPage));
  //总页数存入请求作用域

  HibernateSessionFactory.closeSession() ;
  //不仅关闭了Session,还把ThreadLocal中清空了,这里不能使用Session.close()
  return result ;

 }
}


--------------------------------------------------------------------------------

前台封装:

显示分页的结果:

第1页/共10页  上一页   下一页    跳转到__页  每页6条

应该封装成标签较好。

建一个标签处理类:

package org.mybbs.taglib;

public class PaginationTag extends SimpleTagSupport
{
 private String url = null ;

 private boolean showPerPage = true ;
 private boolean showToPage = true ;
 //别忘了给上面的三个属性加入getter和setter方法!!!
 
 public void doTag() throws JspException,IOException
 {
  PageContext pageContext = (PageContext)getJspContext ;
  JspWriter out = pageContext.getOut() ;
  StringBuffer sb = new StringBuffer() ;
  if(url==null)
  {
   url = ((HttpServletRequest)pageContext.getRequest()).getRequestURI();
  }
  System.out.println(url);
  
  sb.append("<form action='")
    .append(url)
    .append("'>");

  renderInfo(pageContext,sb); //第1页/共10页
  renderPrePage(pageContext,sb);//上一页       
  renderNextPage(pageContext,sb);//下一页
  if(showToPage) renderToPage(sb);// 跳转到__页
  if(showPerPage) renderPerPage(sb);//每页6条
  
  sb.append("</form>");
  out.println(sb.toString());
 }

 protected void renderInfo(PageContext pageContext,StringBuffer sb)
  throws JspException,IOException
 {
  
  Integer page = (Integer)pageContext.getRequest().getAttribute(Pagination.PAGE);
  if(page==null)
  {
   page = new Integer(1) ; 
  }
  Integer totalPage = (Integer)pageContext.getRequest()
   .getAttribute(Pagination.TOTAL_PAGE);

  sb.append("第")
    .append(page.intValue())
    .append("页");
  if(totalPage!=null)
  {
   sb.append("/").append("共").append(totalPage).append(页);
  }
 }

 protected void renderPrePage(PageContext pageContext,StringBuffer sb)
  throws JspException,IOException
 {
  Integer page = (Integer)pageContext.getRequest().getAttribute(Pagination.PAGE);
  if(page==null)
  {
   page = new Integer(1) ; 
  }

  if(page.intValue()<=0)
  {
   sb.append("    ").append("上一页");
  }
  else
  {
   sb.append("<a href='").append(url).append("?").append(Pagination.PAGE)
     .append("=").append(page.intValue()-1)
     .append("'>").append("上一页").append("</a>");
  }
 }

 protected void renderNextPage(PageContext pageContext,StringBuffer sb)
  throws JspException,IOException
 {
  Integer page = (Integer)pageContext.getRequest().getAttribute(Pagination.PAGE);
  if(page==null)
  {
   page = new Integer(0) ; 
  }
  
  Integer totalPage = (Integer)pageContext.getRequest()
   .getAttribute(Pagination.TOTAL_PAGE);
  
  if(totalPage==null)
  {
   return ; 
  }
  if(page.intValue()>=totalPage.intValue())
  {
   sb.append("    ").append("下一页");
  }
  else
  {
   sb.append("<a href='").append(url).append("?").append(Pagination.PAGE)
     .append("=").append(page.intValue()+1)
     .append("'>").append("下一页").append("</a>");
  }
 }

 protected void renderToPage(StringBuffer sb) throws JspException,IOException
 {
  sb.append("到<input type='text' name='")
    .append(Pagination.PAGE)
    .append("' size='1' οnblur='document.forms[0].submit()'>页");
   
 }

 protected void renderPerPage(StringBuffer sb) throws JspException,IOException
 {
  sb.append("每页显示<input type='text' name='")
    .append(Pagination.PER_PAGE)
    .append("' size='1' οnblur='document.forms[0].submit()'>条");
   
 }
}


建立一个tld文件mybbs.tld

<tlib-version>2.0</tlib-version>
<short-name>mybbs</shourt-name>

<tag>
 <name>pagination</name>
 <tag-class>org.mybbs.taglib.PaginationTag</tag-class>
 <body-content>scriptless</body-content>
 <attribute>
  <name>url</name>
  <required>no</required>
  <rtexprvalue>yes</rtpextvalue>
 </attribute>
 <attribute>
  <name>showToPage</name>
  <required>no</required>
  <rtexprvalue>yes</rtpextvalue>
 </attribute>
 <attribute>
  <name>showPerPage</name>
  <required>no</required>
  <rtexprvalue>yes</rtpextvalue>
 </attribute>
</tag>

------------------------------------------------

做一个Action来测试一下上面的分页封装:
org.mybbs.action.GeneralActioni作为Action的直接父类

<action path="/listSection" type="org.mybbs.action.ListSectionAction">
 <forward name="success" path="/WEB-INF/jsp/listSection.jsp">
</action>
public class ListSectionAction extends GeneralAction
{
 public ActionForward execute()
 {
  request.setAttribute("sections",query(request,Sections.class,true));
  return mapping.findForward("success");
 }
}


在WEB-INF中建立一个jsp页面listSection.jsp

引入mybbs的tld文件和logic的tld文件。

<body>
 <table border="1">
  <logic:iterate id="section" name="sections">
   <tr>
    <td>${section.sectionId}</td>
    <td>${section.sectionName}</td>
    <td>${section.sectionEnglishName}</td>
    <td>${section.sectionTable}</td>
    <td>${section.onlineAmount}</td>
    <td>${section.sectionCreateTime}</td>
   </tr>
  </logic:iterate>
  <tr>
   <td colspan="6" align="right">
    <mybbs:pagination url="${pageContext.request.contextPath}/listSection.do"/>
   </td>
  </tr>
 </table>
</body>


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值