Use Struts to combine JBuilder7, MySQL to establish a Web site (2) - Page Display
Author: Sailing (blue shrimp)
IAMCYH@263.net This program all source code: vod.zip introduction: This article follows the first content, continuing the production of the VOD website (first "using struts combined with jbuilder7, mysql to establish a Web site (1) - Connection database "), when we need to provide a large amount of content in the database, we generally use two methods, the first simple, read the contents of the database in the database, then all displayed on the web, this The method is generally used when the amount of data is small; there is a method to display the paging display, and it is also a way to use the major websites. There are many ways to paginize, and I use it here to take a mobile database pointer. Methods.
Establishing pageInfo bean's task is to store all information about pagination, including total number of pages, total number of records, current pages, number of pages of the previous page, the number of pages of the next page, will these five Information is included in the same bean will have a great convenience of programming in the JSP page, because there are currently many websites to put the current pages, the number of pages of the previous page, and the number of pages of the next page In the bean, but in the JSP page, add 1 and minus 1, which is added, although it is very convenient, but this will result in logical operations in the JSP page, destroy the rules of the MVC, or above Putting 5 variables into a bean programming method is just my personal habit. If you feel that there is something wrong, please advise. The code for pageinfo is as follows:
package vod.model; import java.util.Vector; public class PageInfo {private int totalPage; // total number of pages private int resultCount; // a total of how many records private int page; // current number of pages private int previousPage ; // Previous PRIVATE INT NEXTPAGE; / / Next Public Void SetTotalpage (INT TOTALPAGE) {this.totalpage = Totalpage;} public int gettotalpage ()}} ---------------------------------- Public void setResultcount (int count) {this.resultcount = count;} Public int getResultcount () {returnrate resultcount;} // -------------------------------------------------------------------------------------------------------------------------------------------- ----- Public void setpage (int page) {this.page = page;} public int get;} // ------------------ ------------------------- Public void setpreviouspage = page;} public int getpreviouspage () {Return (this. Page-1);} // ------------------------------------------ -public void setnextPage (INT page) {this.nextpage = page;} public int getNextPage () {return (this.page 1);} //-------------- --------------------------- / *** Generate a PageInfo object based on the array * We agree that index in the array is 0 Total number of pages * index is 1 record total * @Param info * @ Return * / public static pageinfo load (int "info) {pageinfo (); int int atvalue = 0; intValue = info [0]; if (INTVALUE > 0) PageInfo.SettotalPage (INTVALUE); INTVALUE = INFO [1]; if (INTVALUE> 0) PageInfo.setResultCount (INTVALUE); Return PageInfo;}} At the INT array in the LOAD () method here, we agree The first element in the middle page is the total page, the second element is the total number of records. The getPreviouspage () method here does not return PREVIOUSPAGE directly, but is reduced according to the value of Page. 1 Get previouspage is convenient for future calls.
Based on the database, we must first do what we have to do before making a paging is to determine what is the amount of data in the database you want. The amount of data can be divided into a few pages, with a total of how much data. Let's take a look at the implementation of this paging code (EvaluatedateBase.java):
package vod.model; import java.sql.Connection; import org.gjt.mm.mysql.jdbc2.ResultSet; import java.sql.PreparedStatement; import java.sql.Statement; import java.sql.SQLException; public class EvaluateDateBase { / *** Returns an instance of PageInfo based on the number of data sheets in the method, and returns a pageinfo instance * / public static pageinfo getpageInfo (String Datebase, Connection CONN, INT PAGESIZE) THROWS SQLEXCEPTION {INT TOTALPAGE = 0 ; int resultcount = 0; int = info = new int [2]; string sql = ""; if (conn == null) throw new SQLEXCEPTION ("No CONN EVALUATEDATEBASE"); ResultSet RsCount = NULL; preparedState psmt = NULL; SQL = "SELECT Count (*) from" DateBase; / / Depending on the database's name, the corresponding SQL statement try {psmt = conn.preparestatement (sql); rscount = (resultset) psmt.executeQuery (); rscount .next (); resultcount = rscount.getint (1); rscount.close ();} catch (sqlexception e) {E.PrintStackTrace ();} Totalpage = (Resultcount Pagesize-1) / PageSize; // Statistics Page number / / Remember our agreement? // index is 0 for the total number of pages, index is 1 Total number of records INFO [0] = TotalPage; Info [1] = resultcount; PageInfo PageInfo = PageInfo.Load (info); Return PageInfo;} SQL = "Select Count (*) from" DateBase; get the corresponding SQL statement, based on the result set obtained by this SQL statement through GetInt (1) How many records will be received by this result set.
And (Resultcount PageSize-1) / PageSize gets the number of record numbers that are displayed in need, maybe beginners will puzzle why not directly use the total number of results to get the total number of pages with the number of results required per page. This is because if the number of records contains cannot be completely removed, then the number of statistics will be less than one page, according to the above method calculations will get the correct value, if you are interested, everyone can calculate, of course, you can It is achieved by another method to be added if it is not possible to complete it. Finally, the total number of points and total record numbers are placed in a PageInfo instance for future calls.
Get all the movies about football, and obtain the appropriate LinkedList to obtain the code required by the appropriate LinkedList to get the code required by the page, and our page principle is simple, and an example: Currently we set up Only 10 records are displayed, so if the user wants to get the content on page 2, it is a record 11-20, we will move the database from the 10th record, then through While and Next ) The combined method obtains data from 10-20. Each record is then read, and the field of the database is matched in the field in the FOOTBALL BEAN through FOOTBALL LOAD () and put it in a LinkedList. Code below (MoreFootball.java): package vod.model; import java.sql.Connection; import org.gjt.mm.mysql.jdbc2.ResultSet; import java.sql.PreparedStatement; import java.sql.Statement; import java. sql.SQLException; import java.util.LinkedList; public class MoreFootball {Connection conn; public void setConn (Connection conn) {this.conn = conn;} public LinkedList getFootballList (int page, int pageSize) throws SQLException {LinkedList footballList; if (conn == null) throw new SQLException ( "No Connection in MoreFootball"); PreparedStatement pstmt = null; ResultSet rs = null; footballList = new LinkedList (); try {pstmt = conn.prepareStatement ( "select * from football order by Date DESC "); RS = (ResultSet) pstmt.executeQuery (); // According to the number of pages currently displayed and each page requires a pointer INT i = (Page-1) * PageSize; // Due to the 0 position IF (i! = 0) f (i! = 0) f (i); // If i is 10, then the database's pointer will move on / * for (int J = 0; j
Note that the code commented here: / * for (int J = 0; j
package vod.controller; import vod.model.PageInfo; import vod.model.MoreFootball; import vod.model.EvaluateDateBase; import java.io.IOException; import java.util.LinkedList; import java.util.Locale; import javax. servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts. action.ActionMapping; import org.apache.struts.action.ActionServlet; import org.apache.struts.util.MessageResources; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; public class MoreFootballAction Extends action {Connection Connection; LinkedList FootballList; Public ActionForward Perform (ActionMApping Mapping, ActionForm for m, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {ActionErrors errors = new ActionErrors (); HttpSession session = request.getSession (); int page = 0; // current number of pages required int pageSize = 0; // every Page Display how many data PageInfo FootballPageInfo = NULL; / / About information about the number of pages String Temppage; / / From the web.xml file acquired the number of entries displayed per page (I set to 10) PageSize = Integer.Parseint String) Servlet.getServletContext (). GetInitParameter ("Pagesize"))); // If there is no clear page number, the default is the first page Temppage = Request.getParameter ("page"); if (Temppage == Null) Temppage = " 1 "; page = integer.parseint (TEMPPAGE); Try {DataSource DataSource = servlet.finddataSource (NULL); connection = DataSource.getConnection (); // Check if the session already exists,
If you don't have a query, add FootballPageInfo // to session // // If you already exist directly from the session (SESSION.GETATTRIBUTE ("FootballPageInfo") == NULL) {// parameter is a data sheet name, connection, how many entries per page footballPageInfo = EvaluateDateBase.getPageInfo ( "football", connection, pageSize);} else {footballPageInfo = (PageInfo) session.getAttribute ( "footballPageInfo");} if (page> footballPageInfo.getTotalPage ()) {page = footballPageInfo.gettotalpage ();} else if (page <0) {page = 1;} // Set the previous page of FootballPageInfo and the value footballpageinfo.setpage (Page); // the footballPageInfo placed sessionsession.setAttribute ( "footballPageInfo", footballPageInfo); footballList = new LinkedList (); moreFootball morefootball = new moreFootball (); morefootball.setConn (connection); // connection setup data as necessary pages // and the number of pages per page article obtained LinkedListfootballList = morefootball.getFootballList (page, pageSize); if (footballList == null) {saveErrors (request, errors); return (new ActionForward ( "No footballList in vod.controller.MoreFootallAction "));} session.setttribute (" footballlist ", footballlist); // Put the FootballList will be put into session // do what you wish with myco Nnection} catch (sqlexception SQLE) {GetServlet (). log ("Connection.Process", SQLE);} Finally {// Enclose THIS IN A FINALLY BLOCK To Make // Sure THE Connection Is CloseDif (Connection! = NULL) TRY {Connection.close ();} catch (SQLException E) {getServlet (). log ("Connection.Close", E);}} Return ("Success"));}} Action.xml and Struts -config.xml file Configuration This will no longer be elaborated, please refer to the first article "Use Struts to combine JBuilder7, MySQL to establish Web Site (1) - Connect Database" struts-config.xml:
XML Version = "1.0" Encoding = "ISO-8859-1"> <- This is the Struts configuration file for the example application, using the proposed new syntax NOTE: You would only flesh out the details in the." form- bean "declarations if you had a generator tool that used them to createthe corresponding Java classes for you. Otherwise, you wouldneed only the" form-bean "element itself, with the corresponding" name "and" type "attributes .--> < Struts-config> ==== form bean definitions ========================================== -> JSP page Welcome.jsp: The link will be added to this page and call morefootballAction and specify the first page. code show as below: <% @ Page ContentType = "Text / HTML; Charset = GB2312"%> <% @ Taglib Uri = "/ Web-INF / STRUTS-Bean.TLD" prefix = "bean"%> <% @ Taglib URI = "/ Web-inf / struts-html.tld "prefix =" html "%> <% @ taglib URI =" / web-inf / struts-logic.tld "prefix =" logic "%> Tr> / html: link> td> "48"> Intro "/> div> "Length" /> div> td> tr> logic: Itereate> table> body> html> morefootball.jsp: Here <% @ Page ContentType = "Text / HTML; Charset = GB2312"%> <% @ Taglib Uri = "/ Web-INF / STRUTS-Bean.TLD" prefix = "bean"%> <% @ Taglib URI = "/ Web-inf / struts-html.tld "prefix =" html "%> <% @ taglib URI =" / web-inf / struts-logic.tld "prefix =" logic "%> "Length" /> div> In fact, there is also a part of the name to pop up a new window after clicking the name of the football movie, including information about the corresponding football movie, because the content is repeated, so it is no longer written, including in the source code. The next article will be about the use of FORMBEAN and the insertion and deletion of the database. All source code: vod.zip I write an article's purpose only because I can only find very little Chinese information about Struts at the time, especially fire, simply wrote one. I sincerely hope that Chinese information about Java on the Internet can get more and more. In the use of Tomacat, it produces a problem with Tomact MySQL to use the connection pool in JB7. Please help me, thank you. About the Author: Sailing, studied at the industrial and commercial management of Nanjing University of Technology, hobby Java programming, familiar with website production, sincerely hopes to communicate with you. Studio: Mars Studio
id div> td> footname div> td> ClickS div> td> commend div> td> bad div> td> div>
ID div> td> commend div> td> bad div> td>
Moviename div> td>
div> td>
ID div> td> ViewURL div> td> ClickS div> td> INTRO div> td> DATE div> td>
div> td>