Monday, September 21, 2015

Bài tập IXJ - Import XML to WebApplication

Trong bài này chúng ta sẽ upload file XML có mẫu qui định trước lên web server và rút trích dữ liệu đề đưa vào SQL server.
Nội dung mẫu XML
[sourcecode language="xml"]
<emplist>
<emp status="off">
<id>1</id>
<name>Been</name>
</emp>
<emp status="on">
<id>2</id>
<name>Andrew</name>
</emp>
</emplist>
[/sourcecode]

Tạo một web site, sử dụng JSF 2.2
Tạo managebean như sau:
[sourcecode language="java"]
package codes;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.Part;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
*
* @author ntdan
*/
@ManagedBean
@RequestScoped
public class FileUploadBean {

private Part file;
private String fileName = "";

/**
* Creates a new instance of FileUploadBean
*/
public FileUploadBean() {
}

public Part getFile() {
return file;
}

public void setFile(Part file) {
this.file = file;
}

public String upload() {
try {
fileName = file.getSubmittedFileName() + " "
+ file.getSize() + " bytes";
String filePath = FacesContext.getCurrentInstance().getExternalContext()
.getRealPath("/upload") + "/" + file.getSubmittedFileName();
// luu file
file.write(filePath);
// luu du lieu
importXML(filePath);
} catch (Exception ex) {
System.out.println(ex.toString());
}
return "index";
}

public String getFileName() {
return fileName;
}

public void setFileName(String fileName) {
this.fileName = fileName;
}

private void importXML(String filename) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("jdbc:sqlserver://172.16.160.54\\sql2008;database=northwind;user=sa;password=sa;");
PreparedStatement comm = conn.prepareStatement("insert into Employees(FirstName,LastName) values(?,?)");

DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
DocumentBuilder db = fac.newDocumentBuilder();
Document doc = db.parse(new File(filename));

NodeList list = doc.getElementsByTagName("emp");
int pos = 0;
while (pos < list.getLength()) {
NodeList emp = list.item(pos).getChildNodes();
comm.setString(1, emp.item(3).getTextContent());
comm.setString(2, "L_" + emp.item(3).getTextContent());
// them du lieu
comm.executeUpdate();
pos++;
}

fileName += "\n" + pos +" rows added!";
} catch (ClassNotFoundException ex) {
Logger.getLogger(FileUploadBean.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(FileUploadBean.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(FileUploadBean.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(FileUploadBean.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FileUploadBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
[/sourcecode]

Hiệu chỉnh lại trang index.xhtml
[sourcecode language="html"]
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Upload</title>
</h:head>
<h:body>
<f:view>
<h:form enctype="multipart/form-data">
<h:inputFile value="#{fileUploadBean.file}"/>
<h:commandButton value="Upload"
action="#{fileUploadBean.upload()}"/><br/>
File: <h:outputText value="#{fileUploadBean.fileName}"/>
</h:form>
</f:view>
</h:body>
</html>
[/sourcecode]

Chạy trang index.xhtml --> chọn file emp.xml chứa nội dung và nhấn Upload chúng ta có giao diện như sau:
Snap 2015-09-21 at 15.16.34

Mã nguồn tham khảo -->> ở đây

OK vậy là chúng ta đã import nội dung XML vào csdl.

No comments:

Post a Comment

Translate