Struts Principles and Practice (3) Author: Luokuai Bo issued a document time: 2004.08.05
First, the working principle of JDBC Struts is in nature is a Java program. To access the database in the Struts application, first, you must understand the working principle of Java Database Connectivity API (JDBC). As its name is revealed, the JDBC library provides a bottom API to support basic SQL features independent of any particular SQL implementation. Provide basic functions for database access. It is a class and interface that extracts the public concepts accessed by various databases. JDBC API includes two packages: java.sql (called JDBC kernel API) and Javax.sql (called JDBC standard extension). They together contain the classes needed to develop database applications with Java. These classes or interfaces include: java.sql.driverManagerjava.sql.driverjava.sql.connectionjava.sql.StatementJava.sql.preparedStateMentJava.sql.ResultSet, etc. This makes it easier to send SQL statements from Java programs to the database, and suitable for All SQL dialects. That is to say, if a database is like Oracle, it is necessary to rewrite it again for MS SQL Server. But you can use the same Java application for a variety of database systems. In this way, everyone may have some unacceptable, we can make a better than one side: the United Nations meeting, the United Nations Member States' participants (quite our specific database management systems) often have their own language (dialect). The General Assembly spokesman (equivalent to the Java application here) is impossible to speak in various languages. You only need to use a language (equivalent to our JDBC) to speak. So how to ensure that the participants of each member understand the statement, which is to rely on the same voice (equivalent to the JDBC driver we here). In fact, the driver translates the SQL statement in the Java program into a specific database energy execution, and then performs the corresponding database management system. Therefore, when using the JDBC API to access the database, we have to use different drivers for different databases. The driver is actually a specific implementation of a specific database JDBC interface. They generally have the following three functions: establish a data source Connection Send SQL statement to the data source to retrieve the result set, how is JDBC work? Java.sql.driverManager load driver, when java.sql.driverManager's getConnection () method is called, DriverManager is trying to find a URL for the database (or a form of data source) in the registered driver. The driver, and transmits the URL of the database to the acceptsURL () method of the driver, the driver confirms that you have the ability to connect to the URL. The generated connection Connection represents a session with a particular database. Statement (including PreparedStatement and CallableState "objects act as a container for executing SQL statements on a given connection. After performing the character sentence, generate the ResultSet result set object, and the data in the table can be accessed through a series of getter of the result set. Here, it is the basic working process of JDBC, in practical applications, often use JDBC extension objects such as DataSource, etc., is limited to the space, and it is not discussed in detail. Second, the basic configuration to access the database is to access the MS SQL Server2000 database as an example to introduce the basic configuration.
First, go to the Microsoft website to download the JDBC driver, running setup.exe will get three files: msbase.jar, mssqlser.jar and msutil.jar Place the / WebApps / mystruts / web-inf / lib directory.
Configure data sources in struts-config.xml files
Here, there is a point to causing everyone to pay attention, that is, the various items configured in Struts-Config.xml have certain order requirements, and the order of several major projects is roughly like this:
Data-Sources
Form-beans
Action-mapings
Message-resources
Plug-in
Comply with the above order when configuring
Value = "com.microsoft.jdbc.sqlserver.sqlserdriver" /> Value = "JDBC: Microsoft: SQLSERVER: //127.0.0.1: 1433; DatabaseName = mystruts; selectmethod = cursor" /> data-source> data-sources> Let's make a simple description of this configuration code: In this sentence, if you only configure only one data source in your Struts application, Key = "a" can be used to use this key value when configuring multiple data sources, that is, can be configured for an application. Multiple data sources allow it to access multiple databases. Value = "JDBC: Microsoft: SQLSERVER: //127.0.0.1: 1433; DatabaseName = mystruts; SelectMethod = CURSOR "/> SQL Server: //127.0.0.1: 1433 in this sentence; database server name (this example is the IP address representing the native) and the database name is the same as your specific situation. At the same time, pay attention to the username and password of the access to the database must also be in touch with your actual situation. Indicates the maximum number of active connections, which also shows that these connections are pooling. Indicates that the database is increased, deleted, and the modified operation must be explicitly submitted. That is, connect.commit () must be used; such a command can really change the record in the database table. Set to this convenient user organize its own database transactions. Third, now we will expand the example of the login we talked before, let it access the username and password information stored in the database table, but also make the error information given more clearly. To this end, we must do some preparations, if you haven't installed MS SQL Server2000, please install, and download the latest patch package. Built a database called MyStruts and build a table named userInfo in the database, which is both fields: username and password, their field types are varchar (10), where username is the primary key. In this table, enter a record, the field values of username and password are LHB and AWAVE, respectively. It is basically done in this preparation. In order to access the database, first, to modify the Action class, the modified code list is as follows: Package action; Import java.io.ioException; 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.Actionerro; 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 bussness.userInfobo; Import entity.userinfoform; Import javax.sql.datasource; Import java.sql.connection; Import java.sql.sqlexception; Public Final Class LogonAction Extends Action { Public ActionForward Execute (ActionMapping Mapping, Actionform Form, HTTPSERVLETREQUEST REQUEST, Httpservletresponse response THROWS IOException, servletexception { UserInfoform UserInfoform = (userInfoform) form; / / Get username and password from the web layer String username = userinfoform.getusername (). Trim (); string password = userinfoform.getpassword (). Trim (); // Statement error set object ActionerroS Errors = new actionerrors (); // Declare data source and connection object DataSource DataSource; CONNECTION CNN = NULL; // Verify input IF (username.equals (")) { ActionError Error = New Actionerror ("Error.Missing.userName); Errors.Add (ActionerRors.global_Error, Error); } IF (Password.equals (")) { ActionError Error = New Actionerror ("Error.Missing.Password"); Errors.Add (ActionerRors.global_Error, Error); } // Call business logic IF (errors.size () == 0) { String validated = "" Try { // obtain database connection DataSource = getDataSource (Request, "a"); CNN = DataSource.getConnection (); UserInfobo UserInfobo = New UserInfobo (CNN); Validated = UserInfobo.validatePwd (username, password); IF (Validated.equals ("Match")) { // All the user information is saved and turned to the successful page HttpSession session = request.getations (); Session.setttribute ("UserInfoForm", FORM); Return mapping.findforward ("Success"); } } Catch (throwable e) { // Process possible errors E.PrintStackTrace (); Actionerror Error = New ActionError (E.getMessage ()); Errors.Add (ActionerRors.global_Error, Error); } } // Turn to the input page as an error, and display the corresponding error message SaveerRors (Request, Errors); Return New ActionForward (mapping.getinput ()); } } Note: DataSource = getDataSource (Request, "A"); this sentence, if there is only one data source in the configuration, and there is no key = "a", this sentence should be written as DataSource = getDataSource (request); As can be seen from the list, it is mainly to increase the code of the access database. At the same time, our business object has also changed a change, there is no parameters, and now there is a parameter CNN representing the database connection, so we must also modify the business object. The list of business objects after the change is as follows: Package bussness; Import entity.userinfoform; Import java.sql.connection; Import java.sql.sqlexception; Import java.lang.exception; Import DB.USERINFODAO; Public class usrinfobo { PRIVATE CONNECTION CNN = NULL; Public UserInfobo (Connection CNN) { THIS.CNN = CNN; } Public String ValidatePwd (String UserName, String Password) { String validateresult = "" Try { Userinfodao userinfodao = new userinfodao (cnn); Validateresult = UserInfodao.ValidatePwd (username, password); ValidateResult.equals ("Error.logon.invalid")) { // If the username is not matched with the password, Throw new runtimeException ("error.logon.invalid); } Else IF (ValidateResult.equals ("Error.Removed.user")) { // If you can't find a user, let's report this fault, so that the error message you see will be more detailed. Throw new runtimeException ("Error.Removed.user"); } } Catch (Exception E) { Throw new runtimeException (E.GetMessage ()); } Finally { Try { IF (CNN! = null) { CNN.Close (); } } Catch (SQLException SQLE) { Sqle.printStackTrace (); Throw new runtimeException ("error.unexpected"); } } Return validateresult; } } The code of this business object is also relatively simple, and the focus is to call an object called UserInFodao in the ValidatePwD method, which is the data access object that actually performs database operations. The list of code is as follows: Package DB; Import entity.userinfoform; Import java.sql. *; Public class usrinfodao { PRIVATE CONNECTION CON; Public userinfodao (connection con) { THIS.CON = con; } Public String ValidatePwd (String UserName, String Password) { PreparedStatement PS = NULL; ResultSet RS = NULL; String Validated = "Error.logon.invalid"; UserInfoform UserInfoform = NULL; String SQL = "SELECT * from userinfo where username =?"; Try { IF (con?isclosed ()) { Throw New IllegalStateException ("Error.unexpected"); } PS = con.preparestatement (SQL); ps.setstring (1, username); RS = ps.executeQuery (); IF (rs.next ()) { IF (! rs.getstring ("password"). Trim (). Equals (password)) { Return Validated; // Password is incorrect return password does not match information } Else { Validated = "match"; // password correctly returns the password matching information Return validated; } } else { Validated = "error.removed.user"; // Nothing to find the user Return validated; } } catch (sqlexception e) { E.PrintStackTrace (); Throw new runtimeException ("error.unexpected"); } finally { Try { IF (PS! = NULL) ps.close (); IF (rs! = null) Rs.close (); } catch (sqlexception e) { E.PrintStackTrace (); Throw new runtimeException ("error.unexpected"); } } } } Next, simply analyze the work of data access objects: To access the database, you generally have to experience the following steps: Get a connection to the database Create a SQL statement to perform the SQL statement management result set, getting the database connection this example is done in the Action class, the code is as follows: Datasource = getDataSource (Request, "a"); cnn = DataSource.getConnection (); Action transmits the connection as a parameter to the business object when the business object is called, and then pass the service object to the database access object. To illustrate a little, you have to put the struts-legacy.jar file. / WebApps / MyStruts / Web-INF / LIB directory. We have to The / WebApps / MyStruts / Web-INF / CLASSES directory built a subdirectory named DB, saved the data access class in the subdirectory in the subscriberinFodaoFodao.java file name. Compile the .java file in each package according to the method introduced in the article. You can start Tomcat to re-run your program. Careful readers may notice, so far, the various news in our program is not expressed in Chinese. In the next article, we will discuss the Struts's international programming, the so-called I18N programming, for us The problem that is often encountered in programming is also analyzed. references: "JSP Web Programming Guide" - Electronics Industry Press, Jayson Falkner, etc. "Java database programming book" John O'Donahue is waiting to translate " "Struts in action" TED husted CEDRIC DUMOULIN George Franciscus David Winterfeldt "Programming Jakarta Struts" Chuck Cavass "Mastering Jakarta Struts" James Goodwill "Struts Kick Start" James Turner Kevin Bedell Author: Luo Kuaibo Dangyang IRS Information Center can contact him by lhbf@sina.com