Use Struts to combine JBuilder7, MySQL to establish a Web site (1) - Connect Database (Modify)
Author: Sailing (blue shrimp)
Iamcyh@263.net This program all Sourcecodes: vod.zip
Introduction: For the introduction of Struts, please refer to: http://jakarta.apache.org About Struts Chinese version User Guide: Download (We want Special Marmbers forum thanks to Mr. Cao Xiao Gang's selfless dedication, the article is his translation) Discuss how to use JBuilder7 combined with Struts to create a background database for mysql's Web site. Site function analysis: (1) This website is a VOD on-demand website, to meet the user's online viewing, download movie files, in the station search (2) All films in the website are classified into football shoots, movies, funny fragments, MTV four Category, and establish a data sheet in the database (3) Homepage, the top ten of the top ten movies of the above four categories, click on the "more" link next to each category, all movies, press the order ROP (4) Due to the large number of visitors, use the database connection pool. (5) Homepage Search colors, you can search for the above four categories as a keyword search (6) home page, click on the name of the corresponding topic, the first part of this topic This article is only completed (1) - (4) Preparation: First we download the "package" required to build this web site from the Internet, MySQL JDBC driver can be downloaded at www.mysql.com, the optional package of JDBC2.0 followed by programs Source code is available, Struts can get from http://jakarta.apache.org, servlet package is provided by JBuilder7. (1) Open JBuilder7, establish a new engineering (vod.jpx), change the default code of the project to GB2312, as shown below: (2) Will get the project requirement to join JBuilder, as shown in Figure: (3) established A servlet and JSP empty files are executed separately, then delete. (This is for JB automatically establishing a related directory, and obtains a servlet package) (4) unwrapping Struts-Example.War and Struts-documentation.war in the WebApps directory in the downloaded Struts with WinRAR or WinZip (Struts documentation) ), Find struts.tld, struts-bean.tld, struts-form.tld, struts-html.tld, struts-logic.tld, struts-template., Struts-template. TLD files, copy it to the / web-infrot directory under the project folder established in JB, and then join the project in JB to avoid deleting it when REBUILD is. As shown in the figure: (5) Create a database, establish a database named GDVOD in MySQL, establish the SQL required by the data table in the source code directory SRC, mysql.sql. The data sheet is as follows:
Name: Football
Column name
Types of
Description
id
VARCHAR (10) Unique ID
Footballname
VARCHAR (50)
Movie name
Viewurl
Varchar (255)
Watch online
Downurl
Varchar (255)
Download URL
ClickS
Int (5)
Users click the number of times
Sort
VARCHAR (20)
Category (default: football fragment)
INTRO
TEXT
Introduction
Commend
Int (5)
User recommended
date
VARCHAR (20)
Join the date
Bad
Int (5)
Users report bad links
Length
Int (5)
The length of the film
The rest of the data is in this class, and the movie name fields in Fun, Movie, MTV are Funname, Moviename, MtVName, respectively.
Establishing Bean (1) Corresponds to this, we establish a map of data tables relative to Bean. Create a bean named Football, located in the vod.mode package as follows:
package vod.model; import java.sql.SQLException; import org.gjt.mm.mysql.jdbc2.ResultSet; import java.io.Reader; import java.io.BufferedReader; import java.io.Serializable; public class Football implements Serializable {private String id; private String footballName; private String viewURL; private String downURL; private int clicks; private String sort; private String intro; private int commend; private String date; private int bad; private int length; // - ----------------------------- Public void setid (String ID) {this.id = id;} public string getId () { Return ID;} // ------------------------------- public void setfootballname (string name) {this.footballname = name PUBLIC STRING GETFOOTBALLNAME () {Return FootballName;} // ----------------------------- Public void setViewURL (String URL) {this.viewURL = URL;} public string getViewURL () {Return viewURL;} // -------------------------------------------------------------------------------------------------------------------------------- --- Public void setdownurl (string url) {this.downurl = url;} public string getdownurl () {return downurl;} // -------------------- ----------- Public Void setClicks (int clicks) {this.clicks = clicks;} public int getClicks () {return clicks;} // ------------------------------------------------------------------------------------------------------------ ------- Public void setsort (string sort) {this.sort = sort;} public string getsort () {Return Sort;} // ------------------------------------------------------ --------------- Public void setIntro {this.intro = intro;} public string getIntro () {Return INTRO;} // -------- ----------------------- Public void setcommend (int commend) {this.commend = Commend;} public int getcommend () {return commend;} // ------------------------------ Public void setdate (string date) {this.date = date;} public string getdate ) {Return Date;} // ----------------------------- Public void setbad (int bag) {this.bad = Bad;} public int getbad () {return bad;
} // ------------------------------ Public void setlength (int length) {this.length = length;} int getLength () {return length;} public static Football load (ResultSet rs) throws SQLException {Football football = new Football (); String strValue = null; int intValue = 0; strValue = rs.getString ( "id"); if (strValue = null!) football.setId (strValue); strValue = rs.getString ( "footballName"); if (! strValue = null) football.setFootballName (strValue); strValue = rs.getString ( "viewURL"); if (Strvalue! = null) Football.SetViewURL (Strvalue); Strvalue = rs.getstring ("downurl"); if (strValue! = null) Football.SetDownurl; intValue = rs.Getint ("ClickS"); if (INTVALUE> 0) Football.SetClicks (intValue); strval = rs.getstring ("sort"); if (strValue! = null) Football.SetSort (Strvalue); / * try {reader reader = rs.getCharacTream ("Intro "); BufferedReader bReader = new BufferedReader (reader); String inLine; strValue =" "; while ((inLine = bReader.readLine ())! = null) {strValue = strValue inLine;}} catch (Exception e) { E.PrintStackTrace ();} * / strval = rs.getstring ("i NTRO "); if (strval! = null) Football.setIntro; INTVALUE = rs.Getint (" commend "); if (intValue> 0) Football.setcommend (intValue); strval = rs.getstring (" Date "); if (strValue! = null) football.Setdate (Strvalue); INTVALUE = rs.Getint (" BAD "); if (intValue> 0) Football.Setbad (intValue); intValue = rs.getint (" Length " ); IF (intValue> 0) Football.setlength; returnif;}}
Public Static Football Load (ResultSet RS) method As a static method of this bean, a reseltset object is received, and an instance of a FOOTBALL is generated in the method, and the contents of the RS are assigned to Fireball, and finally Returns this FOOTBALL instance The purpose of the database connection segment below will be described, and the data can be packaged well. We note here commented code: / * try {Reader reader = rs.getCharacterStream ( "intro"); BufferedReader bReader = new BufferedReader (reader); String inLine; strValue = ""; while ((inLine = bReader.readLine ())! = null = Strvalue inline;}} catch (E) {E.PrintStackTrace ();} * / This code is reported when the program is running: said Mysql JDBC2 does not implement rs.getcharacterstream ("Intro") This method, I feel very unexpected, or because I can't use this method, please advise. Since the TEXT type is used in the database, a large amount of text will use flow reading will increase the performance of the program. The code of the other three beans is as follows:
package vod.model; import org.gjt.mm.mysql.jdbc2.ResultSet; import java.sql.SQLException; import java.io.Reader; import java.io.BufferedReader; import java.io.Serializable; public class Fun implements Serializable {private String id; private String funName; private String viewURL; private String downURL; private int clicks; private String sort; private String intro; private int commend; private String date; private int bad; private int length; // - ----------------------------- Public void setid (String ID) {this.id = id;} public string getId () { Return ID;} // ------------------------------- public void setfunname (string name) {this.funname = name PUBLIC STRING GETFunName () {Return Funname;} // ------------------------------ Public void setViewURL (String URL) {this.viewURL = URL;} public string getViewURL () {Return viewURL;} // -------------------------------------------------------------------------------------------------------------------------------- --- Public void setdownurl (string url) {this.downurl = url;} public string getdownurl () {return downurl;} // -------------------- ----------- Public void setClicks (int clicks) {thi S.Clicks = Click;} public int getClicks () {return clicks;} // ------------------------------- Public void setsort (string sort) {this.sort = sort;} public string getsort () {return sort;} // ----------------------- ---------------------------------------------- ----------------------------------------------------------------------------------------------------------- ------------------------ Public void setdate (String Date) {this.date = Date;} public string getdate () {return date;} / / ------------------------------ Public void setbad (int bag) {this.bad = Bad;} public int GetBad () {RETURN BAD;
} // ------------------------------ Public void setlength (int length) {this.length = length;} INT getLength () {RETURN Length;} spreadstSet {fun fun = new fun (); string string strign = null; int rtValue = 0; strign = rs.getstring ("id"); if (Strvalue! = null) Fun.setId (Strvalue); strval = rs.getstring ("funname"); if (strValue! = null) Fun.setFunname (strValue = rs.getstring ("viewurl); if (Strvalue! = null) Fun.setViewURL (Strvalue); strValue = rs.getstring ("downurl"); if (strValue! = null) Fun.setdownurl; intValue = rs.getint ("clicks"); if (INTVALUE> 0) Fun.setClicks (INTVALUE); Strvalue = rs.getstring ("sort"); if (strValue! = null) fun.setsort (strValue); / * try {reader reader = rs.getCharacterstream ("Intro "); BufferedReader bReader = new BufferedReader (reader); String inLine; strValue =" "; while ((inLine = bReader.readLine ())! = null) {strValue = strValue inLine;}} catch (Exception e) { E.PrintStackTrace ();} * / strval = rs.getstring ("intro"); if (strValue! = null) Fun.setIntro (Strvalue); intValue = rs .Getint ("commend"); if (intValue> 0) Fun.setcommend (intValue); strval = rs.getstring ("date"); if (strValue! = null) fun.setdate (strValue); intValue = rs. Getint ("Bad"); if (INTVALUE> 0) Fun.setbad (INTVALUE); INTVALUE = RS.GETINT ("Length"); if (INTVALUE> 0) Fun.setLength; Return Fun;}}
package vod.model; import org.gjt.mm.mysql.jdbc2.ResultSet; import java.sql.SQLException; import java.io.Reader; import java.io.BufferedReader; import java.io.Serializable; public class Movie implements Serializable {private String id; private String movieName; private String viewURL; private String downURL; private int clicks; private String sort; private String intro; private int commend; private String date; private int bad; private int length; // - ----------------------------- Public void setid (String ID) {this.id = id;} public string getId () { Return ID;} // ------------------------------- Public void setmoviename (string name) {this.Moviename = NAME PUBLIC STRING GETMOVIENAME () {Return Moviename;} // ------------------------------ Public void setViewURL (String URL) {this.viewURL = URL;} public string getViewURL () {Return viewURL;} // -------------------------------------------------------------------------------------------------------------------------------- --- Public void setdownurl (string url) {this.downurl = url;} public string getdownurl () {return downurl;} // -------------------- ----------- Public void setClicks (int ClickS) {this.clicks = clicks;} public int getClicks () {return clicks;} // ------------------------------------------------------------------------------------------------------------------------ --- Public void setsort (string sort) {this.sort = sort;} public string getsort () {Return Sort;} // -------------------- ----------- public void setIntro (string intro) {this.intro = intro;} public string getIntro () {Return INTRO;} // ------------ ------------------- Public void setcommend (int commend) {this.commend = Commend;} public int getcommend () {return commend;} // ---- --------------------------- Public void setdate (String Date) {this.date = Date;} public string getdate () {Return Date ;} // ------------------------------- public void setbad (int bag) {this.bad = BAD; Public int getbad () {return bad;
} // ------------------------------ Public void setlength (int length) {this.length = length;} int getLength () {return length;} public static Movie load (ResultSet rs) throws SQLException {Movie movie = new Movie (); String strValue = null; int intValue = 0; strValue = rs.getString ( "id"); if (Strvalue! = null) Movie.setId (Strvalue); Strvalue = rs.getstring ("moviename"); if (strValue! = null) Movie.seTmoviename (Strvalue = rs.getstring ("viewURL"); if (Strvalue! = null) Movie.setViewURL (Strvalue); strval = rs.getstring ("downurl"); if (strValue! = null) Movie.SetDownurl; intValue = rs.getint ("clicks"); if (INTVALUE> 0) Movie.setClicks (INTVALUE); strval = rs.getstring ("sort"); if (strValue! = null) Movie.setsort (Strvalue); / * try {reader reader = rs.getcharacTream ("Intro "); BufferedReader bReader = new BufferedReader (reader); String inLine; strValue =" "; while ((inLine = bReader.readLine ())! = null) {strValue = strValue inLine;}} catch (Exception e) { E.PrintStackTrace ();} * / strval = rs.getstring ("intro"); if (Strvalue! = null) Movie.setin TRO (STRVALUE); INTVALUE = rs.Getint ("commend"); if (intValue> 0) Movie.setcommend (intValue); strval = rs.getstring ("date"); if (strValue! = null) Movie.Setdate (strValue); INTVALUE = rs.getint ("BAD"); if (intValue> 0) Movie.setbad (intValue); intValue = rs.Getint ("Length"); if (INTVALUE> 0) Movie.setlength (intValue Return movie;}}
package vod.model; import org.gjt.mm.mysql.jdbc2.ResultSet; import java.sql.SQLException; import java.io.Reader; import java.io.BufferedReader; import java.io.Serializable; public class Mtv implements Serializable {private String id; private String mtvName; private String viewURL; private String downURL; private int clicks; private String sort; private String intro; private int commend; private String date; private int bad; private int length; // - ----------------------------- Public void setid (String ID) {this.id = id;} public string getId () { Return ID;} // ------------------------------- public void setmtvname (string name) {this.mtvname = name } public string getmtvname () {return mtvname;} // ------------------------------ Public void setViewURL (String URL) {this.viewURL = URL;} public string getViewURL () {Return viewURL;} // -------------------------------------------------------------------------------------------------------------------------------- --- Public void setdownurl (string url) {this.downurl = url;} public string getdownurl () {return downurl;} // -------------------- ----------- Public void setClicks (int clicks) {thi S.Clicks = Click;} public int getClicks () {return clicks;} // ------------------------------- Public void setsort (string sort) {this.sort = sort;} public string getsort () {return sort;} // ----------------------- ---------------------------------------------- ----------------------------------------------------------------------------------------------------------- ------------------------ Public void setdate (String Date) {this.date = Date;} public string getdate () {return date;} / / ------------------------------ Public void setbad (int bag) {this.bad = Bad;} public int GetBad () {RETURN BAD;
} // ------------------------------ Public void setlength (int length) {this.length = length;} INT getLength () {RETURN LENGTH;} public static mtv loading (Resultset RS) throws sqlexception {MTV MTV = new MTV (); string strign = NULL; int INT INTVALUE = 0; strValue = rs.getstring ("id"); if (Strvalue! = null) mtv.setid (Strval = rs.getstring ("mtvname"); if (Strvalue! = null) mtv.setmtvname (Strvalue = rs.getstring ("viewurl); if (Strvalue! = null) MTV.SetViewURL (STRVALUE); strValue = rs.getstring ("downurl"); if (strValue! = null) MTV.SetDownurl; intValue = rs.getint ("clicks"); if (INTVALUE> 0) MTV.SETCLICKS (INTVALUE); strValue = rs.getstring ("sort"); if (strValue! = null) mtv.setsort (Strvalue); / * try {reader reader = rs.getcharacTream ("Intro "); BufferedReader bReader = new BufferedReader (reader); String inLine; strValue =" "; while ((inLine = bReader.readLine ())! = null) {strValue = strValue inLine;}} catch (Exception e) { E.PrintStackTrace ();} * / strval = rs.getstring ("intro"); if (strValue! = null) mtv.setIntro (Strvalue); intValue = rs .Getint ("commend"); if (intValue> 0) mtv.setcommend (intValue); strval = rs.getstring ("date"); if (strValue! = null) mtv.setdate; intValue = rs. GetInt ("Bad"); IF (INTVALUE> 0) MTV.SetBad (INTVALUE); INTVALUE = rs.Getint ("Length"); if (INTVALUE> 0) mtv.setLength; return mtv;}}
(2) Establish a class named DisplayWelcome, this class's task is based on the four categories in the top ten of the four categories in the top ten entries, and returns the top of the LinkedList to return. Add it to the session in the relevant Action in Struts, which is convenient to display in the JSP page. Note that the LOAD method used here to just build the BEAN will return an instance of the same bean using the static method of this bean, and add it to the corresponding LinkedList. This is a instance of a bean with different data in the LinkedList, which can be taken out in the JSP page. code show as below:
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 Displaywelcome {Connection Conn (Connection Conn) {this.conn = conn;} / *** get the top ten data in the order (depending on ID number) * @Param conn * @ @@ return * @throws SQLException * / public LinkedList getFootballList () throws SQLException {LinkedList footballList; if (conn == null) throw new SQLException ( "No Connection in DisplayWelcomeAction"); PreparedStatement pstmt = null; ResultSet rs = null; footballList = new LinkedList (); try {// prepare the query SqlpStMt = conn.preparestatement ("Select * from football order by id desc"); // execute the query and copy the resultS // to a listrs = (Org.gjt.mm .mysql.jdbc2.resultset) PSTMT.ExecuteQuery (); int i = 0; while (rs.next () && i <10) {footballlist.add (football.load (RS)); i ;}} finally {if (rs! = null) rs.close (); if (pstmt! = null) PSTMT.Close ();} return footballlist;} / *** acquired the top ten data in the order (depending on ID number) * @Param conn * @ Return * @Throws SQLEXCEPTION * / Public LinkedList GetFunlist () THROWS SQLEXCEPTION {LinkedList Funlist; if (conn == null) throw new SQLException ( "No Connection in DisplayWelcomeAction"); PreparedStatement pstmt = null; ResultSet rs = null; funList = new LinkedList (); try {// Prepare the query SQLpstmt = conn.prepareStatement ( "select * from fun order by id "); // execute the query and copy the resultS // to a listrs = (org.gjt.mm.mysql.jdbc2.resultset) PSTMT.ExecuteQuery (); int i = 0; while (rs.next () && i <
10) {Funlist.add (Fun.Load (RS)); i ;}} finally {if (rs! = Null) rclose (); if (pstmt! = Null) PSTMT.Close ();} return funlist } / *** Acquired to join the top ten data in the order (dependent ID number) * @Param conn * @ Return * @Throws SQLEXCEPTION * / Public LinkedList getMovielist () THROWS SQLELIST; IF (conn == null) throw new SQLException ( "No Connection in DisplayWelcomeAction"); PreparedStatement pstmt = null; ResultSet rs = null; movieList = new LinkedList (); try {// Prepare the query SQLpstmt = conn.prepareStatement ( "select * from movie order BY ID DESC "); // execute the query and copy the resultS // to a listrs = (org.gjt.mm.mysql.jdbc2.resultset) PSTMT.ExecuteQuery (); int i = 0; while (rs.next () && i <10) {Movielist.add (Movie.Load (RS)); i ;}} finally {if (rs! = null) {ix (); if (pstmt! = null) PSTMT.Close );}} / *** acquired the top ten data in the order (depending on ID number) * @param conn * @ return * @Throws SQLEXCEPTION * / Public LinkedList GetMtvlist () THROWS SQLEXCEPTION {LinkedList MTVLIST; IF (conn == null) Throw new SQLEXCEPTION ("No Connection in Di splayWelcomeAction "); PreparedStatement pstmt = null; ResultSet rs = null; mtvList = new LinkedList (); try {// Prepare the query SQLpstmt = conn.prepareStatement (" select * from mtv order by id desc "); // Execute the Query and copy the resultS // to a listrs = (org.gjt.mm.mysql.jdbc2.resultset) PSTMT.ExecuteQuery (); int i = 0; while (rs.next () && i <10) {MTVLIST. Add (MTV.LOAD (RS)); i ;}} finally {if (rs! = null) rclose (); if (pstmt! = null) PSTMT.Close ();} return mtvlist;}
(3) Establish an action, the positioning of the page in Struts is completed by Action, and the Action controls the website program to process the user's request because of which BuinessBean is called. The Action of Action named: DisplayWelComeAction is created. This Action task is to accept the user's request, then call the database connection pool comes with Struts to get a connection, then set this database to set an instance of DisplayWelcome through SetConn (). After doing the corresponding getxxlist () method, you will get the corresponding LinkedList, add it to the session to make it easy to display the display of the content carrier JSP page. code show as below:
package vod.controller; import vod.model.DisplayWelcome; 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 DisplayWelcomeAction extends Action {Connection connection; LinkedList footballList; LinkedList funList; LinkedList movieList LinkedList mtvlist; / *** Accepted the top ten entry by VOD.MODEL.DISPLAYWECLOME 0, put it in Request * @P aram mapping * @param form * @param request * @param response * @ return * @throws IOException * @throws ServletException * / public ActionForward perform (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {ActionErrors errors = new ActionErrors (); try {DataSource dataSource = servlet.findDataSource (null); connection = dataSource.getConnection (); footballList = new LinkedList (); funList = new LinkedList (); movieList = new LinkedList (); mtvList = new LinkedList (); Displaywelcome Displaywelcome = new displaywelcome (); displaywelcome.setconn (connections); footballlist = displaywelcome.getfootballList (); funlist =
displaywelcome.getFunList (); movieList = displaywelcome.getMovieList (); mtvList = displaywelcome.getMtvList (); if (footballList == null) {saveErrors (request, errors); return (new ActionForward ( "No footballList in vod.controller. DisplayWelcomeAction "));} if (funList == null) {saveErrors (request, errors); return (new ActionForward (" No funList in vod.controller.DisplayWelcomeAction "));} if (movieList == null) {saveErrors ( request, errors); return (new ActionForward ( "No movieList in vod.controller.DisplayWelcomeAction"));} if (mtvList == null) {saveErrors (request, errors); return (new ActionForward ( "No mtvList in vod. controller.DisplayWelcomeAction "));} HttpSession session = request.getSession (); session.setAttribute (" footballTop ", footballList); session.setAttribute (" funTop ", funList); session.setAttribute (" movieTop ", movieList); Session.setttribute ("MTVTOP", MTVList); // do what you wish with myconnection} catch (sqlexception sqle) {getServlet (). log ("connection.process", sqle);} finally {// enclose this in A Finally B Lock to make // Sure the connection is closedif (Connection! = null) Try {connection.close ();} catches (SQLEXCEPTION E) {getServlet (). log ("Connection.Close", E);}} return Mapping.FindForward ("Success"));}} Configuration Struts: (1) The bean and the Action have been completed. Below we will configure the Struts related XML files, first open the web.xml file in JB, will The following is added to the web.xml file:
/ taglib-location> taglib>
XML Version = "1.0" Encoding = "ISO-8859-1">
/ global-forwards>
Action.xml Task is to specify the jump inside the action, and I have always think of this and struts-config.xml to repeat, don't understand the meaning of this Action.xml file, my comprehension is limited, Please advise.
Establish a JSP page
(1) Create a home page: Since the first page appears in front of the user contains a database read, because reading must be implemented through the functional call related beans through the Action call, here The role of the home page is to transit the user's request, jump to Welcome.jsp, and the transfer is responsible by an action and call the related bean read database in this action while jumping. code show as below:
<% @ Page ContentType = "Text / HTML; Charset = GB2312"%> <% @ page language = "java"%> <% @ Taglib URI = "/ Web-inf / struts-logic.tld" prefix = "logic "%>
<% @ 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 "%>