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.
[embed]https://youtu.be/caDsv_-EHPY[/embed]
1. Tạo Website sử dụng JSF 2.2
2. Tạo managebean như sau:
[sourcecode language="java"]
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;
}
}
[/sourcecode]
3. Tạo trang index.xhtml để upload file như sau:
[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>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>
[/sourcecode]
4. Tạo trang xem ảnh vừa upload và thông tin về hình
[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>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>
[/sourcecode]
OK, chạy trang index.xhtml --> chonj file upload hệ thống sẽ chuyển qua trang view.xhtml để xem ảnh vừa upload.
Showing posts with label aducation. Show all posts
Showing posts with label aducation. Show all posts
Friday, September 25, 2015
Tuesday, September 22, 2015
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:
[sourcecode language="java"]
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);
[/sourcecode]
Sẽ được chuyển thành file XML có nội dung như sau:
[sourcecode language="xml"]
<?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>
[/sourcecode]
Để 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
[sourcecode language="java"]
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 + "]";
}
}
[/sourcecode]
2. EmpList
[sourcecode language="java"]
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;
}
}
[/sourcecode]
3. Tạo 2 phương thức để chuyển đổi
[sourcecode language="java"]
// 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();
}
[/sourcecode]
4. Test
[sourcecode language="java"]
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);
}
[/sourcecode]
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
[sourcecode language="text"]
[Emp [code:A001, name:Nguyen Van Mit, address:Can Tho, tel:+8499999999], Emp [code:A002, name:Tran Van Cam, address:Can Tho, tel:+848888888]]
[/sourcecode]
Mã nguồn tham khảo tại đây
Ví dụ danh sách chứa các Emp như sau:
[sourcecode language="java"]
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);
[/sourcecode]
Sẽ được chuyển thành file XML có nội dung như sau:
[sourcecode language="xml"]
<?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>
[/sourcecode]
Để 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
[sourcecode language="java"]
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 + "]";
}
}
[/sourcecode]
2. EmpList
[sourcecode language="java"]
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;
}
}
[/sourcecode]
3. Tạo 2 phương thức để chuyển đổi
[sourcecode language="java"]
// 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();
}
[/sourcecode]
4. Test
[sourcecode language="java"]
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);
}
[/sourcecode]
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
[sourcecode language="text"]
[Emp [code:A001, name:Nguyen Van Mit, address:Can Tho, tel:+8499999999], Emp [code:A002, name:Tran Van Cam, address:Can Tho, tel:+848888888]]
[/sourcecode]
Mã nguồn tham khảo tại đây
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:

Mã nguồn tham khảo -->> ở đây
OK vậy là chúng ta đã import nội dung XML vào csdl.
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:

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.

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

Các thư viện hỗ trợ -->> đây
Mã nguồn tham khảo như sau:
[sourcecode language="java"]
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);
}
}
}
[/sourcecode]
File XSL-FO như sau:
[sourcecode language="xml"]
<?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>
[/sourcecode]
Căn bản là vậy !!!
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

Các thư viện hỗ trợ -->> đây
Mã nguồn tham khảo như sau:
[sourcecode language="java"]
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);
}
}
}
[/sourcecode]
File XSL-FO như sau:
[sourcecode language="xml"]
<?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>
[/sourcecode]
Căn bản là vậy !!!
Thursday, September 17, 2015
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.
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:

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

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:

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

Bước 2: Tạo các file css để định dạng danh sách và hiển thị hiệu ứng:
[sourcecode language="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;
}
[/sourcecode]
[sourcecode language="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;
}
[/sourcecode]
[sourcecode language="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;
}
[/sourcecode]
Bước 3: Tạo file kết nối với cơ sở dữ liệu
[sourcecode language="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"); ?-->
[/sourcecode]
Bước 4: Tạo trang index
[sourcecode language="php"]
<!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>
[/sourcecode]
Chúc các bạn thành công.
- 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:

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:

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:

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

Bước 2: Tạo các file css để định dạng danh sách và hiển thị hiệu ứng:
- demo.css
[sourcecode language="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;
}
[/sourcecode]
- style_common.css:
[sourcecode language="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;
}
[/sourcecode]
- style1.css
[sourcecode language="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;
}
[/sourcecode]
Bước 3: Tạo file kết nối với cơ sở dữ liệu
- dbconnect.php
[sourcecode language="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"); ?-->
[/sourcecode]
Bước 4: Tạo trang index
[sourcecode language="php"]
<!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>
[/sourcecode]
Chúc các bạn thành công.
Friday, September 11, 2015
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

Nội dung hiện thị sau phân tích

Mã nguồn ví dụ
[sourcecode language="java"]
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/>";
}
}
[/sourcecode]
goodluck!!!
Nội dung XML

Nội dung hiện thị sau phân tích

Mã nguồn ví dụ
[sourcecode language="java"]
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/>";
}
}
[/sourcecode]
goodluck!!!
Parsing XML using DOM (Basic)
Objectives
- Overview XML parse using DOM
- Create DOM with content loaded from SQL Server
- Save DOM to XML file
- Find information in XML file
- Update content in XML file
Load Data form XML
Create java class JavaApplication1 and declare 02 variable
static ResultSet rs;
static Document doc;
Load Data from Employees table
[sourcecode language="java"]
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();
[/sourcecode]
Create createDom method to transform RS to DOM
[sourcecode language="java"]
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);
}
}
[/sourcecode]
Write DOM to XML file
[sourcecode language="java"]
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());
}
}
[/sourcecode]
Update status attribute of emp tag with content of id tag equal id
[sourcecode language="java"]
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;
}
}
}
[/sourcecode]
Find an employee in XML file with id tag content equal id
[sourcecode language="java"]
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;
}
[/sourcecode]
Add new emp tag to existing XML file if emp id tag do not exist in XML file
[sourcecode language="java"]
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);
}
}
[/sourcecode]
Test app
[sourcecode language="java"]
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());
}
}
}
[/sourcecode]
}
}
Shifl + F6 to run
Thursday, September 10, 2015
Direct access to SQL Server From Android
Sử dụng thư viện JTDS --> http://sourceforge.net/projects/jtds/ để truy cập SQL Server từ Android
[embed]https://youtu.be/8cp8ykUNmL4[/embed]
Download thư viện từ đây
Kết nối với SQL Server như sau:
[sourcecode language="java"]
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
conn = DriverManager
.getConnection(""
+ "jdbc:jtds:sqlserver://172.16.160.81/northwind;instance=SQL2008;"
+ "user=sa;password=sa;");
[/sourcecode]
net.sourceforge.jtds.jdbc.Driver là dạng Drive truy cập SQL Server.
Thêm dữ liệu
[sourcecode language="java"]
comm = conn.prepareStatement("insert into Employees("
+ "firstname, lastname) values(?,?)");
comm.setString(1, etFirst.getText().toString());
comm.setString(2, etLast.getText().toString());
comm.executeUpdate();
[/sourcecode]
Đọc dữ liệu
[sourcecode language="java"]
comm = conn.createStatement();
ResultSet rs = comm.executeQuery("Select EmployeeID, Firstname From Employees");
String msg = "";
while (rs.next()) {
msg += "\nID: " + rs.getInt("EmployeeID") + " Name: "
+ rs.getString("Firstname");
[/sourcecode]
Giao diện
[sourcecode language="html"]
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<EditText
android:id="@+id/etFirstName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:background="#eeeeee"
android:hint="Firstname"
android:textColor="#000000"
android:textSize="24dp" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/etLastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eeeeee"
android:hint="Lastname"
android:padding="4dp"
android:textColor="#000000"
android:textSize="24dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp" >
<Button
android:id="@+id/btnConnect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Connect" />
<Button
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Add new" />
</LinearLayout>
<TextView
android:id="@+id/tvDs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:padding="8dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
[/sourcecode]
Mã nguồn tham khảo https://drive.google.com/file/d/0B2F9IAasWwaNYVZSc2tiZDNlNTA/view?usp=sharing
[embed]https://youtu.be/8cp8ykUNmL4[/embed]
Download thư viện từ đây
Kết nối với SQL Server như sau:
[sourcecode language="java"]
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
conn = DriverManager
.getConnection(""
+ "jdbc:jtds:sqlserver://172.16.160.81/northwind;instance=SQL2008;"
+ "user=sa;password=sa;");
[/sourcecode]
net.sourceforge.jtds.jdbc.Driver là dạng Drive truy cập SQL Server.
Thêm dữ liệu
[sourcecode language="java"]
comm = conn.prepareStatement("insert into Employees("
+ "firstname, lastname) values(?,?)");
comm.setString(1, etFirst.getText().toString());
comm.setString(2, etLast.getText().toString());
comm.executeUpdate();
[/sourcecode]
Đọc dữ liệu
[sourcecode language="java"]
comm = conn.createStatement();
ResultSet rs = comm.executeQuery("Select EmployeeID, Firstname From Employees");
String msg = "";
while (rs.next()) {
msg += "\nID: " + rs.getInt("EmployeeID") + " Name: "
+ rs.getString("Firstname");
[/sourcecode]
Giao diện
[sourcecode language="html"]
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<EditText
android:id="@+id/etFirstName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:background="#eeeeee"
android:hint="Firstname"
android:textColor="#000000"
android:textSize="24dp" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/etLastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eeeeee"
android:hint="Lastname"
android:padding="4dp"
android:textColor="#000000"
android:textSize="24dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp" >
<Button
android:id="@+id/btnConnect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Connect" />
<Button
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Add new" />
</LinearLayout>
<TextView
android:id="@+id/tvDs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:padding="8dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
[/sourcecode]
Mã nguồn tham khảo https://drive.google.com/file/d/0B2F9IAasWwaNYVZSc2tiZDNlNTA/view?usp=sharing
Wednesday, December 17, 2014
Responsive web design (RWD) - Thiết kế giao diện web thích ứng với kích thước màn hình thiết bị
Trước đây để có thể hiển thị nội dung website của mình trên các thiết bị di động thi giải pháp được sử dụng là tạo thêm một website phiên bản di động, như giờ thi với phương pháp thiết kế giao diện thích ứng (Responsive web design) chúng ta hoàn toàn có thể sắp xếp nội dung trên trang web của chúng ta tùy theo màn hình thiết bị mà không cần phải viết thêm một website phiên bản di động nữa.
[caption id="attachment_1542" align="aligncenter" width="660"]
Giao diện thích ứng với kích thước màn hình[/caption]
Demo môn học PHP tại CUSC
Responsive web design (RWD) hiểu một cách đơn giản là chúng ta sẽ bố trí lại nội dung của trang web tùy theo kích thước màn hình của thiết bị (hình trên). Nói là bố trí lại vì Responsive web design (RWD) chỉ đơn thuần là ẩn/hiện hay sắp xếp trật tự của nội dung trên trang mà thôi.
Với sự hỗ trợ của CSS3 (Media Queries năm 2012) và HTML5 thì phương pháp thiết kế này trở nên rất dễ thực hiện.
Ví dụ:
[sourcecode language="css"]
@media screen and (min-width:500px) { ... }
[/sourcecode]
Giúp xác định kích thước của màn hình thiết bị và ràng buộc nếu nhỏ hơn 500px thì nội dung ở giữa sẽ được thực hiện. Như vậy chúng ta chỉ việc đặt tên cho các phần tử nội dung (html element) trên trang và xử lý chúng là được.
<html xmlns="http://www.0w3.org/1999/xhtml">
<head>
<!--viewport xac dinh kich thuot dung theo man hinh-->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="icon" type="image/ico" href="images/favorite.ico">
<title>Salomon shop</title>
<link href="css.css" rel="stylesheet" type="text/css" />
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="main">
<div id="header">
<h1>SALOMON</h1>
</div>
<div id="Skin_Menu_Ngang">
<ul id="nav">
<li><a href="?home">TRANG CHỦ</a></li>
<li style="border-right: 0px"><a href="?function=dk">ĐĂNG KÝ</a></li>
</ul>
</div>
<div id="noidung">
<div id="cotPhai"> Cot phai </div>
<div id="cotTrai"> cot trai </div>
</div>
<div id="footer"> Footer </div>
</div>
</body>
</html>
Chúng ta có giao diện như sau:

Lưu ý dòng
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
Giúp xác định tỉ lệ scale và qui đổi điểm ảnh của màn hình thiết bị về px.
Ví dụ code css cho Demo môn học PHP tại CUSC như sau:
[sourcecode language="css"]
@media screen and (max-width: 800px) {
#main {
width:100%;
}
#header {
width: 100%;
background-image:none;
text-align:center;
vertical-align:middle;
height:70px;
}
#header h1{
visibility:visible;
display:inline-block;
font-family:Arial, Helvetica, sans-serif;
font-size:xx-large;
color:#FFF;
}
#trinhdon {
width: 100%;
}
#footer {
width: 100%;
}
#noidung {
width: 100%;
}
#cotTrai {
width: 100%;
}
#cotPhai {
width: 100%;
}
}
@media screen and (max-width: 600px) {
#main {
width: 100%;
}
#nav
{
display:none;
}
#header {
width: 100%;
background-image:none;
text-align:center;
vertical-align:middle;
height:70px;
}
#header h1{
display:inline-block;
font-family:Arial, Helvetica, sans-serif;
font-size:xx-large;
color:#FFF;
}
#trinhdon {
width: 100%;
}
#footer {
width: 100%;
}
#noidung {
width: 100%;
}
#cotTrai {
width: 100%;
}
#cotPhai {
width: 100%;
}
}
@media screen and (max-width:480px) {
#nav
{
display:none;
}
#main {
width: 100%;
}
#header {
width: 100%;
background-image:none;
text-align:center;
vertical-align:middle;
height:70px;
}
#header h1{
display:inline-block;
font-family:Arial, Helvetica, sans-serif;
font-size:xx-large;
color:#FFF;
}
#trinhdon {
width: 100%;
}
#footer {
width: 100%;
}
#noidung {
width: 100%;
}
#cotTrai {
width: 100%;
}
#cotPhai {
text-align:center;
width: 100%;
display:inline;
}
}
[/sourcecode]
Ở đây tôi qui định nếu màn hình kích thướt lớn hơn 800px thì chúng ta có giao diện web trên máy tính với header và nội dung bố trí mặc định. Nếu lớn hơn 600px và nhỏ hơn 800px thì bố trí lại 02 phần trái phải theo chiều dọc, ...
Gần đây Chrome hỗ trợ chức năng test giao diện trên các thiết bị động.
1. Nhấn F12 để vào chế độ developer
2. Chọn vào hình điện thoại ở của sổ code
3. Thay đôi kích thước màn hình bằng thướt đo hay chọn thiết bị.
Hi vọng là bài viết này có ích cho các bạn sinh viên tìm hiểu một cách căn bản nhất.
[caption id="attachment_1542" align="aligncenter" width="660"]
Giao diện thích ứng với kích thước màn hình[/caption]Demo môn học PHP tại CUSC
Responsive web design (RWD) hiểu một cách đơn giản là chúng ta sẽ bố trí lại nội dung của trang web tùy theo kích thước màn hình của thiết bị (hình trên). Nói là bố trí lại vì Responsive web design (RWD) chỉ đơn thuần là ẩn/hiện hay sắp xếp trật tự của nội dung trên trang mà thôi.
Với sự hỗ trợ của CSS3 (Media Queries năm 2012) và HTML5 thì phương pháp thiết kế này trở nên rất dễ thực hiện.
Ví dụ:
[sourcecode language="css"]
@media screen and (min-width:500px) { ... }
[/sourcecode]
Giúp xác định kích thước của màn hình thiết bị và ràng buộc nếu nhỏ hơn 500px thì nội dung ở giữa sẽ được thực hiện. Như vậy chúng ta chỉ việc đặt tên cho các phần tử nội dung (html element) trên trang và xử lý chúng là được.
<html xmlns="http://www.0w3.org/1999/xhtml">
<head>
<!--viewport xac dinh kich thuot dung theo man hinh-->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="icon" type="image/ico" href="images/favorite.ico">
<title>Salomon shop</title>
<link href="css.css" rel="stylesheet" type="text/css" />
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="main">
<div id="header">
<h1>SALOMON</h1>
</div>
<div id="Skin_Menu_Ngang">
<ul id="nav">
<li><a href="?home">TRANG CHỦ</a></li>
<li style="border-right: 0px"><a href="?function=dk">ĐĂNG KÝ</a></li>
</ul>
</div>
<div id="noidung">
<div id="cotPhai"> Cot phai </div>
<div id="cotTrai"> cot trai </div>
</div>
<div id="footer"> Footer </div>
</div>
</body>
</html>
Chúng ta có giao diện như sau:

Lưu ý dòng
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
Giúp xác định tỉ lệ scale và qui đổi điểm ảnh của màn hình thiết bị về px.
Ví dụ code css cho Demo môn học PHP tại CUSC như sau:
[sourcecode language="css"]
@media screen and (max-width: 800px) {
#main {
width:100%;
}
#header {
width: 100%;
background-image:none;
text-align:center;
vertical-align:middle;
height:70px;
}
#header h1{
visibility:visible;
display:inline-block;
font-family:Arial, Helvetica, sans-serif;
font-size:xx-large;
color:#FFF;
}
#trinhdon {
width: 100%;
}
#footer {
width: 100%;
}
#noidung {
width: 100%;
}
#cotTrai {
width: 100%;
}
#cotPhai {
width: 100%;
}
}
@media screen and (max-width: 600px) {
#main {
width: 100%;
}
#nav
{
display:none;
}
#header {
width: 100%;
background-image:none;
text-align:center;
vertical-align:middle;
height:70px;
}
#header h1{
display:inline-block;
font-family:Arial, Helvetica, sans-serif;
font-size:xx-large;
color:#FFF;
}
#trinhdon {
width: 100%;
}
#footer {
width: 100%;
}
#noidung {
width: 100%;
}
#cotTrai {
width: 100%;
}
#cotPhai {
width: 100%;
}
}
@media screen and (max-width:480px) {
#nav
{
display:none;
}
#main {
width: 100%;
}
#header {
width: 100%;
background-image:none;
text-align:center;
vertical-align:middle;
height:70px;
}
#header h1{
display:inline-block;
font-family:Arial, Helvetica, sans-serif;
font-size:xx-large;
color:#FFF;
}
#trinhdon {
width: 100%;
}
#footer {
width: 100%;
}
#noidung {
width: 100%;
}
#cotTrai {
width: 100%;
}
#cotPhai {
text-align:center;
width: 100%;
display:inline;
}
}
[/sourcecode]
Ở đây tôi qui định nếu màn hình kích thướt lớn hơn 800px thì chúng ta có giao diện web trên máy tính với header và nội dung bố trí mặc định. Nếu lớn hơn 600px và nhỏ hơn 800px thì bố trí lại 02 phần trái phải theo chiều dọc, ...
Gần đây Chrome hỗ trợ chức năng test giao diện trên các thiết bị động.
1. Nhấn F12 để vào chế độ developer
2. Chọn vào hình điện thoại ở của sổ code
3. Thay đôi kích thước màn hình bằng thướt đo hay chọn thiết bị.
Hi vọng là bài viết này có ích cho các bạn sinh viên tìm hiểu một cách căn bản nhất.
Tuesday, December 16, 2014
Xác định mật độ điểm ảnh trên Android
Đoạn code sau giúp chúng ta xác định mật độ điểm ảnh và qui đổi sang đơn vị đo px (tương đương 50DP)

[sourcecode language="java"]
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
switch (metrics.densityDpi) {
case DisplayMetrics.DENSITY_LOW:
pxSize = 38;
break;
case DisplayMetrics.DENSITY_MEDIUM:
pxSize = 50;
break;
case DisplayMetrics.DENSITY_HIGH:
pxSize = 75;
break;
case DisplayMetrics.DENSITY_XHIGH:
pxSize = 100;
break;
case DisplayMetrics.DENSITY_XXHIGH:
pxSize = 150;
break;
case DisplayMetrics.DENSITY_XXXHIGH:
pxSize = 200;
break;
}
[/sourcecode]
Với sự hỗ trợ của thư viện này chúng ta xác định được tỉ lệ giữa độ đo DP và PX khá đơn giản.
[sourcecode language="java"]
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
switch (metrics.densityDpi) {
case DisplayMetrics.DENSITY_LOW:
pxSize = 38;
break;
case DisplayMetrics.DENSITY_MEDIUM:
pxSize = 50;
break;
case DisplayMetrics.DENSITY_HIGH:
pxSize = 75;
break;
case DisplayMetrics.DENSITY_XHIGH:
pxSize = 100;
break;
case DisplayMetrics.DENSITY_XXHIGH:
pxSize = 150;
break;
case DisplayMetrics.DENSITY_XXXHIGH:
pxSize = 200;
break;
}
[/sourcecode]
Với sự hỗ trợ của thư viện này chúng ta xác định được tỉ lệ giữa độ đo DP và PX khá đơn giản.
Tuesday, May 6, 2014
Ứng dụng hiệu ứng để chuyển activity trong Android
Một ví dụ nhỏ để hình dung animation trong Android
- Khi chuyển activity thay vì lật đơn giản chúng ta tạo hiệu ứng zoom-in và zoom-out để chuyển activity.
Bước 1. Tạo các hoạt cảnh với XML file
Tạo file in.xml và out.xml trong thư mục anim (lưu ý chính xác tên thư mục)
- Nôi dung in.xml
1 <set xmlns:android="http://schemas.android.com/apk/res/android" >
2 <alpha
3 android:duration="3000"
4 android:fillAfter="true"
5 android:fromAlpha="0.0"
6 android:toAlpha="1.0" >
7 </alpha>
8 </set>
- Nội dung out.xml
1 <set xmlns:android="http://schemas.android.com/apk/res/android" >
2 <alpha
3 android:duration="4000"
4 android:fillAfter="true"
5 android:fromAlpha="1.0"
6 android:toAlpha="0.0" >
7 </alpha>
8
9 <rotate
10 android:duration="3000"
11 android:fillAfter="true"
12 android:fromDegrees="0"
13 android:interpolator="@android:anim/accelerate_decelerate_interpolator"
14 android:pivotX="50%"
15 android:pivotY="50%"
16 android:toDegrees="360" >
17 </rotate>
18 </set>
Bước 2. Gán hình nền cho màn hình chào
Mở lại layout màn hình chào và gán thuộc tính background và đặt tên cho RelativeLayout. Hình s_1 của background là hình nằm trong thư mục drawable
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 xmlns:tools="http://schemas.android.com/tools"
3 android:id="@+id/bg"
4 android:background="@drawable/s_1"
5 android:layout_width="match_parent"
6 android:layout_height="match_parent"
7 android:paddingBottom="@dimen/activity_vertical_margin"
8 android:paddingLeft="@dimen/activity_horizontal_margin"
9 android:paddingRight="@dimen/activity_horizontal_margin"
10 android:paddingTop="@dimen/activity_vertical_margin"
11 tools:context="vn.cusc.animation.Chao$PlaceholderFragment" >
12 </RelativeLayout>
Bước 3. Gán hiệu ứng rõ dần cho màn hình chào và hiệu ứng chuyển sang giao diện chính
1 public class Chao extends Activity {
2 RelativeLayout rl;
3 @Override
4 protected void onCreate(Bundle savedInstanceState) {
5 super.onCreate(savedInstanceState);
6 setContentView(R.layout.activity_chao);
7 // tham chi?u d?n background activity
8 rl = (RelativeLayout)findViewById(R.id.bg);
9 // load ho?t hình cho màn hinh n?n
10 Animation a = AnimationUtils.loadAnimation(this, R.anim.in);
11 // ch?y hi?u ?ng rõ d?n
12 rl.setAnimation(a);
13 CountDownTimer t = new CountDownTimer(2000,1000) {
14 @Override
15 public void onTick(long millisUntilFinished) {
16 // c?u trúc màu ARGB trong dó A là alpha là d? trong su?t
17 }
18 @Override
19 public void onFinish() {
20 Intent i = new Intent(getApplicationContext(), Main.class);
21 startActivity(i);
22 overridePendingTransition(R.anim.in, R.anim.out);
23 finish();
24 }
25 };
26 t.start();
27 }
28 }
Subscribe to:
Posts (Atom)