DOM4J reads XML configuration files for database connection

Source: Internet
Author: User
This section describes DOM4J. It is said that JavaXMLAPI (Dom4jisaneasytouse, opensourcelibraryforworkingwithXML, xpathand~tonthejavaplatformusingthejavacollectionsframeworkandwithfullsupportfordom, SAXandJAXP.

This section describes DOM4J. It is said that it is an excellent and excellent Java xml api (Dom4j is an easy to use, open source library for working with XML, XPath and XSLT on the Java platform using the Java Collections Framework and with full support for DOM, SAX and JAXP.

This section describes DOM4J.

It is said that it is an excellent and excellent Java xml api (Dom4j is an easy to use, open source library for working with XML, XPath and XSLT on the Java platform using the Java Collections Framework and with full support for DOM, SAX and JAXP .).

About XML files.

A asked me A question: why does XML in java be used as A configuration file? Such as text files.

My first reaction was to eat anything for (feed... And then ask why... At the beginning, I imitated it and thought about it for a long time.

Take a test of some frequently used things, just like why the same company has a higher position than me... What we need is thinking and learning...

Let's talk about the features of our configuration file: the configuration file here needs to be able to store a small amount of data and be easy to operate and maintain. Therefore

At the beginning of the selection, the text features and encoding issues will be considered comprehensively. Therefore, XML will be taken into consideration as a j2ee standard.

Instead of text as the j2ee standard. (Only my understanding ......)

The method for connecting to the database at the beginning:

/*** Get connection * @ return **/public static Connection getConnection () throws ClassNotFoundException {// database connection object. Connection conn = null; try {// driver name. Class. forName ("oracle. jdbc. driver. OracleDriver"); // database connection string. String url = "jdbc: oracle: thin: @ localhost: 1521: BJPOWERNODE"; // the username and password of the oracle database. String username = "drp"; String password = "drp"; // connect to the database. Conn = DriverManager. getConnection (url, username, password);} catch (ClassNotFoundException e) {// print the error. E. printStackTrace ();} catch (SQLException e) {// print the error. E. printStackTrace () ;}// return the connection object. Return conn ;}


Some optimizations were made.:

We put some configuration files for connecting data into XML files. Obviously, we are doing this for convenience. From the perspective of change

Prediction problems, so we put the initial configuration data in the Code for connecting to the Database Class, extracted it, and put it in the configuration file.

The connection configuration information is stored in web. xml.

 
 
  
   
    oracle.jdbc.driver.OracleDriver
   
   
    jdbc:oracle:thin:@localhost:1521:BJPOWERNODE
   
   
    drp
   
   
    drp
   
  
 


In this way, we will read some driver names, connection strings, user names, and password information from this XML file.

If we place the read and connection in the connection class (DbUtil database operation tool class), this class has too many responsibilities, which is not conducive

Expansion of large systems. Therefore, we gave the configuration file read to a dedicated class to do this, and we named it

XmlConfigReader, which reads XML files.

Find articles about reading XML files from the Internet, the source code is also a lot, it is said that there are four ways, http://developer.51cto.com/art/201106/270685.htm here is not detailed description. Here we use DOM4j to read XML files. It is mainly to introduce the corresponding dom4j package and view the dom4j API during use.

To read the configuration file, we read the string, driver name, connection string, user name, and password information. They are a whole

If the return value of the number is a string, it is inconvenient to separate the long string when connecting to the database. So we put them

After encapsulation, we encapsulate them into a configuration tool class, JdbcConfig, so that we can pass a whole. Just like a person is

We should not separate his arm and legs.

Our encapsulatedConfiguration File entity class:

/*** Jdbc configuration information. * @ Author lovesummer **/public class JdbcConfig {// connection string. Private String url; // user name. Private String userName; // password. Private String password; // The name of the drive. Private String driverName; public String getDriverName () {return driverName;} public void setDriverName (String driverName) {this. driverName = driverName;} public String getUrl () {return url;} public void setUrl (String url) {this. url = url;} public String getUserName () {return userName;} public void setUserName (String userName) {this. userName = userName;} public String getPassword () {return password;} publi C void setPassword (String password) {this. password = password;} // overwrite the toString method of the object. @ Overridepublic String toString () {// TODO Auto-generated method stubreturn this. getClass (). getName () + "{driverName:" + driverName + ", url:" + url + ", userName:" + userName + "}";}}


WeRead configuration filesClass:

Package com. bjpowernode. drp. util; import java. io. inputStream; import javax. servlet. jsp. tagext. tryCatchFinally; import org. dom4j. document; import org. dom4j. extends entexception; import org. dom4j. element; import org. dom4j. io. SAXReader; // read the configuration file class. /*** Resolve the sys-config.xml file in singleton mode. * Parse the sys-config.xml file. * @ Author lovesummer **/public class XmlConfigReader {// qinghan style. // Private Static member variables. Private static XmlConfigReader instance = new XmlConfigReader (); // Save the jdbc-related configuration information object. Private JdbcConfig jdbcconfig = new JdbcConfig (); // private constructor. Private XmlConfigReader () {SAXReader reader = new SAXReader (); // get the current thread. InputStream in = Thread. currentThread (). getContextClassLoader (). getResourceAsStream ("sys-config.xml"); try {Document doc = reader. read (in); // get the Element in xml. 1. Retrieve the drive name. Element driverNameElt = (Element) doc. selectObject ("/config/db-info/driver-name"); // 2. Retrieve the url string. Element urlElt = (Element) doc. selectObject ("/config/db-info/url"); // 3. Retrieve the user name and password. Element userNameElt = (Element) doc. selectObject ("/config/db-info/user-name"); Element passwordElt = (Element) doc. selectObject ("/config/db-info/password"); // obtain jdbc-related configuration information. Jdbcconfig. setDriverName (driverNameElt. getStringValue (); jdbcconfig. setUrl (urlElt. getStringValue (); jdbcconfig. setUserName (userNameElt. getStringValue (); jdbcconfig. setPassword (passwordElt. getStringValue ();} catch (incluentexception e) {// print error e. printStackTrace () ;}// public static entry method. Public static XmlConfigReader getInstance () {return instance;}/*** return jdbc-related configuration. * @ Return */public JdbcConfig getJdbcConfig () {return jdbcconfig ;}}


After optimization, weDatabase Connection class(Like China before and after reform and opening up ):

/*** Encapsulate common database operations, tool class * @ author lovesummer **/public class DbUtil {/*** get connection * @ return **/public static Connection getConnection () throws ClassNotFoundException {Connection conn = null; try {// create a jdbc configuration class. JdbcConfig jdbcconfig = XmlConfigReader. getInstance (). getJdbcConfig (); // retrieve the drive name. Class. forName (jdbcconfig. getDriverName (); // gets the connection object. Conn = DriverManager. getConnection (jdbcconfig. getUrl (), jdbcconfig. getUserName (), jdbcconfig. getPassword ();} catch (ClassNotFoundException e) {// throw tione. printStackTrace ();} catch (SQLException e) {e. printStackTrace () ;}return conn ;}// test. Public static void main (String [] args) throws ClassNotFoundException {System. out. println (DbUtil. getConnection ());}}


After optimization, the division of responsibilities of each class is clearly defined. On this basis, optimization can be performed again. I will not talk about it here. In this process, I learned

This thinking method of code optimization is loaded with the programmer's idea, and the code has a soul step by step... come on .....

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.