Thursday, September 4, 2014

Strut2 ví dụ căn bản

 

Basic exercise:

Using Strut 2 to develop login application.

clip_image002

If login fail

clip_image004

If login successful

clip_image006

1. Create Java web application base on Strut2 framework as figure below.

clip_image008

2. Create some file as structure

clip_image009

3. Open struts.xml and modify as

clip_image011

4. Open appResources: create some keys

clip_image012

5. Open Login class and add new code as

clip_image014

6. Generate getter/setter for two field above

clip_image016

7. Next, design login page

clip_image018

8. Next, index.jsp page

clip_image020

9. Next, error.jsp page

clip_image022

10. Now, deploy and run login.jsp page

Strut2-Validation

Using Strut validate input data

clip_image023

If input data invalid

clip_image024

If input data is valid

clip_image025

clip_image027

1. Design customer.jsp as

clip_image029

2. Add some new key to appResources

clip_image030

3. Assign Customer action in struts.xml

clip_image031

4. Add new class with name “Customer” into codes package

clip_image032

5. Generate setter and getter for 4 fields

6. Add new file “Customer-validation.xml” into package

clip_image033

Now, re-deploy and run

Using annotations

All action class must be inside actions package

clip_image034

Strut Controller now change to org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

1 <filter>
2 <filter-name>struts2</filter-name>
3 <filter-class>
4 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
5 </filter-class>
6 <init-param>
7 <param-name>actionPackages</param-name>
8 <param-value>codes</param-value>
9 </init-param>
10 </filter>
11 <filter-mapping>
12 <filter-name>struts2</filter-name>
13 <url-pattern>/*</url-pattern>
14 </filter-mapping>

If your Action extend from ActionSupport, then your Action class name has no rule required.


Ex: Login action beloved


Otherwise, action class name must end with Action string


Ex: account action


1 @Namespace("/")
2 @ResultPath(value = "/")
3 @Results({
4 @Result(name = "success", location = "index.jsp"),
5 @Result(name = "error", location = "error.jsp")}
6 )
7 public class accountAction {
8 @Action(value="account")
9 public String execute() throws Exception {
10 if ("nvmit".equals(getName())) {
11 return SUCCESS;
12 } else {
13 return ERROR;
14 }
15 }
16 private String name ="";
17 public String getName() {
18 return name;
19 }
20 public void setName(String name) {
21 this.name = name;
22 }
23 }

@Namespace Annotation in Struts 2


@Namespace is used at class level or package level. This helps to change the namespace for action class. While accessing or calling action class, it hides package structure. When namespace is applied at package level, all the action of that package gets that namespace as default.


1 @Results({
2 @Result(name = "SUCCESS", location = "/user/index.jsp"),
3 @Result(name = "ERROR", location = "/user/error.jsp")
4 })
5 @Namespaces(
6 @Namespace("/user")
7 )
8 public class Login extends ActionSupport{
9 @Action(value = "/user/login")
10 public String execute() throws Exception {
11 if ("nvmit".equals(getName()) && "nvmit".equals(getPwd())) {
12 return "SUCCESS";
13 } else {
14 return "ERROR";
15 }
16 }
17
18 //Java Bean to hold the form parameters
19 private String name;
20 private String pwd;
21
22 public String getName() {
23 return name;
24 }
25
26 public void setName(String name) {
27 this.name = name;
28 }
29
30 public String getPwd() {
31 return pwd;
32 }
33
34 public void setPwd(String pwd) {
35 this.pwd = pwd;
36 }
37 }
38

The above class can be accessed by @Namespace + @Action that is /user/form
http://localhost:8080/Struts2Demo-1/user/form


Create Project with beloved structure


clip_image035


Project Structure


user/login.jsp


1 <%@ taglib uri="/struts-tags" prefix="s"%>
2 <html>
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
5 <title>Login Page</title>
6 </head>
7 <body>
8 <h3>Welcome User, please login below</h3>
9 <s:form action="/user/login">
10 <s:textfield name="name" label="User Name"></s:textfield>
11 <s:textfield name="pwd" label="Password" type="password"></s:textfield>
12 <s:submit value="Login"></s:submit>
13 </s:form>
14 </body>
15 </html>

user/index.jsp


1 <%@page contentType="text/html" pageEncoding="UTF-8"%>
2 <%@taglib prefix="s" uri="/struts-tags" %>
3 <!DOCTYPE html>
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>JSP Page</title>
8 </head>
9 <body>
10 <h1>Hello <s:property value="name" /></h1>
11 </body>
12 </html>

account.jsp


1 <%@page contentType="text/html" pageEncoding="UTF-8"%>
2 <%@taglib prefix="s" uri="/struts-tags" %>
3 <!DOCTYPE html>
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>JSP Page</title>
8 </head>
9 <body>
10 <h1>Hello <s:property value="name" /></h1>
11 </body>
12 </html>
13

Index.jsp same above


 


Download source code ===> here

Saturday, August 16, 2014

Tài liệu về thiết kê giao diện ứng dụng trên Android (android design guidelines)

Một tài liệu giới thiệu căn bản về thiết kế giao diện trên Android ngắn gọn và hữu ích cho người mới bắt đầu

Download -> android design guidelines

:)

Monday, July 28, 2014

Sử dụng Transaction trên JDBC

Như đã nêu ở bài trước bài này chúng ta sẽ làm ví dụ về quản lý Transaction và batch execute trên jdbc.

JDBC cho phép thực thì hàng loạt thao tác trong một lần gởi yêu cần về server dữ liệu (batch).

Chúng ta ví dụ thêm dữ liệu và 02 bảng đồng thời (Semester và Subject của bài trước).

1 Connection conn; 2 conn = DriverManager.getConnection("jdbc:sqlserver://localhost;user=sa;password=sa;database=java;"); 3 // khoi tao transaction 4 conn.setAutoCommit(false); 5 Statement command = conn.createStatement(); 6 command.addBatch("insert into semester(id,name) values(1,'Semester 1')"); 7 command.addBatch("insert into subject(id,sem_id,name) values(1,1,'HTML')"); 8 command.addBatch("insert into subject(id,sem_id,name) values(2,1,'Java')"); 9 command.addBatch("insert into subject(id,sem_id,name) values(2,1,'csharpe')"); 10 command.executeBatch(); 11 // cap nhat thay doi du lieu ve server 12 conn.setAutoCommit(true);

Nhìn vào đoạn mã trên chúng ta thấy rằng sẽ có 03 dòng dữ liệu được thêm vào hệ thống nhưng dòng cuối cùng thì lỗi trùng khóa chính. Với lệnh

1 conn.setAutoCommit(false);

Chúng ta đã báo cho jdbc biết rằng những thay đổi mà chúng ta đã thực hiện thì chỉ được chấp nhận khi nào chúng ta gọi lệnh

1 conn.setAutoCommit(true);

Do đó, khi chạy ứng dụng chúng ta sẽ kg có dòng nào được thêm vào dữ liệu ở đây do dòng 09 phát sinh lỗi nên dòng 12 sẽ không được thực thi.

Friday, July 18, 2014

Sử dụng stored procedure trong jdbc

 

Cấu trúc dữ liệu

1 IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Semester]') AND type in (N'U'))
2 DROP TABLE [dbo].[Semester]
3 GO
4
5 CREATE TABLE [dbo].[Semester](
6 [id] [int] NOT NULL,
7 [name] [nvarchar](50) NULL,
8 CONSTRAINT [PK_Semester] PRIMARY KEY CLUSTERED
9 (
10 [id] ASC
11 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
12 ) ON [PRIMARY]
13
14 GO
15
16 IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Subject]') AND type in (N'U'))
17 DROP TABLE [dbo].[Subject]
18 GO
19
20 CREATE TABLE [dbo].[Subject](
21 [id] [int] NOT NULL,
22 [sem_id] [int] NOT NULL,
23 [name] [nvarchar](50) NULL,
24 [duration] [int] NULL,
25 CONSTRAINT [PK_Subject] PRIMARY KEY CLUSTERED
26 (
27 [id] ASC,
28 [sem_id] ASC
29 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
30 ) ON [PRIMARY]
31
32 GO

Tạo một storeprocedure như sau


1 CREATE PROCEDURE ListAll
2 @Sem_id int
3 AS
4 BEGIN
5 SELECT * From Subject where sem_id = @Sem_id
6 END
7 GO

Như vậy chúng ta sẽ có được một thủ tục tên là “ListAll”. Đoạn mã sau dùng để gọi thực thi thủ tục trên


1 public void jdbcSQLServer() {
2 try {
3 // dang ky driver
4 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
5 Connection conn;
6 // thiet lap ke noi
7 conn = DriverManager.getConnection("jdbc:sqlserver://localhost;user=sa;password=sa;database=java;");
8 // khoi tao loi goi thuc thi thu tuc
9 CallableStatement command = conn.prepareCall("{call ListAll (?)}");
10 // cung cap gia tro cho bien
11 command.setInt(1, 1);
12 ResultSet result = command.executeQuery();
13 // duyet ket qua
14 while (result.next()) {
15 System.out.print(result.getInt("id"));
16 System.out.println(" - " + result.getString("name"));
17 }
18 // dong ket noi
19 conn.close();
20 } catch (Exception ex) {
21 ex.printStackTrace();
22 }
23 }

Gọi thực thi đoạn mã trên chúng ta có kết quả sau


1 -  HTML
2 -  Java

====>>>> Bài tiếp theo chúng ta tìm hiểu Transaction trên jdbc.

Thursday, July 17, 2014

Căn bản về JDBC – Từng bước kết nối dữ liệu SQL server

  1. Đăng ký Driver.
  2. Thiết lập kết nối với DataBase Server.
  3. Tạo và thực thi câu lệnh.
  4. Xử lý kết quả và đóng kết nối.

Để đăng ký JDBC drive chúng ta sử dụng hàm forName của lớp Class

Đối với odbc:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Cần đăng ký odbc user với hệ điều hành windows (tôi sẽ demo trực tiếp)

http://youtu.be/iRBQm1YrSHY

Đối với jdbc:

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

Cần nhúng thư viện jdbc của sql server vào ứng dụng. download tại jdbc sqlserver driver (phần nhúng vào tôi sẽ demo trực tiếp)

http://youtu.be/cRyPUvkZx-U

Tiếp theo, chúng ta thiết lập kết nối.

Đối với loại kết nối thứ 4 cho sql server

Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost;user=sa;password=sa;database=Northwind;");

Đối với loại kết nối thứ 1

Connection con = DriverManager.getConnection("jdbc:odbc:demo", "sa","sa");

Bước kế tiếp chúng ta tạo câu lệnh đọc dữ liệu và đón nhận thông qua ResultSet

Với odbc

Statement command = con.createStatement();
ResultSet result = command.executeQuery("Select * from Employees");

Với jdbc loại 4

PreparedStatement command = conn.prepareStatement("Select * from Employees where employeeid like ?");
command.setInt(1,id);
ResultSet result = command.executeQuery();

Đoạn trên chúng ta sử dụng dấu ? để tham qui định tham số trong câu lệnh truy vấn, sử dụng các setXXX(số thứ tự tham số bắt đầu = 1) với XXX là loại dữ liệu mối gán vào.

Thao tác cuối cùng là xử lý dữ liệu đã nhận về và đóng kết nối với database server. Trong phần này chúng ta chỉ đơn giản là liệt kê các cột dữ liệu gồm: tên cột, loại dữ liệu và ràng buộc của cột dữ liệu, hiển thị toàn bộ dữ liệu đã nhận được.

1. Thể hiện cấu trúc dữ liệu lấy về (giống nhau cho cả hai loại driver mà chúng ta đã thực hiện lý do là dữ liệu đã lấy về ứng dụng đề được chứa trong ResultSet

ResultSetMetaData rsm = result.getMetaData();

int count = rsm.getColumnCount();
  for(int i=0; i<count;i++) {
     System.out.print("Col " + rsm.getColumnName(i+1));
     System.out.println("is"+rsm.getColumnTypeName(i+1));
}

Chạy thử ứng dụng chúng ta có kết quả như sau:

Col EmployeeID is int identity
Col LastName is nvarchar
Col FirstName is nvarchar
Col Title is nvarchar
Col TitleOfCourtesy is nvarchar
Col BirthDate is datetime
Col HireDate is datetime
Col Address is nvarchar
Col City is nvarchar
Col Region is nvarchar
Col PostalCode is nvarchar
Col Country is nvarchar
Col HomePhone is nvarchar
Col Extension is nvarchar
Col Photo is image
Col Notes is ntext
Col ReportsTo is int
Col PhotoPath is nvarchar
Col Image is nvarchar
Col Hinh is varchar
Col Gender is bit

2. Duyệt và in kết quả ra màn hình

for (int i = 0; i < count; i++) {
  System.out.print("Col"+rsm.getColumnName(i+1) + "\t");
}
System.out.println();
while (result.next()) {
  for (int i = 0; i < count; i++) {
   System.out.print("Col"+result.getString(i + 1)+ "\t");
  }
  System.out.println("");
}

Chạy ứng dụng chúng ta có kết quả sau:

EmployeeID    LastName    FirstName    Title    TitleOfCourtesy   
1    Ngo Tuong Dan    Ngo    null    Ms.   
2    Fuller    Andrew    Vice President, Sales    Dr.   
3    Leverling    Janet    null    Ms.   
4    Peacock    Margaret    Sales Representative    Mrs.   
5    Buchanan    Steven    Sales Manager    Mr.   
6    Suyama    Michael    Sales Representative    Mr.   
7    King    Robert    Sales Representative    Mr.   
8    Callahan    Lauradddd    Inside Sales Coordinator    Ms.

Cuối cùng là đóng kết nối với database server

con.close();

Như vậy là chúng ta đã thực hiện được những thao tác rất rất cơ bản trong sử dụng jdbc để đọc dữ liệu.

>>>> Bài tiếp theo tôi sẽ thực hiện gọi hàm và thủ tục.

Translate