|
|
|
Java/JSP การสร้างคลาส เพื่อรับค่า จากไฟล์ xml เพื่อจะนำค่าเหล่านั้นไปใช้ในการติดต่อดาต้าเบส |
|
|
|
|
|
|
|
ReadXMLFile.java
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
/**
*
* @author Administrator
*/
public class ReadXMLFile {
public String db_host;
public String db_name;
public String db_port;
public String db_user;
public String db_pass;
public String getDBHost(){
return db_host;
}
public String getDBName(){
return db_name;
}
public String getDBPort(){
return db_port;
}
public String getDBUser(){
return db_user;
}
public String getDBPass(){
return db_pass;
}
public void setDBConfig(String db_id) {
try {
File fXmlFile = new File("/WEB-INF/configuration/applicationconfig.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("database");
boolean falg=true;
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
if (eElement.getAttribute("id").equalsIgnoreCase(db_id)) {
db_host = eElement.getElementsByTagName("host").item(0).getTextContent();
db_name = eElement.getElementsByTagName("name").item(0).getTextContent();
db_port = eElement.getElementsByTagName("port").item(0).getTextContent();
db_user = eElement.getElementsByTagName("username").item(0).getTextContent();
db_pass = eElement.getElementsByTagName("password").item(0).getTextContent();
falg = false;
break;
}
}
}
if(falg)throw new Exception("NOT Found: " + db_id);
} catch (Exception e) {
}
}
}
สมมุติว่าผมทำคลาสนี้เสร็จแล้ว เวลาผมจะเรียกใช้ค่า (เอาไปปริ้นหน้า jsp )host,name,port,username,password ยังไงครับ
|
|
|
|
|
Date :
2013-06-07 13:01:32 |
By :
s_007 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ประกาศ Class แบบ Constructors ครับ
Code (Java)
public class ReadXMLFile {
string m_host;
string m_name;
string m_port;
string m_username;
string m_password;
public ReadXMLFile(string host,string name,string port,string username,string password)
{
m_host = host;
m_name = name;
m_port = port;
m_username = username;
m_password = password;
}
...
..
}
เรียกใช้
Code (Java)
ReadXMLFile cls = new ReadXMLFile(a,b,c,d,e);
|
|
|
|
|
Date :
2013-06-07 13:18:06 |
By :
mr.win |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Load balance : Server 04
|