Struts和Hibernate实现的查询分页显示

本文介绍了一个使用Struts和Hibernate实现的图书查询系统,该系统能够根据书名、作者或出版社进行搜索,并实现分页展示结果的功能。文章详细展示了关键类如Pager的实现方式及如何在Struts配置文件中定义Action。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Struts和Hibernate实现的查询数据库中book后分页显示的源代码(Book Bean类的代码不再显示):
业务实现过程:
          1.选择按什么查询,包括书名、作者、出版社,然后输入要查询的内容,提交查询。
            2.FormBean将提交的数据封装传递给Action进行处理。
            3.Action根据所得到的数据,调用组装DAO的业务逻辑,进行查询。
 
Pager Bean类的代码如下:
public class Pager {

 

	private int currentPage = 1;

	private int pageSize = 10;

	private int totalPages =0;

	private int totalRows = 0;

	private int pageStartRow = 0;

	private int pageEndRow = 0;

	private boolean hasPrevious = false;

	private boolean hasNext = false;

	@SuppressWarnings("unchecked")

	private List bookList;
	

	@SuppressWarnings("unchecked")

	public Pager(List list){

		this.currentPage=1;

		this.bookList=list;

		this.totalRows=list.size();

		this.hasPrevious=false;


		if(totalRows % pageSize==0)

			totalPages=totalRows/pageSize;

		else

			totalPages=totalRows/pageSize+1;


		if(currentPage>=totalPages)

			hasNext=false;

		else

			hasNext=true;	

		if(currentPage==1)

			hasPrevious=false;

		else 

			hasPrevious=true;
	

		if(totalRows<pageSize){

			this.pageStartRow=0;

		    this.pageEndRow=totalRows-1;

		}

		else{

			this.pageStartRow=0;

			this.pageEndRow=pageSize-1;

		}

	}

	public int getCurrentPage() {

		return currentPage;

	}

	public void setCurrentPage(int currentPage) {

		this.currentPage = currentPage;

	}

	public int getPageSize() {

		return pageSize;

	}

	public void setPageSize(int pageSize) {

		this.pageSize = pageSize;

	}

	public int getTotalPages() {

		return totalPages;

	}

	public void setTotalPages(int totalPages) {

		this.totalPages = totalPages;

	}

	public int getTotalRows() {

		return totalRows;

	}

	public void setTotalRows(int totalRows) {

		this.totalRows = totalRows;

	}

	public int getPageStartRow() {

		return pageStartRow;

	}

	public void setPageStartRow(int pageStartRow) {

		this.pageStartRow = pageStartRow;

	}

	public int getPageEndRow() {

		return pageEndRow;

	}

	public void setPageEndRow(int pageEndRow) {

		this.pageEndRow = pageEndRow;

	}

	public boolean isHasPrevious() {

		return hasPrevious;

	}

	public void setHasPrevious(boolean hasPrevious) {

		this.hasPrevious = hasPrevious;

	}

	public boolean isHasNext() {

		return hasNext;

	}

	public void setHasNext(boolean hasNext) {

		this.hasNext = hasNext;

	}

	@SuppressWarnings("unchecked")

	public List getBookList() {

		return bookList;

	}


	@SuppressWarnings("unchecked")

	public void setBookList(List bookList) {

		this.bookList = bookList;

	}


	@SuppressWarnings("unchecked")
 
         public List getBooks(){

           pageStartRow=(currentPage-1)*pageSize;

           if(hasNext==false)

	      pageEndRow=totalRows-1;

           else

              pageEndRow=pageStartRow+pageSize-1;

	  List books = new ArrayList();

	  for (int i = pageStartRow; i <= pageEndRow; i++) {

	        books.add((Bookinfo)bookList.get(i));

	  }

	    return books;

	}

	
	@SuppressWarnings("unchecked")

	public List getNextPage(){

	    currentPage=currentPage+1;

	    if(currentPage>=1 && currentPage<totalPages)

	    	hasNext=true;

	    else

	    	hasNext=false;

	    if(currentPage>1 && currentPage<=totalPages)

	    	hasPrevious=true;

	    else

	    	hasPrevious=false;

	    List books=getBooks();

	    return books;
	}

	@SuppressWarnings("unchecked")

	public List getPreviousPage(){

	    currentPage=currentPage-1;

	    if(currentPage>=1 && currentPage<totalPages)

	    	hasNext=true;

	    else

	    	hasNext=false;

	    if(currentPage>1 && currentPage<=totalPages)

	    	hasPrevious=true;

	    else

	    	hasPrevious=false;

	    List books=getBooks();

	    return books;	

	}
}
searchForm类的源代码如下:
@SuppressWarnings("unchecked")

public class searchForm extends ActionForm{

	private static final long serialVersionUID = 1L;

	private String searchItem;

         private String searchContent;

	public String getSearchItem() {

		return searchItem;

	}

	public void setSearchItem(String searchItem) {

		this.searchItem = searchItem;

	}

	public String getSearchContent() {

		return searchContent;

	}

	public void setSearchContent(String searchContent) {

		this.searchContent = searchContent;

	}

}
searchAction类的源代码如下:
public class searchAction extends Action {

	Pager pager;

	@SuppressWarnings("unchecked")

	List list;

	@SuppressWarnings("unchecked")

	public ActionForward execute(ActionMapping mapping, ActionForm form,

			HttpServletRequest request, HttpServletResponse response)

			throws Exception {

		String action = request.getParameter("action");

		if (action == null || action.equals("null")) {

			list = selectBooks(form);

			if(list.size()<0 || list==null)

				return mapping.findForward("fail");

			pager = new Pager(list);

			List books = pager.getBooks();

		         request.setAttribute("ps",pager.getPageStartRow());

		         request.setAttribute("result", books);

			request.setAttribute("pager", pager);

		} else {

			if (action == "prepage" || action.equals("prepage")) {
				
                      List books = pager.getPreviousPage();

			    request.setAttribute("ps",pager.getPageStartRow());	

				request.setAttribute("result", books);

				request.setAttribute("pager", pager);

			}

			if (action == "nextpage" || action.equals("nextpage")) {

			    List books = pager.getNextPage();

			    request.setAttribute("ps",pager.getPageStartRow());

				request.setAttribute("result", books);

				request.setAttribute("pager", pager);

			}

		}

                 return mapping.findForward("success");

	}



	@SuppressWarnings("unchecked")

	public List selectBooks(ActionForm form) {

		searchForm searchform = (searchForm) form;

		String item = searchform.getSearchItem();

		String content = searchform.getSearchContent();

		searchDAO dao = new searchDAO();

		List list = null;

		if (item.equals("bookname"))

			list = dao.getBookBybookName(content);

		if (item.equals("author"))

			list = dao.getBookByAuthor(content);

		if (item.equals("press"))

			list = dao.getBookByPress(content);

		return list;

	}

}
 
struts-config.xml文件如下:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>

  <!-- ===========FormBean and Action applicated to search books========== -->

  <form-beans>

     <form-bean name="searchForm" type="com.ustc.actionform.guix.searchForm">

     </form-bean>

  </form-beans>

 
  <action-mappings>

      <action path="/searchAction" type="com.ustc.action.guix.searchAction" name="searchForm" scope="request">

         <forward name="success" path="/searchresult.jsp"></forward>

         <forward name="fail" path="/searchfail.jsp"></forward>

      </action>

  </action-mappings>

 <!-- ===========FormBean and Action applicated to search books========== -->

<message-resources parameter="com.ustc.ApplicationResource"></message-resources>

</struts-config>
 
web.xml文件如下:
 
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<!--===============================字符编码转换过滤器 ===================================  -->

  <filter>

       <filter-name>set character encoding</filter-name>

       <filter-class>com.ustc.action.guix.SetCharacterEncodingFilter</filter-class>

       <init-param>

            <param-name>encoding</param-name>

            <param-value>gb2312</param-value>

       </init-param>

  </filter>

  <filter-mapping>

       <filter-name>set character encoding</filter-name>

       <url-pattern>*.do</url-pattern>      

  </filter-mapping>

<!--===============================字符编码转换过滤器 ===================================  -->

  <servlet>

    <servlet-name>action</servlet-name>

    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

    <init-param>

      <param-name>config</param-name>

      <param-value>/WEB-INF/struts-config.xml</param-value>

    </init-param>

    <init-param>

      <param-name>debug</param-name>

      <param-value>3</param-value>

    </init-param>

    <init-param>

      <param-name>detail</param-name>

      <param-value>3</param-value>

    </init-param>

    <load-on-startup>0</load-on-startup>

  </servlet>

  <servlet-mapping>

    <servlet-name>action</servlet-name>

    <url-pattern>*.do</url-pattern>

  </servlet-mapping>

  <welcome-file-list>

    <welcome-file>/index.jsp</welcome-file>

  </welcome-file-list>

</web-app>
 
SetCharacterEncodingFilter类源代码如下:
public class SetCharacterEncodingFilter implements Filter {

    protected String encoding=null;

    protected FilterConfig filterConfig =null;

    protected boolean ignore = true;

	@Override

	public void destroy() {

	   //撤销所有全局变量的值,置为NULL

	   this.encoding=null;

	   this.filterConfig=null;

	}

	@Override

	public void doFilter(ServletRequest request, ServletResponse response,

			FilterChain chain) throws IOException, ServletException {

	   //从web.xml中得到过滤器的字符串编码

       if(ignore || (request.getCharacterEncoding()==null)){

    	    String encoding = selectEncoding(request);

    	    if(encoding!=null)

    	    	 request.setCharacterEncoding(encoding);//设置字符串编码

       }

       chain.doFilter(request, response);

	}

    
	@Override

	public void init(FilterConfig filterConfig) throws ServletException {

		//初始化方法判断web.xml中过滤器是否传入ignore参数,当ignore参数为yes或true时忽略本过滤器

                   this.filterConfig = filterConfig;

                this.encoding = filterConfig.getInitParameter("encoding");

                String value = filterConfig.getInitParameter("ignore");

                if(value==null)

        	             this.ignore=true;

                else if(value.equalsIgnoreCase("true"))

                      this.ignore=true;

                else if (value.equalsIgnoreCase("yes")) 

	             this.ignore=true;

                else 

        	             this.ignore=false;    

	}

    public String selectEncoding(ServletRequest request){

    	return (this.encoding);

    }

}
 
searchresult.jsp源代码如下:
 
<%@ page contentType="text/html;charset=gb2312" language="java"%>

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>

<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%>

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>


<html>

<head><title>查询结果</title></head>

<body>

    <center><h2>查询结果</h2>

    <html:link page="/index.jsp">首页</html:link>|

      <hr/>

    </center> 

    <br/><br/>

    <table border="1" width="90%" align="center">

        <tr>

          <td width="4%" align="center">序号

            <td width="37%" align="center">书名

            <td width="13%" align="center">作者

            <td width="10%" align="center">价格

            <td width="18%" align="center">出版社

    </tr>

        <logic:present name="result" scope="request">

	     共<bean:write name="pager" property="totalPages"/>页

	      第<bean:write name="pager" property="currentPage"/>页

	      共<bean:write name="pager" property="totalRows"/>条记录

               	          
	      <logic:equal name="pager" property="hasPrevious" value="true">

	                 <html:link page="/searchAction.do?action=prepage">上一页</html:link>

	     </logic:equal>

	     <logic:equal name="pager" property="hasNext" value="true">   

	                 <html:link page="/searchAction.do?action=nextpage">下一页</html:link>

	     </logic:equal>

		        
              <%! static int i=1; %>

              <logic:iterate id="abook" name="result" scope="request">

	        <tr>

	        <td align="center">	

	              <% int rowstart=Integer.parseInt((request.getAttribute("ps").toString()));out.print(rowstart+i); i++;%>

	        </td>

	        <td><bean:write name="abook" property="bookname"></bean:write></td>

	        <td align="center"><bean:write name="abook" property="author"></bean:write></td>

	        <td align="center"><bean:write name="abook" property="price" format="0.00"></bean:write></td>

	        <td align="center"><bean:write name="abook" property="press"></bean:write></td>

         	        </tr> 

	      </logic:iterate>

               <% i=1; %>

      </logic:present>  

    </table>

</body>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值