Thursday, November 26, 2015
Friday, November 20, 2015
Thursday, November 5, 2015
jax-rs (sử dụng jersey) (P1)
jax-rs (sử dụng jersey) (P1)
Trong bài này chúng ta sẽ tìm hiểu các tạo dich vụ vụ web theo kiến trúc Rest. Bài này chúng ta sẽ cài đặt cách giao tiếp qua phương thức GET.
B1: Tạo java web project
B2: Tạo rest service



Sau khi xong, mở file web.xml chúng ta sẽ thấy xuất hiện thêm đoạn xml sau:
[sourcecode language="xml"]
<servlet>
<servlet-name>ServletAdaptor</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ServletAdaptor</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
[/sourcecode]
Hiệu chỉnh lại nội dung của lớp Student như sau:
[sourcecode language="java"]
package codes;
import javax.ws.rs.PathParam;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
@Path("student")
public class Student {
public Student() {
}
/**
* Phuong thuc se duoc kich hoat khi nhan duoc
* yeu cau tu phia client theo phuong phap get
* Ket qua tra ve chuyen thanh chuoi
*/
@GET
@Produces("text/plain")
public String getText() {
return "hello moto";
}
/**
* Phuong thuc se duoc kich hoat khi nhan duoc
* yeu cau tu phia client theo phuong phap get
* Ket qua tra ve chuyen thanh chuoi XML
*/
@Path("/xml")
@GET
@Produces("text/xml")
public String getXML(@QueryParam("id") int id) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Customer customer = new Customer(id, "Nguyen Van Mit", "Can Tho");
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(customer, sw);
String xmlString = sw.toString();
return xmlString;
} catch (JAXBException ex) {
return ex.toString();
}
}
/**
* Phuong thuc se duoc kich hoat khi nhan duoc
* yeu cau tu phia client theo phuong phap get
* nhan tham so id theo cach gan them vao URL
* Ket qua tra ve chuyen thanh chuoi xml
*/
@Path("/xml/{id}")
@GET
@Produces("text/xml")
// @PathParam("id") tim phan id tren URL
public String getXMLID(@PathParam("id") int id) {
return "<rs><id>"+id+"</id>"
+ "<name>hello moto</name>"
+ "</rs>";
}
/**
* Phuong thuc se duoc kich hoat khi nhan duoc
* yeu cau tu phia client theo phuong phap get
* Ket qua tra ve chuyen thanh chuoi JSON
*/
@Path("/json")
@GET
@Produces("text/json")
public String getJSON() {
return "{'id':1, "
+ "'name':'Nguyen Van Mit'}";
}
}
[/sourcecode]
Biên dịch và deploy website.
Mở trình duyệt và gõ địa chỉ như sau để test:


Như vậy là chúng ta đã có được dịch vụ web theo kiến trúc Rest
Các bước thực hiện chi tiết và tạo client để gọi dịch vụ với ajax tham khảo video này:
[embed]https://youtu.be/BOhU3gKGpKo[/embed]
Thử xem sao !
- Tạo Rest service trên java sử dụng gói jersey
- Gọi Rest service từ trang html với java script
Trong bài này chúng ta sẽ tìm hiểu các tạo dich vụ vụ web theo kiến trúc Rest. Bài này chúng ta sẽ cài đặt cách giao tiếp qua phương thức GET.
B1: Tạo java web project
B2: Tạo rest service



Sau khi xong, mở file web.xml chúng ta sẽ thấy xuất hiện thêm đoạn xml sau:
[sourcecode language="xml"]
<servlet>
<servlet-name>ServletAdaptor</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ServletAdaptor</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
[/sourcecode]
Hiệu chỉnh lại nội dung của lớp Student như sau:
[sourcecode language="java"]
package codes;
import javax.ws.rs.PathParam;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
@Path("student")
public class Student {
public Student() {
}
/**
* Phuong thuc se duoc kich hoat khi nhan duoc
* yeu cau tu phia client theo phuong phap get
* Ket qua tra ve chuyen thanh chuoi
*/
@GET
@Produces("text/plain")
public String getText() {
return "hello moto";
}
/**
* Phuong thuc se duoc kich hoat khi nhan duoc
* yeu cau tu phia client theo phuong phap get
* Ket qua tra ve chuyen thanh chuoi XML
*/
@Path("/xml")
@GET
@Produces("text/xml")
public String getXML(@QueryParam("id") int id) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Customer customer = new Customer(id, "Nguyen Van Mit", "Can Tho");
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(customer, sw);
String xmlString = sw.toString();
return xmlString;
} catch (JAXBException ex) {
return ex.toString();
}
}
/**
* Phuong thuc se duoc kich hoat khi nhan duoc
* yeu cau tu phia client theo phuong phap get
* nhan tham so id theo cach gan them vao URL
* Ket qua tra ve chuyen thanh chuoi xml
*/
@Path("/xml/{id}")
@GET
@Produces("text/xml")
// @PathParam("id") tim phan id tren URL
public String getXMLID(@PathParam("id") int id) {
return "<rs><id>"+id+"</id>"
+ "<name>hello moto</name>"
+ "</rs>";
}
/**
* Phuong thuc se duoc kich hoat khi nhan duoc
* yeu cau tu phia client theo phuong phap get
* Ket qua tra ve chuyen thanh chuoi JSON
*/
@Path("/json")
@GET
@Produces("text/json")
public String getJSON() {
return "{'id':1, "
+ "'name':'Nguyen Van Mit'}";
}
}
[/sourcecode]
Biên dịch và deploy website.
Mở trình duyệt và gõ địa chỉ như sau để test:


Như vậy là chúng ta đã có được dịch vụ web theo kiến trúc Rest
Các bước thực hiện chi tiết và tạo client để gọi dịch vụ với ajax tham khảo video này:
[embed]https://youtu.be/BOhU3gKGpKo[/embed]
Thử xem sao !
Saturday, October 31, 2015
Friday, October 30, 2015
HTML5 Lưu trữ dữ liệu web
Bài trước, chúng ta đã tìm hiểu một đặc điểm thú vị của HTML5: hỗ trợ vẽ các đối tượng 2D thông qua thẻ canvas. Hôm nay, chúng ta lại tiếp cận một API mới của HTML5, lưu trữ dữ liệu web ở phía máy khách.
Lưu trữ web là một đặc điểm kỹ thuật được đưa ra bởi W3C, hỗ trợ việc lưu trữ dữ liệu tại phiên làm việc của người dùng hoặc lưu trữ trong thời gian lâu dài. Nó cho phép lưu trữ 5 MB thông tin cho mỗi tên miền.
Có 2 loại:
Ví dụ: xây dựng phiên làm việc của người dùng sau khi đăng nhập, …
Ví dụ: đếm số lần người dùng đã truy cập trang; ghi nhớ thông tin tài khoản, mật khẩu cho lần đăng nhập sau, …
Trước khi sử dụng sessionStorage và localStorage, chúng ta phải kiểm tra trình duyệt hiện tại có hỗ trợ 2 dạng lưu trữ này không?
Code tham khảo kiểm tra trình duyệt:
[sourcecode language="html"]
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Kiểm tra lưu trữ phiên</title>
<script>
function checkSupport()
{
if (('sessionStorage' in window) && window['sessionStorage'] !== null)
{
alert("Trình duyệt hỗ trợ lưu trữ web");
return;
}
alert("Trình duyệt không hỗ trợ lưu trữ web");
}
</script>
</head>
<body onLoad="checkSupport()">
</body>
</html>
[/sourcecode]
Để kiểm tra localStorage trong trình duyệt: thay đổi dòng code:
[sourcecode language="html"]
if (('sessionStorage' in window) &amp;&amp; window['sessionStorage'] !== null)
[/sourcecode]
thành
[sourcecode language="html"]
if (('localStorage' in window) &amp;&amp; window['localStorage'] !== null)
[/sourcecode]
1. Cách lưu trữ dữ liệu:
Có 3 cách để lưu trữ:
Ghi chú: 3 cách lưu trữ này cũng áp dụng cho localStorage
Ví dụ đơn giản để lưu trữ dữ liệu:
[sourcecode language="html"]
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Working with Session Storage</title>
<script>
function testStorage()
{
if(('sessionStorage' in window) && window['sessionStorage'] != null){
sessionStorage.setItem('name', 'Sarah');
document.write("The name is:" + sessionStorage.getItem('name') + "
");
sessionStorage.setItem(6, 'Six');
document.write("The number 6 is : " + sessionStorage.getItem(6) + "
");
sessionStorage["age"] = 20;
document.write("The age is : " + sessionStorage.age);
}
}
</script>
</head>
<body onLoad="testStorage()">
</body>
</html>
[/sourcecode]
Kết quả:

2. Ví dụ: Sử dụng sessionStorage để tạo phiên làm việc khi người dùng đăng nhập:
Kịch bản xử lý như sau:
Code:
Trang đăng nhập (dangnhap.html)
[sourcecode language="html"]
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Phiên làm việc người dùng</title>
<script>
function kiemTra()
{
//kiem tra du lieu
if(('sessionStorage' in window) && window['sessionStorage'] !== null){
// bỏ qua bước bắt lỗi tài khoản, mật khẩu
// tạo sessionStorage với key là user lưu tài khoản người dùng
sessionStorage.setItem('user', document.frm.txtTK.value);
// tạo sessionStorage với key là pass lưu mật khẩu người dùng
sessionStorage.setItem('pass', document.frm.txtMK.value);
return true;
}else alert("Không hỗ trợ");
}
</script>
</head>
<body >
<form name="frm" onSubmit="return kiemTra()" action="thanhcong.html">
<table>
<tr>
<td>Tài khoản:</td>
<td><input name="txtTK" /></td>
</tr>
<tr>
<td>Mật khẩu:</td>
<td><input name="txtMK" type="password"/></td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" value="Đăng nhập" /></td>
</tr>
</table>
</form>
</body>
</html>
[/sourcecode]
Trang thông báo thành công (thanhcong.html):
[sourcecode language="html"]
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Thanh cong</title>
<script>
if(sessionStorage.getItem('user') != null)
document.write("Chúc mừng bạn "
+ sessionStorage.getItem('user')
+ " đã đăng nhập thành công");
else document.write('Bạn chưa đăng nhập');
/* Xử lý nút thoát : xóa biến lưu trữ user*/
function thoat(){
sessionStorage.removeItem('user');
location.href="thanhcong.html";
}
</script>
</head>
<body>
<form>
<input value="Thoát" type="button" onClick="thoat()" />
</form>
</body>
</html>
[/sourcecode]
Video:
[embed]https://youtu.be/ee7G5Y3A8WE[/embed]
3. Ví dụ: Sử dụng localStorage để đếm số lần người dùng truy cập vào trang web:
Mỗi lần người dùng vào trang web:
Chú ý: Tắt trình duyệt và mở lên lại thì biến localStorage[‘truy cập’] vẫn cập nhật từ giá trị cũ.
Code:
[sourcecode languange="html"]
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Lưu trữ cực bộ</title>
<script>
function store()
{
if(('localStorage' in window) && window['localStorage'] != null){
if(localStorage.getItem('truycap') == null)
localStorage.setItem('truycap', 1);
else
localStorage.setItem('truycap', parseInt(localStorage.getItem('truycap')) + 1);
document.write("Số lần đăng nhập = " + localStorage.getItem('truycap'));
}
else{
alert("Trình duyệt không hỗ trợ LocalStorage");
}
}
</script>
</head>
<body onLoad="store()">
</body>
</html>
[/sourcecode]
[sourcecode language="html"]
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Lưu trữ cực bộ</title>
<script>
function loadData(){
if(('localStorage' in window)
&& window['localStorage'] != null
&& localStorage.getItem('ghinho')
){
document.frmDangNhap.txtDN.value = localStorage.getItem('tendangnhap');
document.frmDangNhap.txtMK.value = localStorage.getItem('matkhau');
}
}
function store()
{
var tendangnhap = document.getElementById("txtDN").value;
var matkhau = document.getElementById("txtMK").value;
var ghinho = document.getElementById("chkGhiNho");
if(('localStorage' in window) && window['localStorage'] != null){
localStorage.setItem('tendangnhap', tendangnhap);
localStorage.setItem('matkhau', matkhau);
alert("Tên người dùng : " + localStorage.getItem('tendangnhap') + ", Mật khẩu : " + localStorage.getItem('matkhau'));
}
else{
alert("Trình duyệt không hỗ trợ LocalStorage");
}
//ghi nho thong tin
if(ghinho.checked)
{
localStorage.setItem('ghinho', 1);
}
}
</script>
</head>
<body onLoad="loadData()" >
<form method="get" name="frmDangNhap" >
<table width="50%" border="1" align="center">
<tr>
<th colspan="2" scope="col">Đăng nhập </th>
</tr>
<tr>
<td>Tên đăng nhập: </td>
<td><input type="text" id="txtDN" name="txtDN" /></td>
</tr>
<tr>
<td>Mật khẩu:</td>
<td><input type="text" id="txtMK" name="txtMK" /></td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Đăng nhập" onClick="store();"/>
<input type="checkbox" id="chkGhiNho" />Ghi nhớ thông tin</td>
</tr>
</table>
</form>
</body>
</html>
[/sourcecode]
Video tham khảo
[embed]https://youtu.be/LcLLxot5bmw[/embed]
Chúc các bạn hiểu được cơ bản về lưu trữ web trong HTML5
Lưu trữ web là một đặc điểm kỹ thuật được đưa ra bởi W3C, hỗ trợ việc lưu trữ dữ liệu tại phiên làm việc của người dùng hoặc lưu trữ trong thời gian lâu dài. Nó cho phép lưu trữ 5 MB thông tin cho mỗi tên miền.
Có 2 loại:
- sesionStorage: lưu trữ dữ liệu trong một phiên làm việc (sẽ bị xóa khi đóng cửa sổ trình duyệt)
Ví dụ: xây dựng phiên làm việc của người dùng sau khi đăng nhập, …
- localStorage: lưu trữ cục bộ (thông tin được lưu trữ lâu dài, không giới hạn thời gian)
Ví dụ: đếm số lần người dùng đã truy cập trang; ghi nhớ thông tin tài khoản, mật khẩu cho lần đăng nhập sau, …
Trước khi sử dụng sessionStorage và localStorage, chúng ta phải kiểm tra trình duyệt hiện tại có hỗ trợ 2 dạng lưu trữ này không?
Code tham khảo kiểm tra trình duyệt:
[sourcecode language="html"]
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Kiểm tra lưu trữ phiên</title>
<script>
function checkSupport()
{
if (('sessionStorage' in window) && window['sessionStorage'] !== null)
{
alert("Trình duyệt hỗ trợ lưu trữ web");
return;
}
alert("Trình duyệt không hỗ trợ lưu trữ web");
}
</script>
</head>
<body onLoad="checkSupport()">
</body>
</html>
[/sourcecode]
Để kiểm tra localStorage trong trình duyệt: thay đổi dòng code:
[sourcecode language="html"]
if (('sessionStorage' in window) &amp;&amp; window['sessionStorage'] !== null)
[/sourcecode]
thành
[sourcecode language="html"]
if (('localStorage' in window) &amp;&amp; window['localStorage'] !== null)
[/sourcecode]
1. Cách lưu trữ dữ liệu:
Có 3 cách để lưu trữ:
- Thông qua các hàm hỗ trợ sẵn: lưu trữ dạng key/value (biến/giá trị)
+ Gán giá trị cho biến: sessionStorage.setItem(“key”) = value (key,value có thể là chuỗi hoặc số)
sessionStorage.setItem('name', 'user')
+ Lấy giá trị của biến: sessionStorage.getItem(“key”)
sessionStorage.getItem('name')
+ Xóa một giá trị biến đã tạo: sessionStorage.removeItem(“key”)
sessionStorage.removeItem('name')
+ Xóa tất cả các biến đã tạo: sessionStorage.clear() - Thông qua cú pháp mảng: sessionStorage[“key”] = value
sessionStorage['name'] = 'user' - Thông qua toán tử dấu chấm: sessionStorage.key = value
sessionStorage.name = “user”
Ghi chú: 3 cách lưu trữ này cũng áp dụng cho localStorage
Ví dụ đơn giản để lưu trữ dữ liệu:
[sourcecode language="html"]
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Working with Session Storage</title>
<script>
function testStorage()
{
if(('sessionStorage' in window) && window['sessionStorage'] != null){
sessionStorage.setItem('name', 'Sarah');
document.write("The name is:" + sessionStorage.getItem('name') + "
");
sessionStorage.setItem(6, 'Six');
document.write("The number 6 is : " + sessionStorage.getItem(6) + "
");
sessionStorage["age"] = 20;
document.write("The age is : " + sessionStorage.age);
}
}
</script>
</head>
<body onLoad="testStorage()">
</body>
</html>
[/sourcecode]
Kết quả:

2. Ví dụ: Sử dụng sessionStorage để tạo phiên làm việc khi người dùng đăng nhập:
Kịch bản xử lý như sau:
- Tạo form đăng nhập.
- Tạo một trang thanhcong.html để hiển thị thông báo đăng nhập thành công.
- Nếu người dùng chưa đăng nhập -> hiển thị trang thanhcong.html thì có thông báo “Bạn chưa đăng nhập”
- Nếu người dùng vào trang đăng nhập rồi tiến hành đăng nhập -> sau khi đăng nhập thành công, qua trang thanhcong.html và hiển thị “Chúc mừng bạn tên đăng nhập đã đăng nhập thành công”.
Code:
Trang đăng nhập (dangnhap.html)
[sourcecode language="html"]
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Phiên làm việc người dùng</title>
<script>
function kiemTra()
{
//kiem tra du lieu
if(('sessionStorage' in window) && window['sessionStorage'] !== null){
// bỏ qua bước bắt lỗi tài khoản, mật khẩu
// tạo sessionStorage với key là user lưu tài khoản người dùng
sessionStorage.setItem('user', document.frm.txtTK.value);
// tạo sessionStorage với key là pass lưu mật khẩu người dùng
sessionStorage.setItem('pass', document.frm.txtMK.value);
return true;
}else alert("Không hỗ trợ");
}
</script>
</head>
<body >
<form name="frm" onSubmit="return kiemTra()" action="thanhcong.html">
<table>
<tr>
<td>Tài khoản:</td>
<td><input name="txtTK" /></td>
</tr>
<tr>
<td>Mật khẩu:</td>
<td><input name="txtMK" type="password"/></td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" value="Đăng nhập" /></td>
</tr>
</table>
</form>
</body>
</html>
[/sourcecode]
Trang thông báo thành công (thanhcong.html):
[sourcecode language="html"]
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Thanh cong</title>
<script>
if(sessionStorage.getItem('user') != null)
document.write("Chúc mừng bạn "
+ sessionStorage.getItem('user')
+ " đã đăng nhập thành công");
else document.write('Bạn chưa đăng nhập');
/* Xử lý nút thoát : xóa biến lưu trữ user*/
function thoat(){
sessionStorage.removeItem('user');
location.href="thanhcong.html";
}
</script>
</head>
<body>
<form>
<input value="Thoát" type="button" onClick="thoat()" />
</form>
</body>
</html>
[/sourcecode]
Video:
[embed]https://youtu.be/ee7G5Y3A8WE[/embed]
3. Ví dụ: Sử dụng localStorage để đếm số lần người dùng truy cập vào trang web:
Mỗi lần người dùng vào trang web:
- Nếu là lần đầu tiên: khởi tạo biến localStorage[‘truy cập’] là 1.
- Nếu là lần thứ 2 về sau: cộng thêm 1 vào biến localStorage[‘truy cập’]
Chú ý: Tắt trình duyệt và mở lên lại thì biến localStorage[‘truy cập’] vẫn cập nhật từ giá trị cũ.
Code:
[sourcecode languange="html"]
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Lưu trữ cực bộ</title>
<script>
function store()
{
if(('localStorage' in window) && window['localStorage'] != null){
if(localStorage.getItem('truycap') == null)
localStorage.setItem('truycap', 1);
else
localStorage.setItem('truycap', parseInt(localStorage.getItem('truycap')) + 1);
document.write("Số lần đăng nhập = " + localStorage.getItem('truycap'));
}
else{
alert("Trình duyệt không hỗ trợ LocalStorage");
}
}
</script>
</head>
<body onLoad="store()">
</body>
</html>
[/sourcecode]
Kết quả:
Lần chạy đầu tiên:
Số lần đăng nhập = 1
Reload lại trang:
Số lần đăng nhập = 2
Các lần chạy tiếp theo -> mỗi lần tăng lên 1.
Tắt trình duyệt và chạy lại trình duyệt vừa rồi:
Số lần đăng nhập = 3
Các bạn có thể tham khảo thêm:
4. Ví dụ sử dụng localStorage để ghi nhớ thông tin đăng nhập:
[sourcecode language="html"]
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Lưu trữ cực bộ</title>
<script>
function loadData(){
if(('localStorage' in window)
&& window['localStorage'] != null
&& localStorage.getItem('ghinho')
){
document.frmDangNhap.txtDN.value = localStorage.getItem('tendangnhap');
document.frmDangNhap.txtMK.value = localStorage.getItem('matkhau');
}
}
function store()
{
var tendangnhap = document.getElementById("txtDN").value;
var matkhau = document.getElementById("txtMK").value;
var ghinho = document.getElementById("chkGhiNho");
if(('localStorage' in window) && window['localStorage'] != null){
localStorage.setItem('tendangnhap', tendangnhap);
localStorage.setItem('matkhau', matkhau);
alert("Tên người dùng : " + localStorage.getItem('tendangnhap') + ", Mật khẩu : " + localStorage.getItem('matkhau'));
}
else{
alert("Trình duyệt không hỗ trợ LocalStorage");
}
//ghi nho thong tin
if(ghinho.checked)
{
localStorage.setItem('ghinho', 1);
}
}
</script>
</head>
<body onLoad="loadData()" >
<form method="get" name="frmDangNhap" >
<table width="50%" border="1" align="center">
<tr>
<th colspan="2" scope="col">Đăng nhập </th>
</tr>
<tr>
<td>Tên đăng nhập: </td>
<td><input type="text" id="txtDN" name="txtDN" /></td>
</tr>
<tr>
<td>Mật khẩu:</td>
<td><input type="text" id="txtMK" name="txtMK" /></td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Đăng nhập" onClick="store();"/>
<input type="checkbox" id="chkGhiNho" />Ghi nhớ thông tin</td>
</tr>
</table>
</form>
</body>
</html>
[/sourcecode]
Video tham khảo
[embed]https://youtu.be/LcLLxot5bmw[/embed]
Chúc các bạn hiểu được cơ bản về lưu trữ web trong HTML5
Wednesday, October 28, 2015
Android - List and kill background process
Android OS is a multitasking operating, there are a lot of running background process, these process make your device will be slower. Android SDK provides set of API allow developer can list all background process and kill (stop) them.
In this post, we will discussing about how listing and kill background process in Android device.
[caption id="attachment_1855" align="alignnone" width="168"]
List all android background processes[/caption]
We need two permission are KILL_BACKGROUND_PROCESSES and to GET_TASKS.
Declare two permission as
[sourcecode language="xml"]
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
<uses-permission android:name="android.permission.GET_TASKS" />
[/sourcecode]
Declare 2 variable
[sourcecode language="java"]
List<ActivityManager.RunningAppProcessInfo> processes;
ActivityManager amg;
[/sourcecode]
Register service with Android get all running processes
[sourcecode language="java"]
// using Activity service to list all process
amg = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
// list all running process
processes = amg.getRunningAppProcesses();
[/sourcecode]
Create MyAdapter class extend BaseAdapter class to populate process's information on ListView as
[sourcecode language="java"]
public class MyAdapter extends BaseAdapter {
List<ActivityManager.RunningAppProcessInfo> processes;
Context context;
public MyAdapter(List<ActivityManager.RunningAppProcessInfo> processes, Context context) {
this.context = context;
this.processes = processes;
}
@Override
public int getCount() {
return processes.size();
}
@Override
public Object getItem(int position) {
return processes.get(position);
}
@Override
public long getItemId(int position) {
return processes.get(position).pid;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Process pro;
if(convertView == null)
{
convertView = new TextView(context);
pro = new Process();
pro.name = (TextView)convertView;
convertView.setTag(pro);
}else
{
pro = (Process)convertView.getTag();
}
pro.name.setText(processes.get(position).processName);
return convertView;
}
class Process
{
public TextView name;
}
}
[/sourcecode]
Display list of process on listview, display name only (just demo).
[sourcecode language="java"]
adp = new MyAdapter(processes, MainActivity.this);
lst.setAdapter(adp);
[/sourcecode]
When user longclick on process name, this process will be kill
[sourcecode language="java"]
lst.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (load == 1) {
for (ActivityManager.RunningAppProcessInfo info : processes) {
if (info.processName.equalsIgnoreCase(
((ActivityManager.RunningAppProcessInfo)parent.getItemAtPosition(position)).processName)) {
// kill selected process
android.os.Process.killProcess(info.pid);
android.os.Process.sendSignal(info.pid, android.os.Process.SIGNAL_KILL);
amg.killBackgroundProcesses(info.processName);
}
}
load = 0;
// refresh list of process
skill_Load_Process();
}
return true;
}
});
[/sourcecode]
You only kill user process, with system process you need a rooted device.
Ok, download sourcecode Here
In this post, we will discussing about how listing and kill background process in Android device.
[caption id="attachment_1855" align="alignnone" width="168"]
List all android background processes[/caption]We need two permission are KILL_BACKGROUND_PROCESSES and to GET_TASKS.
Declare two permission as
[sourcecode language="xml"]
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
<uses-permission android:name="android.permission.GET_TASKS" />
[/sourcecode]
Declare 2 variable
[sourcecode language="java"]
List<ActivityManager.RunningAppProcessInfo> processes;
ActivityManager amg;
[/sourcecode]
Register service with Android get all running processes
[sourcecode language="java"]
// using Activity service to list all process
amg = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
// list all running process
processes = amg.getRunningAppProcesses();
[/sourcecode]
Create MyAdapter class extend BaseAdapter class to populate process's information on ListView as
[sourcecode language="java"]
public class MyAdapter extends BaseAdapter {
List<ActivityManager.RunningAppProcessInfo> processes;
Context context;
public MyAdapter(List<ActivityManager.RunningAppProcessInfo> processes, Context context) {
this.context = context;
this.processes = processes;
}
@Override
public int getCount() {
return processes.size();
}
@Override
public Object getItem(int position) {
return processes.get(position);
}
@Override
public long getItemId(int position) {
return processes.get(position).pid;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Process pro;
if(convertView == null)
{
convertView = new TextView(context);
pro = new Process();
pro.name = (TextView)convertView;
convertView.setTag(pro);
}else
{
pro = (Process)convertView.getTag();
}
pro.name.setText(processes.get(position).processName);
return convertView;
}
class Process
{
public TextView name;
}
}
[/sourcecode]
Display list of process on listview, display name only (just demo).
[sourcecode language="java"]
adp = new MyAdapter(processes, MainActivity.this);
lst.setAdapter(adp);
[/sourcecode]
When user longclick on process name, this process will be kill
[sourcecode language="java"]
lst.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (load == 1) {
for (ActivityManager.RunningAppProcessInfo info : processes) {
if (info.processName.equalsIgnoreCase(
((ActivityManager.RunningAppProcessInfo)parent.getItemAtPosition(position)).processName)) {
// kill selected process
android.os.Process.killProcess(info.pid);
android.os.Process.sendSignal(info.pid, android.os.Process.SIGNAL_KILL);
amg.killBackgroundProcesses(info.processName);
}
}
load = 0;
// refresh list of process
skill_Load_Process();
}
return true;
}
});
[/sourcecode]
You only kill user process, with system process you need a rooted device.
Ok, download sourcecode Here
Monday, October 26, 2015
HTML5 - Xây dựng hình ảnh động đơn giản thông qua đối tượng canvas
Một tiện ích thú vị nhất của HTML5 là hỗ trợ vẽ các đối tượng 2D. Chúng ta có thể vẽ hình tròn, hình chữ nhật, đoạn thẳng, một tấm hình, text, ... lên trang web thông qua các phương thức được hỗ trợ sẵn trong Canvas API của HTML5. Nâng cao hơn nữa, xây dựng một giao diện hoạt hình lên web.
Hôm nay, chúng ta sẽ tìm hiểu một ví dụ đơn giản nhất để có được một hình ảnh động.
Các bước thực hiện:
Code tham khảo:
[sourcecode language="html"]
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HTML5 Animation</title>
<style>
#mySwimmerCanvas{
/*Hiển thị border của canvas*/
border: 2px solid #FF0000
}
</style>
<script>
var positionX = 0;
var positionY = 0;
// Gọi lại hàm draw sau mỗi thời gian 30/1000 giây
setInterval(draw, 30);
//Hàm vẽ người
function draw(){
var centerX = 200; // tọa độ x cho tâm của hình tròn thể hiện cái đầu
var centerY = 50; // tọa độ y cho tâm của hình tròn thể hiện cái đầu
var radius = 20;
// thay đổi tọa độ x, y để thiết lập chuyển động hoạt hình
if (positionX < 30) { positionX += 1; positionY += 1; } else { positionX = 0; positionY = 0; } // khai báo để vẽ các đối tượng 2d lên canvas var canvasSwimmer = document.getElementById("mySwimmerCanvas"); var contextSwimmer = canvasSwimmer.getContext("2d"); //xóa vị trí cũ để vẽ vị trí mới contextSwimmer.clearRect(0,0,400,400); //bắt đầu vẽ contextSwimmer.beginPath(); /*Vẽ đầu (hình tròn) centerX, centerY: tâm đường tròn radius: kích thước bán kính false: vẽ theo chiều kim đồng hồ */ contextSwimmer.arc(centerX, centerY+positionY, radius, 0, 2 * Math.PI, false); contextSwimmer.fillStyle = "#000000"; contextSwimmer.fill(); /* vẽ thân (đoạn thẳng) vẽ nhiều đối tượng lên một canvas -> mỗi đối tượng phải gọi beginPath() lại
*/
contextSwimmer.beginPath();
contextSwimmer.moveTo(200,70+positionY); // điểm thứ nhất để vẽ
contextSwimmer.lineTo(200,175); // điểm thứ hai để vẽ
contextSwimmer.lineWidth = 10; // độ rộng đoạn thẳng
contextSwimmer.strokeStyle = "#000000"; // màu đoạn thẳng
contextSwimmer.lineCap = "round"; // bo tròn hai đầu đoạn thẳng
contextSwimmer.stroke(); // vẽ đoạn thẳng
// vẽ cánh tay bên phải (đoạn thẳng)
contextSwimmer.beginPath();
contextSwimmer.moveTo(200, 100);
contextSwimmer.lineTo(175-positionX,140-positionY);
contextSwimmer.lineWidth = 10;
contextSwimmer.strokeStyle = "#000000";
contextSwimmer.lineCap = "round";
contextSwimmer.stroke();
// vẽ cánh tay bên trái (đoạn thẳng)
contextSwimmer.beginPath();
contextSwimmer.moveTo(200, 100);
contextSwimmer.lineTo(225+positionX,140-positionY);
contextSwimmer.lineWidth = 10;
contextSwimmer.strokeStyle = "#000000";
contextSwimmer.lineCap = "round";
contextSwimmer.stroke();
// vẽ chân bên phải (đoạn thẳng)
contextSwimmer.beginPath();
contextSwimmer.moveTo(200, 175);
contextSwimmer.lineTo(190-positionX,250-positionY);
contextSwimmer.lineWidth = 10;
contextSwimmer.strokeStyle = "#000000";
contextSwimmer.lineCap = "round";
contextSwimmer.stroke();
// vẽ chân bên trái (đoạn thẳng)
contextSwimmer.beginPath();
contextSwimmer.moveTo(200, 175);
contextSwimmer.lineTo(210+positionX,250-positionY);
contextSwimmer.lineWidth = 10;
contextSwimmer.strokeStyle = "#000000";
contextSwimmer.lineCap = "round";
contextSwimmer.stroke();
}
</script>
</head>
<body onload="draw();">
<canvas id="mySwimmerCanvas" width="400" height="400" >
</canvas>
</body>
</html>
[/sourcecode]
Sau khi hoàn thành (nhấp vào hình để xem kết quả hoàn chỉnh):

Chúc các bạn thành công.
Hôm nay, chúng ta sẽ tìm hiểu một ví dụ đơn giản nhất để có được một hình ảnh động.
Vẽ nhiều đối tượng lên một canvas
Để tạo được hoạt hình, chúng ta phải vẽ lại các đối tượng ở các vị trí khác nhau và lặp đi lặp lại việc vẽ này thông qua hàm setInterval trong Javascript.
Các bước thực hiện:
- Tạo đối tượng canvas trong tài liệu để vẽ các hình.
- Tạo hàm draw() để vẽ các đối tượng (mỗi lần vẽ một hình là một trạng thái -> thiết lập một biến có giá trị thay đổi để gán cho vị trí thay đổi).
- Cứ mỗi 30/1000 giây sẽ gọi lại hàm draw() một lần để vẽ lại hình ảnh.
Code tham khảo:
[sourcecode language="html"]
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HTML5 Animation</title>
<style>
#mySwimmerCanvas{
/*Hiển thị border của canvas*/
border: 2px solid #FF0000
}
</style>
<script>
var positionX = 0;
var positionY = 0;
// Gọi lại hàm draw sau mỗi thời gian 30/1000 giây
setInterval(draw, 30);
//Hàm vẽ người
function draw(){
var centerX = 200; // tọa độ x cho tâm của hình tròn thể hiện cái đầu
var centerY = 50; // tọa độ y cho tâm của hình tròn thể hiện cái đầu
var radius = 20;
// thay đổi tọa độ x, y để thiết lập chuyển động hoạt hình
if (positionX < 30) { positionX += 1; positionY += 1; } else { positionX = 0; positionY = 0; } // khai báo để vẽ các đối tượng 2d lên canvas var canvasSwimmer = document.getElementById("mySwimmerCanvas"); var contextSwimmer = canvasSwimmer.getContext("2d"); //xóa vị trí cũ để vẽ vị trí mới contextSwimmer.clearRect(0,0,400,400); //bắt đầu vẽ contextSwimmer.beginPath(); /*Vẽ đầu (hình tròn) centerX, centerY: tâm đường tròn radius: kích thước bán kính false: vẽ theo chiều kim đồng hồ */ contextSwimmer.arc(centerX, centerY+positionY, radius, 0, 2 * Math.PI, false); contextSwimmer.fillStyle = "#000000"; contextSwimmer.fill(); /* vẽ thân (đoạn thẳng) vẽ nhiều đối tượng lên một canvas -> mỗi đối tượng phải gọi beginPath() lại
*/
contextSwimmer.beginPath();
contextSwimmer.moveTo(200,70+positionY); // điểm thứ nhất để vẽ
contextSwimmer.lineTo(200,175); // điểm thứ hai để vẽ
contextSwimmer.lineWidth = 10; // độ rộng đoạn thẳng
contextSwimmer.strokeStyle = "#000000"; // màu đoạn thẳng
contextSwimmer.lineCap = "round"; // bo tròn hai đầu đoạn thẳng
contextSwimmer.stroke(); // vẽ đoạn thẳng
// vẽ cánh tay bên phải (đoạn thẳng)
contextSwimmer.beginPath();
contextSwimmer.moveTo(200, 100);
contextSwimmer.lineTo(175-positionX,140-positionY);
contextSwimmer.lineWidth = 10;
contextSwimmer.strokeStyle = "#000000";
contextSwimmer.lineCap = "round";
contextSwimmer.stroke();
// vẽ cánh tay bên trái (đoạn thẳng)
contextSwimmer.beginPath();
contextSwimmer.moveTo(200, 100);
contextSwimmer.lineTo(225+positionX,140-positionY);
contextSwimmer.lineWidth = 10;
contextSwimmer.strokeStyle = "#000000";
contextSwimmer.lineCap = "round";
contextSwimmer.stroke();
// vẽ chân bên phải (đoạn thẳng)
contextSwimmer.beginPath();
contextSwimmer.moveTo(200, 175);
contextSwimmer.lineTo(190-positionX,250-positionY);
contextSwimmer.lineWidth = 10;
contextSwimmer.strokeStyle = "#000000";
contextSwimmer.lineCap = "round";
contextSwimmer.stroke();
// vẽ chân bên trái (đoạn thẳng)
contextSwimmer.beginPath();
contextSwimmer.moveTo(200, 175);
contextSwimmer.lineTo(210+positionX,250-positionY);
contextSwimmer.lineWidth = 10;
contextSwimmer.strokeStyle = "#000000";
contextSwimmer.lineCap = "round";
contextSwimmer.stroke();
}
</script>
</head>
<body onload="draw();">
<canvas id="mySwimmerCanvas" width="400" height="400" >
</canvas>
</body>
</html>
[/sourcecode]
Sau khi hoàn thành (nhấp vào hình để xem kết quả hoàn chỉnh):

Chúc các bạn thành công.
Subscribe to:
Posts (Atom)

