Upload file đơn giản với JSF 2.2


JSF (Java Server Face) 2.2 bổ sung thêm thẻ inputFile cho phép upload file lên server web trở nên đơn giản hơn bao giờ hết.

1. Tạo Website sử dụng JSF 2.2
2. Tạo managebean như sau:

package codes;
import java.io.IOException;
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;
/**
 *
 * @author ntdan
 */
@ManagedBean
@RequestScoped
public class Upload_File {

    private Part file;
    private String fileName;
    private long fileSize;
    
    /**
     * Creates a new instance of Upload_File
     */
    public Upload_File() {
    }

    public Part getFile() {
        return file;
    }

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

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    
    public String upload()
    {
        try {
            // get name of selected file
            fileName = file.getSubmittedFileName();
            // get file's size
            fileSize = file.getSize();
            // get fullpath of opload folder in web root
            String dirPath= FacesContext.getCurrentInstance().getExternalContext().getRealPath("/upload");
            // write file to upload folder
            file.write(dirPath + "/" + fileName);
            
        } catch (IOException ex) {
            Logger.getLogger(Upload_File.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return "view";
    }

    public long getFileSize() {
        return fileSize;
    }

    public void setFileSize(long fileSize) {
        this.fileSize = fileSize;
    }
}

3. Tạo trang index.xhtml để upload file như sau:

<?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>Facelet Title</title>
    </h:head>
    <h:body>
        Demo for upload file
        <f:view>
            <h:form enctype="multipart/form-data">
                File:<br/>
                <h:inputFile value="#{upload_File.file}"/>
                <br/>
                <h:commandButton value="Upload" action="#{upload_File.upload()}"/>
                <br/>
                File:${upload_File.fileName} - #{upload_File.fileSize} bytes !
            </h:form>

        </f:view>

    </h:body>
</html>

4. Tạo trang xem ảnh vừa upload và thông tin về hình

<?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>Facelet Title</title>
    </h:head>
    <h:body>
        <f:view>
            <br/>
                File:${upload_File.fileName} - #{upload_File.fileSize} bytes !
                <br/>
            <h:graphicImage url="/upload/#{upload_File.fileName}" width="400px"/>
        </f:view>

    </h:body>
</html>

OK, chạy trang index.xhtml –> chonj file upload hệ thống sẽ chuyển qua trang view.xhtml để xem ảnh vừa upload.

Advertisements

Bài tập IXJ – Object/ Object List to XML File and XML File to Object/ Object List


Trong bài tập này chúng ta sẽ chuyển đổi qua lại giữa XML và List<Object>. Bài tập chuyển từ Object <-> XML

Ví dụ danh sách chứa các Emp như sau:

Emp emp = new Emp();
emp.setCode("A001");
emp.setName("Nguyen Van Mit");
emp.setAddress("Can Tho");
emp.setTel("+8499999999");

Emp emp1 = new Emp();
emp1.setCode("A002");
emp1.setName("Tran Van Cam");
emp1.setAddress("Can Tho");
emp1.setTel("+848888888");

List<Emp> emplist = new ArrayList<Emp>();
emplist.add(emp);
emplist.add(emp1);

Sẽ được chuyển thành file XML có nội dung như sau:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<emplist>
    <emp code="A001">
        <address>Can Tho</address>
        <name>Nguyen Van Mit</name>
        <tel>+8499999999</tel>
    </emp>
    <emp code="A002">
        <address>Can Tho</address>
        <name>Tran Van Cam</name>
        <tel>+848888888</tel>
    </emp>
</emplist>

Để thực thực việc chuyển đổi này chúng ta sử dụng thư viện JAXB của Java.
1. Tạo lớp Emp

package jaxb_object_list;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
//the goc
@XmlRootElement(name = "emp")
public class Emp {
    private String code;
    private String name;
    private String address;
    private String tel;
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getCode() {
        return code;
    }
    @XmlAttribute
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getTel() {
        return tel;
    }    
    public void setTel(String tel) {
        this.tel = tel;
    }

    @Override
    public String toString() {
        return "Emp [code:" + code + ", name:" + name + ", address:"
                + address + ", tel:" + tel + "]";
    }
}

2. EmpList

package jaxb_object_list;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
// cac thuoc tinh duoc luu duoi dang the
@XmlAccessorType(XmlAccessType.FIELD)
// the goc
@XmlRootElement(name = "emplist")
public class EmpList {
    // moi phan tu trong danh sach luu thanh the emp
    // cau truc the emp mo ta qua lop Emp
    @XmlElement(name = "emp", type = Emp.class)
    private List<Emp> emplist = new ArrayList<Emp>();
    public EmpList() {}
    public EmpList(List<Emp> emplist) {
        this.emplist = emplist;
    }
    public List<Emp> getEmpList() {
        return emplist;
    }
    public void setEmpList(List<Emp> emplist) {
        this.emplist = emplist;
    }   
}

3. Tạo 2 phương thức để chuyển đổi

// chuyen ds doi tuong thanh xml
public static void marshal(List<Emp> emplist, File selectedFile)
        throws IOException, JAXBException {
    JAXBContext context;
    BufferedWriter writer = null;
    writer = new BufferedWriter(new FileWriter(selectedFile));
    context = JAXBContext.newInstance(EmpList.class);
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(new EmpList(emplist), writer);
    writer.close();
}

// chuyen XML thanh danh sach doi tuong
public static List<Emp> unmarshal(File importFile) throws JAXBException {
    EmpList empList = new EmpList();
    JAXBContext context = JAXBContext.newInstance(EmpList.class);
    Unmarshaller um = context.createUnmarshaller();
    empList = (EmpList) um.unmarshal(importFile);
    return empList.getEmpList();
}

4. Test

public static void main(String[] args) {
    Emp emp = new Emp();
    emp.setCode("A001");
    emp.setName("Nguyen Van Mit");
    emp.setAddress("Can Tho");
    emp.setTel("+8499999999");

    Emp emp1 = new Emp();
    emp1.setCode("A002");
    emp1.setName("Tran Van Cam");
    emp1.setAddress("Can Tho");
    emp1.setTel("+848888888");

    List<Emp> emplist = new ArrayList<Emp>();
    emplist.add(emp);
    emplist.add(emp1);
    //Marshalling: ghi ds doi tuong ra file xml
    try {
        JAXBXMLHandler.marshal(emplist, new File("src/jaxb_object_list/EmpList.xml"));
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    }

    try {
        // khoi tao ds tu XML
        emplist = JAXBXMLHandler.unmarshal(new File("src/jaxb_object_list/EmpList.xml"));
    } catch (JAXBException e) {
        e.printStackTrace();
    }
    System.out.println(emplist);
}

Tới đây chạy ứng dụng chúng ta sẽ có file xml sinh ra và mẫu in ra của sổ output

[Emp [code:A001, name:Nguyen Van Mit, address:Can Tho, tel:+8499999999], Emp [code:A002, name:Tran Van Cam, address:Can Tho, tel:+848888888]]

Mã nguồn tham khảo tại đây

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

<emplist>
    <emp status="off">
        <id>1</id>
        <name>Been</name>
    </emp>
    <emp status="on">
        <id>2</id>
        <name>Andrew</name>
    </emp>
</emplist>

Tạo một web site, sử dụng JSF 2.2
Tạo managebean như sau:

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);
        }
    }
}

Hiệu chỉnh lại trang index.xhtml

<?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>

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.

Bài tập IXJ – FO sử dụng Apache FOP chuyển XML sang PDF


XSL-FO (XSL Formatting Objects) chuyển đổi dữ liệu XML sang các định dạng khác.
XSL - FO
Trong bài thực hành này chúng ta sẽ sử dụng thư viện FOP của Apache tích hợp vào chương trình Java để chuyển tài liệu XML chứa CustomerOrders mua sản phẩm sang biểu mẩu PDF.

CustomerOrders

Snap 2015-09-21 at 13.34.42

Các thư viện hỗ trợ –>> đây

Mã nguồn tham khảo như sau:

package fop_ex;
import java.io.File;
import java.io.OutputStream;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;
public class FOP_EX {
    public static void main(String[] args) {
        try {
            // Setup directories
            File baseDir = new File(".");
            File outDir = new File(baseDir, "src/out");
            outDir.mkdirs();
            // Setup input and output files
            File xmlfile = new File(baseDir, "src/xml/CustomerOrders.xml");
            File xsltfile = new File(baseDir, "src/xslt/Customer_fo.xsl");
            File pdffile = new File(outDir, "CustomerOrders.pdf");
            // configure fopFactory as desired
            final FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
            // configure foUserAgent as desired
            FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
            // Setup output
            OutputStream out = new java.io.FileOutputStream(pdffile);
            out = new java.io.BufferedOutputStream(out);
            try {
                // Construct fop with desired output format
                Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
                // Setup XSLT
                TransformerFactory factory = TransformerFactory.newInstance();
                Transformer transformer = factory.newTransformer(new StreamSource(xsltfile));
                // Set the value of a <param> in the stylesheet
                transformer.setParameter("author", "Nguyen Van Mit");
                // Setup input for XSLT transformation
                Source src = new StreamSource(xmlfile);
                // Resulting SAX events (the generated FO) must be piped through to FOP
                Result res = new SAXResult(fop.getDefaultHandler());
                // Start XSLT transformation and FOP processing
                transformer.transform(src, res);
            } finally {
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }
}

File XSL-FO như sau:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.1" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" exclude-result-prefixes="fo">
    <xsl:output method="xml" version="1.0" omit-xml-declaration="no" indent="yes"/>
    <xsl:param name="author" select="'Tran Van Cam'"/> 
    <xsl:template match="customers">
        <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
            <fo:layout-master-set>
                <fo:simple-page-master master-name="simpleA4" page-height="29.7cm" page-width="21cm" margin-top="2cm" margin-bottom="2cm" margin-left="2cm" margin-right="2cm">
                    <fo:region-body/>
                </fo:simple-page-master>
            </fo:layout-master-set>
            <fo:page-sequence master-reference="simpleA4">
                <fo:flow flow-name="xsl-region-body">
                    <fo:block font-size="16pt" text-align="center" font-weight="bold" space-after="5mm">CUSTOMER ORDER LIST<xsl:value-of select="customers"/>
                    </fo:block>
                    <fo:block font-size="12pt" text-align="center" space-after="5mm">----oOo----</fo:block>
                    <fo:block font-size="10pt">
                        <fo:table table-layout="fixed" width="100%"  
                                  border-collapse="separate" border="solid"
                                  border-separation="3pt">
                            <xsl:attribute-set name="table.cell.padding">
                                <xsl:attribute name="padding-left">2pt</xsl:attribute>
                                <xsl:attribute name="padding-right">2pt</xsl:attribute>
                                <xsl:attribute name="padding-top">2pt</xsl:attribute>
                                <xsl:attribute name="padding-bottom">2pt</xsl:attribute>
                            </xsl:attribute-set>
                            <fo:table-column column-width="2cm"/>
                            <fo:table-column column-width="5cm"/>
                            <fo:table-column column-width="5cm"/>
                            <fo:table-column column-width="2cm"/>
                            <fo:table-column column-width="3cm"/>
                            <fo:table-header>
                                <fo:table-row background-color="#0000FF" color="#FFFFFF">
                                    <fo:table-cell text-align="center">
                                        <fo:block>Order.</fo:block>
                                    </fo:table-cell>
                                    <fo:table-cell>
                                        <fo:block>Customer name</fo:block>
                                    </fo:table-cell>
                                    <fo:table-cell>
                                        <fo:block>Product name</fo:block>
                                    </fo:table-cell>
                                    <fo:table-cell text-align="right">
                                        <fo:block>Quantity</fo:block>
                                    </fo:table-cell>
                                    <fo:table-cell text-align="right">
                                        <fo:block>Price</fo:block>
                                    </fo:table-cell>
                                </fo:table-row>
                            </fo:table-header>                            
                            <fo:table-body>
                                <xsl:apply-templates select="customer"/>
                            </fo:table-body>
                        </fo:table>
                    </fo:block>
                    <fo:block font-size="12pt" text-align="right" space-before="1cm">Signature</fo:block>
                    <fo:block font-size="12pt" text-align="right" space-before="2cm" space-after="5mm"> <xsl:value-of select="$author"/> </fo:block>
                </fo:flow>
            </fo:page-sequence>
        </fo:root>
    </xsl:template>
    <xsl:template match="customer">         
        <xsl:variable name="bgclr">
            <xsl:choose>
                <xsl:when test="position() mod 2">#A7BFDE</xsl:when>
                <xsl:otherwise>#EDF2F8</xsl:otherwise>
            </xsl:choose>
        </xsl:variable>
        <fo:table-row background-color="{$bgclr}">                      
            <xsl:if test="item='Laptop'">
                <xsl:attribute name="font-weight">bold</xsl:attribute>                
            </xsl:if>
            <fo:table-cell text-align="center">
                <fo:block>
                    <xsl:value-of select="position()" format="1."/>
                </fo:block>
            </fo:table-cell>
            <fo:table-cell>
                <fo:block>
                    <xsl:value-of select="name"/>
                </fo:block>
            </fo:table-cell>
            <fo:table-cell>
                <fo:block>
                    <xsl:value-of select="item"/>
                </fo:block>
            </fo:table-cell>
            <fo:table-cell text-align="right">
                <fo:block>
                    <xsl:value-of select="quantity"/>
                </fo:block>
            </fo:table-cell>
            <fo:table-cell text-align="right">
                <xsl:attribute name="font-weight">bold</xsl:attribute>
                <fo:block>
                    <xsl:value-of select="price"/>
                </fo:block>
            </fo:table-cell>
        </fo:table-row>
    </xsl:template>
</xsl:stylesheet>

Căn bản là vậy !!!

Load danh sách sản phẩm từ MySQL với hiệu ứng CSS3


Khi các bạn xây dựng một website bán hàng trực tuyến chẳng hạn, phần nội dung trang chủ của các bạn phải thể hiện được danh sách các sản phẩm.

  • Trong danh sách này, về mặt hình thức, các bạn có thể bố trí các sản phẩm sắp xếp theo dạng bảng, sử dụng các định dạng CSS để trông đẹp mắt.
  • Tiếp đến là phần nội dung, các bạn sử dụng ngôn ngữ để load trực tiếp dữ liệu từ cơ sở dữ liệu MySQL.

Vì thế, ở ví dụ này, chúng ta sẽ xây dựng một trang chủ đơn giản với dữ liệu động load từ cơ sở dữ liệu, kết hợp với CSS3 tạo giao diện thân thiện người dùng.

Giao diện sẽ xây dựng:

trangchu

Trước khi thực hiện, yêu cầu:

  • Cài đặt chương trình Xampp để sử dụng ngôn ngữ PHP và MySQL.
  • Tạo một thư mục gốc danhsachsanpham với các thành phần sau:

thumucgoc

Trong thư mục images, copy 4 hình sản phẩm và đặt tên lần lượt là: 1.png, 2.png, 3.png, 4.png.

Khi mọi thứ sẵn sàng, các bạn làm theo các bước sau:

Bước 1: Vào phpmyadmin, tạo cơ sở dữ liệu tên là quanlybanhang với cấu trúc bảng sanpham như sau:

csdl

Sau đó, chèn 4 sản phẩm vào bảng:

dulieu

Bước 2: Tạo các file css để định dạng danh sách và hiển thị hiệu ứng:

  • demo.css

@import url('reset.css');
/* General Demo Style */
body{
 background:#f9f9f9 url(../images/white_texture.jpg) repeat top left;
 color: #333;
 font-family: 'Oswald', Arial, sans-serif;
 font-size: 13px;
}
.container{
 position:relative;
}
a{
 color: #fff;
 text-decoration: none;
}
.clr{
 clear: both;
}
.main{
 position:relative;
 width:680px;
 margin: 0 auto;
}
h1{
 margin:0px;
 padding:20px 20px 10px 20px;
 font-size:34px;
 color:#333;
 text-shadow:1px 1px 1px #fff;
 text-align:left;
 font-weight:400;
 text-align:center;
}
h1 span{
 display:block;
 font-size: 14px;
 font-family: Georgia, serif;
 font-style: italic;
 color:#b2891b;
 padding-top:10px;
}
/* Header Style */
.header{
 font-family:'Arial Narrow', Arial, sans-serif;
 line-height: 24px;
 font-size: 11px;
 background: #000;
 opacity: 0.9;
 text-transform: uppercase;
 z-index: 9999;
 position: relative;
 -moz-box-shadow: 1px 0px 2px #000;
 -webkit-box-shadow: 1px 0px 2px #000;
 box-shadow: 1px 0px 2px #000;
}
.header a{
 padding: 0px 10px;
 letter-spacing: 1px;
 color: #ddd;
 display: block;
 float: left;
}
.header a:hover{
 color: #fff;
}
.header span.right{
 float: right;
}
.header span.right a{
 float: none;
 display: inline;
}

.more{
 position:relative;
 clear:both;
 font-family:'Arial Narrow', Arial, sans-serif;
 text-transform: uppercase;
 font-size: 11px;
 padding: 5px 0px 10px;
 width: 540px;
 margin: 0 auto;
}
.more ul{
 display:block;
 text-align:center;
 height: 30px;
}
.more ul li{
 display: block;
 padding: 4px 2px;
 float:left;
}
.more ul li.selected a,
.more ul li.selected a:hover{
 background:#b2891b;
 color:#fff;
 text-shadow:none;
}
.more ul li a{
 color:#555;
 float:left;
 background:#fff;
 width:40px;
 padding: 2px 5px;
 -moz-box-shadow:1px 1px 2px #aaa;
 -webkit-box-shadow:1px 1px 2px #aaa;
 box-shadow:1px 1px 2px #aaa;
}
.more ul li a:hover{
 background:#000;
 color:#fff;
}
  • style_common.css:
.view {
   width: 300px;
   height: 200px;
   margin: 10px;
   float: left;
   border: 10px solid #fff;
   overflow: hidden;
   position: relative;
   text-align: center;
   -webkit-box-shadow: 1px 1px 2px #e6e6e6;
   -moz-box-shadow: 1px 1px 2px #e6e6e6;
   box-shadow: 1px 1px 2px #e6e6e6;
   cursor: default;
   background: #fff url(../images/bgimg.jpg) no-repeat center center;
}
.view .mask,.view .content {
   width: 300px;
   height: 200px;
   position: absolute;
   overflow: hidden;
   top: 0;
   left: 0;
}
.view img {
   display: block;
   position: relative;
}
.view h2 {
   text-transform: uppercase;
   color: #fff;
   text-align: center;
   position: relative;
   font-size: 17px;
   padding: 10px;
   background: rgba(0, 0, 0, 0.8);
   margin: 20px 0 0 0;
}
.view p {
   font-family: Georgia, serif;
   font-style: italic;
   font-size: 12px;
   position: relative;
   color: #fff;
   padding: 10px 20px 20px;
   text-align: center;
}
.view a.info {
   display: inline-block;
   text-decoration: none;
   padding: 7px 14px;
   background: #000;
   color: #fff;
   text-transform: uppercase;
   -webkit-box-shadow: 0 0 1px #000;
   -moz-box-shadow: 0 0 1px #000;
   box-shadow: 0 0 1px #000;
}
.view a.info: hover {
   -webkit-box-shadow: 0 0 5px #000;
   -moz-box-shadow: 0 0 5px #000;
   box-shadow: 0 0 5px #000;
}
  • style1.css
.view-first img {
   -webkit-transition: all 0.2s linear;
   -moz-transition: all 0.2s linear;
   -o-transition: all 0.2s linear;
   -ms-transition: all 0.2s linear;
   transition: all 0.2s linear;
}
.view-first .mask {
   -ms-filter: "progid: DXImageTransform.Microsoft.Alpha(Opacity=0)";
   filter: alpha(opacity=0);
   opacity: 0;
   background-color: rgba(219,127,8, 0.7);
   -webkit-transition: all 0.4s ease-in-out;
   -moz-transition: all 0.4s ease-in-out;
   -o-transition: all 0.4s ease-in-out;
   -ms-transition: all 0.4s ease-in-out;
   transition: all 0.4s ease-in-out;
}
.view-first h2 {
   -webkit-transform: translateY(-100px);
   -moz-transform: translateY(-100px);
   -o-transform: translateY(-100px);
   -ms-transform: translateY(-100px);
   transform: translateY(-100px);
   -ms-filter: "progid: DXImageTransform.Microsoft.Alpha(Opacity=0)";
   filter: alpha(opacity=0);
   opacity: 0;
   -webkit-transition: all 0.2s ease-in-out;
   -moz-transition: all 0.2s ease-in-out;
   -o-transition: all 0.2s ease-in-out;
   -ms-transition: all 0.2s ease-in-out;
   transition: all 0.2s ease-in-out;
}
.view-first p {
   -webkit-transform: translateY(100px);
   -moz-transform: translateY(100px);
   -o-transform: translateY(100px);
   -ms-transform: translateY(100px);
   transform: translateY(100px);
   -ms-filter: "progid: DXImageTransform.Microsoft.Alpha(Opacity=0)";
   filter: alpha(opacity=0);
   opacity: 0;
   -webkit-transition: all 0.2s linear;
   -moz-transition: all 0.2s linear;
   -o-transition: all 0.2s linear;
   -ms-transition: all 0.2s linear;
   transition: all 0.2s linear;
}
.view-first:hover img {
   -webkit-transform: scale(1.1,1.1);
   -moz-transform: scale(1.1,1.1);
   -o-transform: scale(1.1,1.1);
   -ms-transform: scale(1.1,1.1);
   transform: scale(1.1,1.1);
}
.view-first a.info {
   -ms-filter: "progid: DXImageTransform.Microsoft.Alpha(Opacity=0)";
   filter: alpha(opacity=0);
   opacity: 0;
   -webkit-transition: all 0.2s ease-in-out;
   -moz-transition: all 0.2s ease-in-out;
   -o-transition: all 0.2s ease-in-out;
   -ms-transition: all 0.2s ease-in-out;
   transition: all 0.2s ease-in-out;
}
.view-first:hover .mask {
   -ms-filter: "progid: DXImageTransform.Microsoft.Alpha(Opacity=100)";
   filter: alpha(opacity=100);
   opacity: 1;
}
.view-first:hover h2,
.view-first:hover p,
.view-first:hover a.info {
   -ms-filter: "progid: DXImageTransform.Microsoft.Alpha(Opacity=100)";
   filter: alpha(opacity=100);
   opacity: 1;
   -webkit-transform: translateY(0px);
   -moz-transform: translateY(0px);
   -o-transform: translateY(0px);
   -ms-transform: translateY(0px);
   transform: translateY(0px);
}
.view-first:hover p {
   -webkit-transition-delay: 0.1s;
   -moz-transition-delay: 0.1s;
   -o-transition-delay: 0.1s;
   -ms-transition-delay: 0.1s;
   transition-delay: 0.1s;
}
.view-first:hover a.info {
   -webkit-transition-delay: 0.2s;
   -moz-transition-delay: 0.2s;
   -o-transition-delay: 0.2s;
   -ms-transition-delay: 0.2s;
   transition-delay: 0.2s;
}
				

Bước 3: Tạo file kết nối với cơ sở dữ liệu

  • dbconnect.php
<!--?php $connect = mysql_connect("localhost", "root", "") or die("Không kết nối được với MYSQL"); mysql_select_db("quanlybanhang", $connect) or die ("Không tìm thấy cơ sở dữ liệu"); mysql_query("SET NAMES utf8"); ?-->

Bước 4: Tạo trang index

<!DOCTYPE html>
<html>
 <head>
 <title>Danh sách sản phẩm</title>
 <meta charset="UTF-8" />
 
 <link rel="stylesheet" type="text/css" href="css/demo.css" />
 <link rel="stylesheet" type="text/css" href="css/style_common.css" />
 <link rel="stylesheet" type="text/css" href="css/style1.css" />
 </head>
 <body>

<div class="container"> 

<div class="main">
 <?php include ("dbconnect.php"); $rs = mysql_query("select * from sanpham"); while($row = mysql_fetch_array($rs)){ ?>

<div class="view view-first">
 <img src="images/<?php echo $row['hinhanh']; ?>" />

<div class="mask">

<h2><?php echo $row['tensanpham']; ?></h2>



<?php echo $row['mota']; ?>

 <a href="#" class="info">MUA HÀNG</a>
 </div>

 </div>

 
 <?php } ?> 
 </div>

 </div>

 </body>
</html>

Chúc các bạn thành công.

SAX căn bản – phân tích XML (dữ liệu thời tiết trực tuyến)


Ví dụ sử dụng SAX phân tích nội dung XML trực tuyến (thông tin dự báo thời tiết)
Nội dung XML
Snap 2015-09-11 at 16.27.57
Nội dung hiện thị sau phân tích
Snap 2015-09-11 at 16.28.14
Mã nguồn ví dụ

package codes;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
 * @author ntdan
 */
public class SAXParser_RSS extends DefaultHandler {
    String urlPath = "http://api.openweathermap.org/data/2.5/forecast?q=can+tho,vn&mode=xml";
    String strresult = "";
    int count = 1;
    boolean namefound = false;
    boolean itemfound = false;

    public String parse() {
        try {
            SAXParserFactory fac = SAXParserFactory.newInstance();
            SAXParser sax = fac.newSAXParser();
            // ket noi truc tiep
            URL url = new URL(urlPath);
            URLConnection conn = url.openConnection();
            InputSource in = new InputSource(conn.getInputStream());
            // phan tich tu luon truc tuyen
            sax.parse(in, this);
            return strresult;
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(SAXParser_RSS.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(SAXParser_RSS.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MalformedURLException ex) {
            Logger.getLogger(SAXParser_RSS.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(SAXParser_RSS.class.getName()).log(Level.SEVERE, null, ex);
        }
        return strresult;
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length); //To change body of generated methods, choose Tools | Templates.

        if (namefound) {
            strresult += "<b>Location</b>: " + new String(ch, start, length) + "!<br/>";
            namefound = false;
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName); //To change body of generated methods, choose Tools | Templates.

        if (qName.equalsIgnoreCase("item")) {
            strresult += "<br/>";
            itemfound = false;
        }
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes); //To change body of generated methods, choose Tools | Templates.
        if (qName.equalsIgnoreCase("name")) {
            namefound = true;
        }

        if (qName.equalsIgnoreCase("item")) {
            itemfound = true;
        }

        if (qName.equalsIgnoreCase("time")) {
            strresult += count++ + ". <i>Time<i> <b>From</b>: " + attributes.getValue("from")
                    + " <b>To</b>: " + attributes.getValue("to");
        }

        if (qName.equalsIgnoreCase("humidity")) {
            strresult += " <i>Humidity</i>: " + attributes.getValue("value")
                    + attributes.getValue("unit") + "<br/>";
        }

        if (qName.equalsIgnoreCase("temperature")) {
            strresult += " <b>Temperature</b>: <b>from</b> "
                    + attributes.getValue("min") + " <b>to</b> "
                    + attributes.getValue("max") + "-"
                    + attributes.getValue("unit");
        }
    }

    @Override
    public void endDocument() throws SAXException {
        super.endDocument(); //To change body of generated methods, choose Tools | Templates.
        strresult += "<br/>End parsing ...";
    }

    @Override
    public void startDocument() throws SAXException {
        super.startDocument(); //To change body of generated methods, choose Tools | Templates.
        strresult += "Start parsing ... <br/>";
    }
}

goodluck!!!

Parsing XML using DOM (Basic)


Objectives

  1. Overview XML parse using DOM
  2. Create DOM with content loaded from SQL Server
  3. Save DOM to XML file
  4. Find information in XML file
  5. Update content in XML file
    1. Load Data form XML
      Create java class JavaApplication1 and declare 02 variable
      static ResultSet rs;
      static Document doc;

      Load Data from Employees table

      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
      Connection conn = DriverManager.getConnection("jdbc:sqlserver://"
              + "172.16.160.81\\sql2008;database=northwind;user=sa;password=sa;");
      PreparedStatement comm = conn.prepareStatement(""
              + "Select EmployeeID, FirstName,LastName From Employees");
      rs = comm.executeQuery();
      

      Create createDom method to transform RS to DOM

      void createDom() {
              try {
                  DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
                  DocumentBuilder db = fac.newDocumentBuilder();
                  doc = db.newDocument();
      
                  Element root = doc.createElement("emplist");
                  // tao nut goc
                  doc.appendChild(root);
      
                  Comment comment = doc.createComment("danh sach nhan vien");
                  // tao nut goc
                  root.appendChild(comment);
      
                  // doc du lieu va tao lai voi xml
                  while (rs.next()) {
                      // tao the emp
                      Element emp = doc.createElement("emp");
                      emp.setAttribute("status", "on");
                      // the id
                      Element id = doc.createElement("id");
                      id.setTextContent(rs.getString("EmployeeID"));
                      emp.appendChild(id);
      
                      // the name
                      Element name = doc.createElement("name");
                      name.setTextContent(rs.getString("FirstName") + " " + rs.getString("LastName"));
                      emp.appendChild(name);
      
                      // gan vao root
                      root.appendChild(emp);
                  }
                  Comment comment1 = doc.createComment("Nhan vien cuoi cung");
                  // gan ghi chu vao phan tu cuoi cung
                  root.insertBefore(comment1, root.getLastChild());
              } catch (Exception ex) {
                  Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
              }
          }
      

      Write DOM to XML file

          void writeToXML(String filename) {
              try {
                  
                  if(new File(filename).exists())
                  {
                      if(JOptionPane.showConfirmDialog(
                              null, filename + " đ? t?n t?i ! \nB?n có mu?n ghi đè không?",
                              "Xác nh?n!", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION)
                      return;
                  }
                  
                  // Create a DOM document for writing 
                  Source source = new DOMSource(doc);
                  // Prepare the output file 
                  Result result = new StreamResult(filename);
                  // Create an instance of Transformer 
                  Transformer xformer = TransformerFactory.newInstance().newTransformer();
                  xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
                  xformer.setOutputProperty(OutputKeys.INDENT, "yes");
                  xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
                  // Write the DOM document to the file 
                  xformer.transform(source, result);
              } catch (TransformerException ex) {
                  System.out.println(ex.toString());
              }
          }
      

      Update status attribute of emp tag with content of id tag equal id

       
        void deactive(int id) {
              // lay danh sach cac the con
              NodeList list = doc.getElementsByTagName("emp");
              // duyet qua ca the con
              for (int i = 0; i < list.getLength(); i++) {
                  // tim con dau tien (the id) va kiem tra gia tri
                  // neu bang voi id thi thuc hien
                  if (Integer.parseInt(list.item(i).getFirstChild().getTextContent()) == id) {
                      // cap nhat gia tri thuoc tinh status cua the emp
                      list.item(i).getAttributes().getNamedItem("status").setNodeValue("off");
                      break;
                  }
              }
          }
      

      Find an employee in XML file with id tag content equal id

          boolean exist(int id) {
              try {
                  DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
                  DocumentBuilder db = fac.newDocumentBuilder();
                  doc = db.parse(new File("src/emp.xml"));
                  // lay danh sach cac the con
                  NodeList list = doc.getElementsByTagName("id");
                  // duyet qua ca the con
                  for (int i = 0; i < list.getLength(); i++) {
                      // tim con dau tien (the id) va kiem tra gia tri
                      // neu bang voi id thi thuc hien
                      if (Integer.parseInt(list.item(i).getTextContent()) == id) {
                          return true;
                      }
                  }
              } catch (ParserConfigurationException ex) {
                  Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
              } catch (SAXException ex) {
                  Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
              } catch (IOException ex) {
                  Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
              }
      
              return false;
          }
      

      Add new emp tag to existing XML file if emp id tag do not exist in XML file

          
      void add(int newId, String newName) {
              try {
                  DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
                  DocumentBuilder db = fac.newDocumentBuilder();
                  doc = db.parse(new File("src/emp.xml"));
      
                  if (exist(newId)) {
                      JOptionPane.showMessageDialog(null, newId + " đ? t?n t?i !");
                      return;
                  }
      
                  // lay the emplist
                  Node root = doc.getDocumentElement();
      
                  // tao the emp
                  Element emp = doc.createElement("emp");
                  emp.setAttribute("status", "on");
                  // the id
                  Element id = doc.createElement("id");
                  id.setTextContent(newId + "");
                  emp.appendChild(id);
      
                  // the name
                  Element name = doc.createElement("name");
                  name.setTextContent(newName);
                  emp.appendChild(name);
      
                  // gan vao root
                  root.appendChild(emp);
      
              } catch (ParserConfigurationException ex) {
                  Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
              } catch (SAXException ex) {
                  Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
              } catch (IOException ex) {
                  Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
              }
          }
      

      Test app

      public class JavaApplication1 {
      
          static ResultSet rs;
          static Document doc;
      
          /**
           * @param args the command line arguments
           */
          public static void main(String[] args) {
              try {
                  Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                  Connection conn = DriverManager.getConnection("jdbc:sqlserver://"
                          + "172.16.160.81\\sql2008;database=northwind;user=sa;password=sa;");
                  PreparedStatement comm = conn.prepareStatement(""
                          + "Select EmployeeID, FirstName,LastName From Employees");
      
                  rs = comm.executeQuery();
      
                  JavaApplication1 xmlDOM = new JavaApplication1();
                  // tao doi tuong t? SQL Server
                  xmlDOM.createDom();
                  // ghi ra file
                  xmlDOM.writeToXML("src/emp.xml");
                  // cap nhat
                  xmlDOM.deactive(5);
                  // luu thay doi
                  xmlDOM.writeToXML("src/emp.xml");
                  // them node
                  xmlDOM.add(100, "Nguyen Van Mit");
                  // luu thay doi
                  xmlDOM.writeToXML("src/emp.xml");
                  
              } catch (Exception ex) {
                  System.out.println(ex.toString());
              }
          }
      
              }
      

      }
      }

      Shifl + F6 to run