Java Learning Notes (2) parsing XML files----Web project __java

Source: Internet
Author: User
Tags java web


It is said that there are 3 ways to parse XML files in Java, but I am not one of them. A lot of information on the Internet, but most of them are done under Java project, I also resolved successfully. However, there are some differences between Java Web Engineering and Java Project Engineering created with Eclipse or myeclipse. One of the things is that there is no Webroot root directory under Java project Engineering, and Java Web Engineering has a webroot root directory, Java compiled class file is default placed under Web-inf/classes, This let me not know in ordinary class how to get the server root path, to know the server is not "WebRoot" This path, for this I am depressed for a long time. However, under the guidance of Pine brother, or solve the problem, in this express thanks.


Well, to start with, look at an XML file Mailconfig.xml:


<?xml version= "1.0" encoding= "UTF-8"?>
<content>
    <mail>
       <mailServerHost> smtp.163.com</mailserverhost>
       <mailServerPort>25</mailServerPort>
       <validate> true</validate>
       <userName>lindf123of@163.com</userName>
       <password>********* </password>
       <fromAddress>lindf123of@163.com</fromAddress>
    </mail>
</ Content>


The path that is located is as follows:




Start parsing the XML file, create a new Java class Xmlutil.java, and the code looks like this:

Package com.ldfsoft.util;
Import Java.io.File;

Import java.io.IOException;
Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;

Import javax.xml.parsers.ParserConfigurationException;
Import org.w3c.dom.Document;
Import org.w3c.dom.Element;
Import org.w3c.dom.NodeList;
Import org.xml.sax.SAXException;

Import Com.ldfsoft.dto.MailSenderDto;
	public class Xmlutil {private Mailsenderdto mailsenderinfodto; Public mailsenderdto getmailmess (String nodename,string fileName) {documentbuilderfactory documentbuilderfactory=
		Documentbuilderfactory.newinstance ();  String path = This.getclass (). getClassLoader (). GetResource ("xml"). GetPath ();
		Obtain the XML directory containing the Mailconfig.xml file Mailsenderinfodto=new mailsenderdto ();
			try {documentbuilder documentbuilder=documentbuilderfactory.newdocumentbuilder ();
			Document Document=documentbuilder.parse (path+file.separator+filename);
			NodeList Nodelist=document.getelementsbytagname (nodename); if (nodelist.getlength() >0) {element element= (Element) Nodelist.item (0); Mailsenderinfodto.setmailserverhost (Element.getelementsbytagname ("Mailserverhost"). Item (0). GetFirstChild ().
				Getnodevalue ()); Mailsenderinfodto.setmailserverport (Element.getelementsbytagname ("Mailserverport"). Item (0). GetFirstChild ().
				Getnodevalue ()); Mailsenderinfodto.setvalidate (Boolean.valueof (Element.getelementsbytagname ("Validate"). Item (0). Getfirstchild ()	. Getnodevalue ()); Note the Boolean-type method Mailsenderinfodto.setusername (Element.getelementsbytagname ("UserName"). Item (0).
				Getfirstchild (). Getnodevalue ()); Mailsenderinfodto.setpassword (Element.getelementsbytagname ("password"). Item (0). Getfirstchild (). Getnodevalue ())
				; Mailsenderinfodto.setfromaddress (Element.getelementsbytagname ("fromaddress"). Item (0). Getfirstchild ().	
			Getnodevalue ());
		The catch (Parserconfigurationexception e) {//TODO auto-generated catch block E.printstacktrace (); catch (Saxexception e) {//TODO auto-generated CAtch block E.printstacktrace ();
		catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
	return mailsenderinfodto;
 }

}

Mailsenderdto the DTO for the previous article (Java Learning Note (1)----send messages in Java), omitted in this article. The getmailmess (stringnodename,string fileName) in this class has two parameters, where nodename is the node name and filename is the file name of the XML file. Encapsulates the acquired data into an instance of Mailsenderdto and returns.

We then replace this method for the class in the previous article with the following form in the Javautil.java class, and some of the code looks like this:

/** * Send activation account email/public void SendEmail (String email) {Mailsenderdto=xmlutil.getmailmess ("mail"),
       "Mailconfig.xml");
             try{String mailtitle= "My network Disk" account activation Mail "; stringmailcontent= "<br><br> Dear" My network Disk "user:<br><br>" + "   & Hello, nbsp. Thank you for registering "My network Disk" account number, click the link below to complete the registration:<br><br> "+"     <ahref=\ "http:/ /localhost:9080/mydisk/swf/activateemail.html#email= "+email+" \ ">http://localhost:9080/mydisk/swf/ Activateemail.html#email= "+email+" </a><br><br> "+"      (such as The link can not be clicked, please copy and paste it into the browser's address bar to access the <br><br> "+"      your email: "+email+" & Lt;br><br> "+"     email can be your account to log in to "My network disk." <br><br> "+"      this message is automatically sent by the system, please do not return directlyComplex. Thank you for your visit, I wish you a happy use.
          
             <br><br> ";      mailsenderdto.settoaddress (email);    Recipient email Address mailsenderdto.setsubject (mailtitle);  Mail Header mailsenderdto.setcontent (mailcontent);  
             Mail content//This class is mainly used to send mail mailsender ms = new MailSender (); Ms.sendhtmlmail (mailsenderdto)//Send HTML format System.out.println ("---------------sent successfully.
       "); }catch (Exception e) {System.out.println ("failed.")
       ");   }
    }

After testing, it is the same effect. Only this greatly reduces the Send mail property and code coupling, easy to manage. In fact, I learned how to parse XML files.


This is the result of my study, allow reprint, welcome to Exchange, but reprint must give the link address of this article: http://blog.csdn.net/youqishini/article/details/7906571, thank you ~

Related Article

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.