SlideShare a Scribd company logo
Lập trình mạng – Chương 6 1
LẬP TRÌNH WEB VỚI CÁC CÔNG NGHỆ
PHỔ BIẾN
1.1 Giới thiệu Servlet/JSP
1.2 Lập trình web với Servlet
1.3 Lập trình web với JSP
1.4 Giới thiệu ASP
1.5 Lập trình web với ASP
Lập trình mạng – Chương 6 2
1.1 Giới thiệu Servlet/JSP
• Servlet là một ứng dụng (class) Java chạy trên nền web server.
• Cơ chế hoạt động theo mô hình CGI mở rộng.
• Chương trình phải được dịch ra ở dạng byte-code(.class), khai báo với
web server. Web server phải hỗ trợ Java.
• Phải extends class HttpServlet. Không có method main.
Lập trình mạng – Chương 6 3
1.1 Giới thiệu Servlet/JSP
• Cần có package servlet.jar để biên dịch (http://java.sun.com/products/servlet/)
• Các server hiện hỗ trợ Servlet:
• Apache Tomcat (http://jakarta.apache.org)
• Sun’s Java Web Server, free, hiện không cho download
(http://wwws.sun.com/software/jwebserver/)
• New Atlanta’s ServletExec, tích hợp ServletEngine vào các web
server(http://newatlanta.com)
• http://www.macromedia.com/software/jrun/trial/
• …
• Tham khảo các tài liệu về Servlet:
http://java.sun.com/products/servlet/docs.html
Lập trình mạng – Chương 6 4
1.1 Giới thiệu Servlet/JSP
• Cấu trúc đơn giản của một Servlet:
import java.io.*;
import java.servlet.*;
import java.servlet.http.*;
public class Sample extends HttpServlet{
public doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
//dùng đối tượng “request” để đọc dữ liệu từ client
//dùng đối tượng “response” để xuất dữ liệu cho client
PrintWriter out = response.getWriter();
//dùng đối tượng out để ghi (method print) dữ liệu cho client
}
}
Lập trình mạng – Chương 6 5
1.1 Giới thiệu Servlet/JSP
• Biên dịch như một class Java.
• File *.class dịch được phải đặt vào đúng thư mục quy định sẵn của
web server.
• Tomcat: $/webpages/WEB-INF/classes
• JWS: $/servlets
• Cấu hình cho web server đối với mỗi servlet:
• Tomcat: hiệu chỉnh file web.xml trong thư mục $/webpages/WEB-INF theo
DTD http://java.sun.com/j2ee/dtds/web-app_2_2.dtd
• JWS: Cấu hình bằng web-based tool được cung cấp.
Lập trình mạng – Chương 6 6
1.1 Giới thiệu Servlet/JSP
• Cơ chế hoạt động của một servlet:
• Web server nhận yêu cầu triệu gọi servlet từ client.
• Nếu servlet chạy lần đầu, web server load file servlet tương ứng, khởi tạo các thông số
bằng qua method init()
• Nếu servlet đã được khởi tạo, tạo một thread để xử lý yêu cầu.
• Gọi methods doXxx() để xử lý các request tương ứng theo giao thức HTTP.
• doGet(..) cho HTTP GET, doPost cho HTTP POST
Lập trình mạng – Chương 6 7
1.2 Lập trình web với Servlet
• Lấy dữ liệu từ web client gởi đến bằng servlet:
• Dùng đối tượng của class HttpServletRequest
• Các methods để lấy thông số:
• getParameter(“para-name”)
• getParameterValues(“para-name”)
String username= request.getParameter(“username”);
String[] choice = request.getParameterValues(“comments”);
• Dùng đối tượng của class HttpServletRequest để lấy các thông tin HTTP
header
Lập trình mạng – Chương 6 8
1.2 Lập trình web với Servlet
• Ví dụ lấy tất cả các thông số từ client
Enumeration parameter_names = request.getParameterNames();
while(parameter_names.hasMoreElements()){
String para = parameter_names.nextElement();
out.print(para + “ = ”);
String[] paraValues = getParameterValues(para);
if(paraValues.lenght()==1){
out.println(paraValues[0]);
}else{
for(int i = 0, i< paraValues.lenght(),i++){
out.print(paraValues[i]+ “-”);
}
}
}
Lập trình mạng – Chương 6 9
1.2 Lập trình web với Servlet
• Lấy các thông số HTTP request header: class HttpServletRequest cung
cấp các method để lấy các thông số request header.
• String getHeader(header-name): lấy nội dung của header-name
• Enumeration getHeaderNames(): lấy tất cả các header-name.
• Một số method điển hình:
• Cookie[] getCookies(): dãy Cookie từ client
• int getContentLength(): trả giá trị Content-Length
• int getContentType(): trả giá trị Content-Type
• int getRemoteUser(): giá trị username nếu có authenticate
Lập trình mạng – Chương 6 10
1.2 Lập trình web với Servlet
• Lấy các thông số HTTP request header:
• Lấy các giá trị của biến môi trường CGI:
• QUERY_STRING: getQueryString()
• REMOTE_ADDR: getRemoteAddr()
• REMOTE_HOST: getRemoteHost()
• REQUEST_METHOD: getMethod()
• PATH_INFO: getPathInfo()
• SCRIPT_NAME: getServletPath()
• SERVER_NAME: getServerName()
• SERVER_PORT: getServerPort()
• HTTP_XXX_YYY: getHeader(“Xxx-Yyy”)
• …
Lập trình mạng – Chương 6 11
1.2 Lập trình web với Servlet
• Gởi dữ liệu cho web client: dùng đối tượng của class
HttpServletResponse:
• Tạo đối tượng PrintWriter để ghi dữ liệu gởi
• PrintWriter out = response.getWriter();
• Xử lý các mã HTTP trả về với các method của class HttpServletResponse:
• void setStatus(int statusCode): gởi các mã response
• void sendError(int errorCode,String msg): gởi mã lỗi theo giao thức HTTP và message
• void sendRedirect(String URL): chuyển đến một trang URL khác
• Các mã có thể theo giao thức HTTP hoặc dùng các hằng số trong class
HttpServletResponse.
Lập trình mạng – Chương 6 12
1.2 Lập trình web với Servlet
• Xử lý Cookie với web browser:
• Chức năng Cookie
• Kết hợp với web browser để lưu các thông số cần thiết.
• Thông tin có thể dùng để thiết lập phiên làm việc(session) trong các ứng dụng thương
mại điện tử(e-commerce).
• Lưu trữ username, password
• Thông tin để customize web site cho user hay dùng cho cơ chế personalization
• …
Lập trình mạng – Chương 6 13
1.2 Lập trình web với Servlet
• Ghi thông tin Cookie lên máy client:
• Thông tin được truyền đi trong field Set-Cookie HTTP header
• Dùng method addCookie(Cookie cookie) của class HttpServletResponse.
• Các thuộc tính quan trọng trong class Cookie:
• Cookie name: setName(String name) – getName()
• Cookie value: setValue(String value) – getValue()
• Max Age: setMaxAge(int seconds) – getMaxAge()
Lập trình mạng – Chương 6 14
1.2 Lập trình web với Servlet
• Ví dụ:
String user=“”,pass=“”;
Cookie[] cookies = request.getCookies();
if(cookies.length==0){
user = request.getParameter(“username”);
pass = request.getParameter(“password”);
Cookie name_cookie = new Cookie(“username”,user); response.addCookie(name_cookie);
Cookie pass_cookie = new Cookie(“password”,pass); response.addCookie(pass_cookie);
}else{
for(int i=0;i<cookies.length;i++){
Cookie cookie = cookies[i];
if(cookie.getName().equals(“username”)) user=cookie.getValue();
if(cookie.getName().equals(“password”)) pass=cookie.getValue();
}
}
Lập trình mạng – Chương 6 15
1.2 Lập trình web với Servlet
• Lưu thông tin về phiên làm việc của user: class HttpSession.
• Có thể dùng để lưu bất kỳ đối tượng nào.
• Đối tượng của class HttpSession được trả về từ method getSession() của class
HttpServletRequest.
• Các method thường sử dụng:
• Object getValue(String name) [2.2: getAttribute]
• void putValue(String name,Object object) [2.2: putAttribute]
• void removeValue(String name) [2.2: removeAttribute]
• String[] getValueNames() [Enumeration getAttributeNames()]
• String getId()
• void setMaxInactiveInterval(int seconds)
Lập trình mạng – Chương 6 16
1.2 Lập trình web với Servlet
• Ví dụ lưu ShoppingCart vào session
HttpSession session = request.getSession(true);
ShoppingCart cart = (ShoppingCart)session.getValue(“ShoppingCart”);
if(cart==null){
cart = new ShoppingCart();
session.putValue(“ShoppingCart”,cart);
}
//process(cart)
Lập trình mạng – Chương 6 17
1.2 Lập trình web với Servlet
• Xử lý kết nối database
• Dùng JDBC (Java DataBase Connectivity) để kết nối và thao tác với database.
• Quy trình xử lý:
• Tạo JDBC driver và URL database
• Thiết lập connection đến URL database
• Tạo đối tượng statement
• Thực thi các câu lệnh SQL
• Xử lý kết quả thực thi
• Đóng kết nối đến database.
Lập trình mạng – Chương 6 18
1.2 Lập trình web với Servlet
• Kết nối đến database thông qua OBDC trên Windows:
• Tạo DataSourceName trong ODBC
Connection con = null; Statement stmt = null; ResultSet rs = null;
String driver = “sun.jdbc.odbc.JdbcOdbcDriver”;
String databaseURL = “jdbc:odbc:DataSourceName”;
try{
Class.forName(driver);
con = DriverManager.getConnection(databaseURL);
stmt = con.createStatement()
rs = stmt.executeQuery(“SELECT * FROM Products”);
while(rs.next()){
out.println(rs.getString[1]+”-” getInt(“quantity”));//…
}
con.close();
}cacth(SQLException se){ con.close(); }
Lập trình mạng – Chương 6 19
1.2 Lập trình web với Servlet
• Có thể kết nối database server bất kỳ có driver hỗ trợ.
• Kết nối đến Oracle Database Server:
driver=“oracle.jdbc.driver.OracleDriver”
databaseURL =“jdbc:oracle:thin@localhost:1521:”+dbName
con = DriverManager.getConnection(databaseURL,user,password)
• Kết nối đến Sysbase:
driver=“com.sysbase.jdbc.SysDriver”
databaseURL = “jdbc:sysbase:Tds:localhost:1521?SERVICENAME=“+dbName
con = DriverManager.getConnection(databaseURL,user,password)
Lập trình mạng – Chương 6 20
1.2 Lập trình web với Servlet
• Dùng Prepared Statements trong các câu lệnh thay đổi dữ liệu:
String preSQLString =
“UPDATE students SET score = ? WHERE ID=?”;
PreparedStatement pre_stmt= connection.prepareStatement(preSQLString);
float[] scores = getScores();
String[] studentIDs = getStudentIDs();
for(int i=0;i< studentIDs.length;i++){
pre_stmt.setFloat(1,scores[i]);
pre_stmt.setString(2, studentIDs[i]);
pre_stmt.execute();
}
Lập trình mạng – Chương 6 21
1.2 Lập trình web với Servlet
• Dùng cơ chế Connection Pooling
• Tạo một dãy các Connection sẵn sàng.
• Dùng cơ chế thread và đồng bộ để chia xẻ các Connection.
public synchronized Connection getConnection() throws SQLException{
if(!availableConnections.isEmpty()){
Connection con = availableConnections.lastElement();
availableConnections.removeElementAt(
availableConnections.size()-1);
busyConnections.addElement(con);
return con;
}else{
//…
}
}
Lập trình mạng – Chương 6 22
1.3 Lập trình web với JSP
• JSP (Java Server Pages) là một trang HTML xen các đoạn mã Java.
• Trang JSP sẽ được web server biên dịch theo thành bytecode, cơ chế
hoạt động tương tự như Servlet.
• Được tạo sẵn các đối tượng của các class HttpServletRequest và
HttpServletResponse để xử lý giao tiếp với web client.
Lập trình mạng – Chương 6 23
1.3 Lập trình web với JSP
• Các đoạn mã Java trong trang JSP được đặt trong tag: <% %>
• Giá trị biểu thức: <%= biểu thức %>
• Khai báo các biếm <%! [type variable;]+ %>
• Java code <% Java code %>
• Chú thích <%-- comments --%>
• Các khai báo chỉ thị (derective):
• <%@ page import=“[package][,package]*” %>
• <%@ page isThreadSafe=“{true|false}” %>
• <%@ page session=“{true|false}” %>
• <%@ include file=“filename” %>
Lập trình mạng – Chương 6 24
1.3 Lập trình web với JSP
Ví dụ trang JSP
<html>
<body bgcolor="white">
<h1> Request Information </h1>
<font size="4">
JSP Request Method: <jsp:expr> request.getMethod() </jsp:expr>
<br>
Request URI: <jsp:expr> request.getRequestURI() </jsp:expr>
<br>
Request Protocol: <jsp:expr> request.getProtocol() </jsp:expr>
<br>
Servlet path: <jsp:expr> request.getServletPath() </jsp:expr>
<br>
Path info: <jsp:expr> request.getPathInfo() </jsp:expr>
<br>
Path translated: <%= request.getPathTranslated() %>
…
Lập trình mạng – Chương 6 25
1.3 Lập trình web với JSP
<%@ page import=“beans.*" session="true" autoFlush="true" buffer="none" %>
<%! Const con = new Const();%>
<jsp:useBean id="check" scope="page" class="beans.CheckAdmin" />
<html> <head>
<SCRIPT language="JavaScript" src="Scripts/ImagesOver.js" type="text/javascript"></SCRIPT>
<title>Check admin account</title>
<META content="text/html; charset=x-user-defined" http-equiv=Content-Type>
<LINK href=“Images/linkref.css" rel=stylesheet> </head>
<body background="Images/StarStuds.gif">
<%
out.println(con.getHeader());
check.processRequest(request);
if(check.check()==true){
out.println("Hello administrator <b>"+check.getName()+"</b>");
}
else{ %>
<br>Invalid password.Please <a href="admin_logon.jsp">try</a> again
<%}
out.println(con.getFooter());
%>
Lập trình mạng – Chương 6 26
1.3 Lập trình web với JSP
• Các đối tượng được xây dựng sẵn trong một trang JSP:
• request: đối tượng class HttpServletRequest
• response: đối tượng class HttpServletResponse
• out: đối tượng class PrintWriter
• session: đối tượng class HttpSession tạo ra từ method getSession() của đối
tượng request
• application: đối tượng class ServletContext
• config: đối tượng class ServletConfig
Lập trình mạng – Chương 6 27
1.4 Giới thiệu ASP
• ASP là một trang HTML có chứa các mã script (VBScript hay
JavaScript). Các script này có thể:
• Lấy thông tin từ user.
• Sinh nội dung động.
• Thao tác với database.
• …
• Trang ASP được chạy trên web-server hỗ trợ (server-side)
Lập trình mạng – Chương 6 28
1.4 Giới thiệu ASP
• Các công cụ:
• Soạn thảo :
• Có thể dùng trình soạn thảo văn bản text bất kỳ.
• Các công cụ trực quan : Ms. Visual InterDev, Ms. FrontPage, Macromedia Dreamweaver…
• Web server:
• Win9x : Personal Web Server
• Win NT/2000 : Internet Information Services.
• Chili!Soft : http://www.ChiliSoft.com (UNIX support)
• HalcyonSoft : http://www.halcyonsoft.com
Lập trình mạng – Chương 6 29
1.4 Giới thiệu ASP
• Thêm script xử lý vào trang ASP:
• Đặt mã trong cặp dấu : <%...%>
• Ví dụ : <HTML><BODY>
<% REM Hello World ! ASP %>
</BODY></HTML>
• Dùng tag SCRIPT :
• <SCRIPT RUNAT=“SERVER”>….</SCRIPT>
• Ví dụ : <HTML><BODY>
<SCRIPT RUNAT=“SERVER”> REM Hello World
</SCRIPT>
</BODY></HTML>
Lập trình mạng – Chương 6 30
1.5 Lập trình web với ASP
• Đối tượng xử lý request sẵn có của ASP: Request.
• Lấy thông tin người dùng nhập từ Form:
• Request.Form(“field_name”)
• Request.Form(index)
• Một số field đặc biệt : checkbox, ratio, các field cùng tên…
Lập trình mạng – Chương 6 31
6.5 Lập trình web với ASP
•Đối tượng xử lý response sẵn có của ASP:
Response
•Các phương thức chính:
• Reponse.Write(“String”)
• Reponse.Redirect(“URL”)
Lập trình mạng – Chương 6 32
1.5 Lập trình web với ASP
• Đối tượng Application:
• Quản lý thông tin về ứng dụng. Có thể dùng để lưu trữ dữ liệu, đối tượng.
• Đối tượng Session:
• Quản lý thông tin về phiên làm việc(session), có thể lưu dữ liệu, đối tượng
của một session
• Đố tượng Server:
• Đặt các thuộc tính, tạo đối tượng mới…
Lập trình mạng – Chương 6 33
1.5 Lập trình web với ASP
• Thao tác database: có thể dùng ADO để thao tác.
• Ví dụ về đọc dữ liệu từ database
Dim objRecordset
Set objRecordset = Server.CreateObject(“ADODB.Recordset”)
objRecordset.Open “table-name”, “DSN=dsn”
Do While NOT objRecordset.EOF
Response.Write objRecordset(“field-name”)
objRecordset.MoveNext
Loop
Lập trình mạng – Chương 6 34
1.5 Lập trình web với ASP
• Đọc dữ liệu bằng câu lệnh SQL:
strSQL = “Select * FROM table WHERE ….”
objRecordset.Open strSQL, “DSN=dsn”
• Dùng in dữ liệu theo dạng bảng, danh sách, listbox…
• Có thể dùng cách này để hiện thực việc tìm kiếm.
Lập trình mạng – Chương 6 35
1.5 Lập trình web với ASP
• Thêm mới record:
Set obj-Recordset-name = Server.CreateObject(“ADODB.Recordset”)
objRecordset-name.Open “table-name”, “DSN=dsn”, _ adOpenDynamic,
adLockOptimistic
obj-Recordset-name.AddNew
obj-Recordset-name.Fields(“field-name”) = …
obj-Recordset-name.Update
‘….
obj-Recordset-name.Close
Lập trình mạng – Chương 6 36
1.5 Lập trình web với ASP
• Cập nhật thông tin trong record:
strSQLUpdate = “UPDATE table SET field1=…, field2=… WHERE …”
objRecordset. Excute strSQLUpdate

More Related Content

What's hot

React js - Component specs and lifecycle
React js - Component specs and lifecycleReact js - Component specs and lifecycle
React js - Component specs and lifecycle
Doanh PHAM
 
Monitor và tối ưu sql server
Monitor và tối ưu sql serverMonitor và tối ưu sql server
Monitor và tối ưu sql server
Huân Bùi Đình
 
Technical note playframework_documentation_working with play - java_vn
Technical note playframework_documentation_working with play - java_vnTechnical note playframework_documentation_working with play - java_vn
Technical note playframework_documentation_working with play - java_vn
Asahina Infotech
 
Ajax control toolkit
Ajax control toolkitAjax control toolkit
Ajax control toolkitNguyen Huy
 
ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015
ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015
ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015
IT Expert Club
 
Kinh nghiệm triển khai Microservices tại Sapo.vn
Kinh nghiệm triển khai Microservices tại Sapo.vnKinh nghiệm triển khai Microservices tại Sapo.vn
Kinh nghiệm triển khai Microservices tại Sapo.vn
Dotnet Open Group
 
Domain Driven Design và Event Driven Architecture
Domain Driven Design và Event Driven Architecture Domain Driven Design và Event Driven Architecture
Domain Driven Design và Event Driven Architecture
IT Expert Club
 
Hướng dẫn xây dựng ứng dụng web theo mô hình MVC bằng ngôn ngữ Java
Hướng dẫn xây dựng ứng dụng web theo mô hình MVC bằng ngôn ngữ JavaHướng dẫn xây dựng ứng dụng web theo mô hình MVC bằng ngôn ngữ Java
Hướng dẫn xây dựng ứng dụng web theo mô hình MVC bằng ngôn ngữ Java
Huy Vũ
 
Vue.js
Vue.jsVue.js
Web203 slide 5
Web203   slide 5Web203   slide 5
Web203 slide 5
tuanduongcntt
 
ITLC HN 14 - Bizweb Microservices Architecture
ITLC HN 14  - Bizweb Microservices ArchitectureITLC HN 14  - Bizweb Microservices Architecture
ITLC HN 14 - Bizweb Microservices Architecture
IT Expert Club
 
Giới thiệu zk framework
Giới thiệu  zk frameworkGiới thiệu  zk framework
Giới thiệu zk framework
nguyễn ngọc viện
 
Bài 1 Lập trình website theo mô hình MVC - Xây dựng ứng dụng web
Bài 1 Lập trình website theo mô hình MVC - Xây dựng ứng dụng webBài 1 Lập trình website theo mô hình MVC - Xây dựng ứng dụng web
Bài 1 Lập trình website theo mô hình MVC - Xây dựng ứng dụng web
MasterCode.vn
 
Bizweb Microservices Architecture
Bizweb Microservices ArchitectureBizweb Microservices Architecture
Bizweb Microservices Architecture
Khôi Nguyễn Minh
 
itlchn 20 - Kien truc he thong chung khoan - Phan 2
itlchn 20 - Kien truc he thong chung khoan - Phan 2itlchn 20 - Kien truc he thong chung khoan - Phan 2
itlchn 20 - Kien truc he thong chung khoan - Phan 2
IT Expert Club
 
Giới thiệu Embulk
Giới thiệu Embulk Giới thiệu Embulk
Giới thiệu Embulk
GMO-Z.com Vietnam Lab Center
 
Phương pháp và chiến lược đối ứng tải trong Web Application Server
Phương pháp và chiến lược đối ứng tải trong Web Application ServerPhương pháp và chiến lược đối ứng tải trong Web Application Server
Phương pháp và chiến lược đối ứng tải trong Web Application Server
GMO-Z.com Vietnam Lab Center
 
Nodejs Introduction
Nodejs IntroductionNodejs Introduction
Nodejs Introduction
thanh can
 

What's hot (20)

Ch06
Ch06Ch06
Ch06
 
React js - Component specs and lifecycle
React js - Component specs and lifecycleReact js - Component specs and lifecycle
React js - Component specs and lifecycle
 
Monitor và tối ưu sql server
Monitor và tối ưu sql serverMonitor và tối ưu sql server
Monitor và tối ưu sql server
 
Technical note playframework_documentation_working with play - java_vn
Technical note playframework_documentation_working with play - java_vnTechnical note playframework_documentation_working with play - java_vn
Technical note playframework_documentation_working with play - java_vn
 
Ajax control toolkit
Ajax control toolkitAjax control toolkit
Ajax control toolkit
 
ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015
ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015
ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015
 
Kinh nghiệm triển khai Microservices tại Sapo.vn
Kinh nghiệm triển khai Microservices tại Sapo.vnKinh nghiệm triển khai Microservices tại Sapo.vn
Kinh nghiệm triển khai Microservices tại Sapo.vn
 
Domain Driven Design và Event Driven Architecture
Domain Driven Design và Event Driven Architecture Domain Driven Design và Event Driven Architecture
Domain Driven Design và Event Driven Architecture
 
Ung dun web chuong 2
Ung dun web  chuong 2Ung dun web  chuong 2
Ung dun web chuong 2
 
Hướng dẫn xây dựng ứng dụng web theo mô hình MVC bằng ngôn ngữ Java
Hướng dẫn xây dựng ứng dụng web theo mô hình MVC bằng ngôn ngữ JavaHướng dẫn xây dựng ứng dụng web theo mô hình MVC bằng ngôn ngữ Java
Hướng dẫn xây dựng ứng dụng web theo mô hình MVC bằng ngôn ngữ Java
 
Vue.js
Vue.jsVue.js
Vue.js
 
Web203 slide 5
Web203   slide 5Web203   slide 5
Web203 slide 5
 
ITLC HN 14 - Bizweb Microservices Architecture
ITLC HN 14  - Bizweb Microservices ArchitectureITLC HN 14  - Bizweb Microservices Architecture
ITLC HN 14 - Bizweb Microservices Architecture
 
Giới thiệu zk framework
Giới thiệu  zk frameworkGiới thiệu  zk framework
Giới thiệu zk framework
 
Bài 1 Lập trình website theo mô hình MVC - Xây dựng ứng dụng web
Bài 1 Lập trình website theo mô hình MVC - Xây dựng ứng dụng webBài 1 Lập trình website theo mô hình MVC - Xây dựng ứng dụng web
Bài 1 Lập trình website theo mô hình MVC - Xây dựng ứng dụng web
 
Bizweb Microservices Architecture
Bizweb Microservices ArchitectureBizweb Microservices Architecture
Bizweb Microservices Architecture
 
itlchn 20 - Kien truc he thong chung khoan - Phan 2
itlchn 20 - Kien truc he thong chung khoan - Phan 2itlchn 20 - Kien truc he thong chung khoan - Phan 2
itlchn 20 - Kien truc he thong chung khoan - Phan 2
 
Giới thiệu Embulk
Giới thiệu Embulk Giới thiệu Embulk
Giới thiệu Embulk
 
Phương pháp và chiến lược đối ứng tải trong Web Application Server
Phương pháp và chiến lược đối ứng tải trong Web Application ServerPhương pháp và chiến lược đối ứng tải trong Web Application Server
Phương pháp và chiến lược đối ứng tải trong Web Application Server
 
Nodejs Introduction
Nodejs IntroductionNodejs Introduction
Nodejs Introduction
 

Similar to Lập trình web với các công nghệ phổ biến

Kiến thức cần thiết làm việc
Kiến thức cần thiết làm việcKiến thức cần thiết làm việc
Kiến thức cần thiết làm việcmanhvokiem
 
Bai2 tong quan_mvc_0567
Bai2 tong quan_mvc_0567Bai2 tong quan_mvc_0567
Bai2 tong quan_mvc_0567
Ham Chơi
 
Bài 3: Servlet - Lập Trình Mạng Nâng Cao
Bài 3: Servlet - Lập Trình Mạng Nâng CaoBài 3: Servlet - Lập Trình Mạng Nâng Cao
Bài 3: Servlet - Lập Trình Mạng Nâng Cao
Tuan Nguyen
 
JavaEE Basic_Chapter4: Servlet Nâng Cao
JavaEE Basic_Chapter4: Servlet Nâng CaoJavaEE Basic_Chapter4: Servlet Nâng Cao
JavaEE Basic_Chapter4: Servlet Nâng Cao
Phaolo Pham
 
Lập trình web asp.net MVC
Lập trình web asp.net MVCLập trình web asp.net MVC
Lập trình web asp.net MVC
MasterCode.vn
 
chuong_02.ppt
chuong_02.pptchuong_02.ppt
chuong_02.ppt
ThuyKhoaCNTTNguyenTh
 
Báo cáo tuần đồ án
Báo cáo tuần đồ ánBáo cáo tuần đồ án
Báo cáo tuần đồ án
Lưu Việt Tùng
 
Web301 slide 1
Web301   slide 1Web301   slide 1
Web301 slide 1
tuanduongcntt
 
Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...
Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...
Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...
VKhang Yang
 
Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winfor...
Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winfor...Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winfor...
Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winfor...
MasterCode.vn
 
Các bước kết nối csdl my sql với java
Các bước kết nối csdl my sql với javaCác bước kết nối csdl my sql với java
Các bước kết nối csdl my sql với java
Brand Xanh
 
Bài 3: Servlet&Cookie&Session - Lập Trình Mạng Nâng Cao
Bài 3: Servlet&Cookie&Session - Lập Trình Mạng Nâng CaoBài 3: Servlet&Cookie&Session - Lập Trình Mạng Nâng Cao
Bài 3: Servlet&Cookie&Session - Lập Trình Mạng Nâng Cao
Tuan Nguyen
 
Sapo Microservices Architecture
Sapo Microservices ArchitectureSapo Microservices Architecture
Sapo Microservices Architecture
Khôi Nguyễn Minh
 
2.gioi thieu co ban ado.net cho nguoi lap trinh c#
2.gioi thieu co ban ado.net cho nguoi lap trinh c#2.gioi thieu co ban ado.net cho nguoi lap trinh c#
2.gioi thieu co ban ado.net cho nguoi lap trinh c#Dao Uit
 
Arrowjs.io
Arrowjs.ioArrowjs.io
Arrowjs.io
TechMaster Vietnam
 
Bai44-48.pptx
Bai44-48.pptxBai44-48.pptx
Bai44-48.pptx
BuiManhHung3
 

Similar to Lập trình web với các công nghệ phổ biến (20)

Kiến thức cần thiết làm việc
Kiến thức cần thiết làm việcKiến thức cần thiết làm việc
Kiến thức cần thiết làm việc
 
Bai2 tong quan_mvc_0567
Bai2 tong quan_mvc_0567Bai2 tong quan_mvc_0567
Bai2 tong quan_mvc_0567
 
Bài 3: Servlet - Lập Trình Mạng Nâng Cao
Bài 3: Servlet - Lập Trình Mạng Nâng CaoBài 3: Servlet - Lập Trình Mạng Nâng Cao
Bài 3: Servlet - Lập Trình Mạng Nâng Cao
 
Apache+ q logs
Apache+ q logsApache+ q logs
Apache+ q logs
 
JavaEE Basic_Chapter4: Servlet Nâng Cao
JavaEE Basic_Chapter4: Servlet Nâng CaoJavaEE Basic_Chapter4: Servlet Nâng Cao
JavaEE Basic_Chapter4: Servlet Nâng Cao
 
Lập trình web asp.net MVC
Lập trình web asp.net MVCLập trình web asp.net MVC
Lập trình web asp.net MVC
 
chuong_02.ppt
chuong_02.pptchuong_02.ppt
chuong_02.ppt
 
Aspnet 3.5 _04
Aspnet 3.5 _04Aspnet 3.5 _04
Aspnet 3.5 _04
 
Báo cáo tuần đồ án
Báo cáo tuần đồ ánBáo cáo tuần đồ án
Báo cáo tuần đồ án
 
Web301 slide 1
Web301   slide 1Web301   slide 1
Web301 slide 1
 
Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...
Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...
Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...
 
Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winfor...
Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winfor...Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winfor...
Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winfor...
 
Các bước kết nối csdl my sql với java
Các bước kết nối csdl my sql với javaCác bước kết nối csdl my sql với java
Các bước kết nối csdl my sql với java
 
Asp control
Asp controlAsp control
Asp control
 
Bài 3: Servlet&Cookie&Session - Lập Trình Mạng Nâng Cao
Bài 3: Servlet&Cookie&Session - Lập Trình Mạng Nâng CaoBài 3: Servlet&Cookie&Session - Lập Trình Mạng Nâng Cao
Bài 3: Servlet&Cookie&Session - Lập Trình Mạng Nâng Cao
 
Sapo Microservices Architecture
Sapo Microservices ArchitectureSapo Microservices Architecture
Sapo Microservices Architecture
 
2.gioi thieu co ban ado.net cho nguoi lap trinh c#
2.gioi thieu co ban ado.net cho nguoi lap trinh c#2.gioi thieu co ban ado.net cho nguoi lap trinh c#
2.gioi thieu co ban ado.net cho nguoi lap trinh c#
 
Arrowjs.io
Arrowjs.ioArrowjs.io
Arrowjs.io
 
Bai44-48.pptx
Bai44-48.pptxBai44-48.pptx
Bai44-48.pptx
 
Ung dung web chuong 6
Ung dung web  chuong 6Ung dung web  chuong 6
Ung dung web chuong 6
 

More from Son Nguyen

Wsdl connector introduction
Wsdl connector introductionWsdl connector introduction
Wsdl connector introduction
Son Nguyen
 
Android intergrate with mule
Android intergrate with muleAndroid intergrate with mule
Android intergrate with mule
Son Nguyen
 
Mule flow overview
Mule flow overviewMule flow overview
Mule flow overview
Son Nguyen
 
Mule flow and filter
Mule flow and filterMule flow and filter
Mule flow and filter
Son Nguyen
 
Handle exceptions in mule
Handle exceptions in muleHandle exceptions in mule
Handle exceptions in mule
Son Nguyen
 
Spring security integrate with mule
Spring security integrate with muleSpring security integrate with mule
Spring security integrate with mule
Son Nguyen
 
Message processor in mule
Message processor in muleMessage processor in mule
Message processor in mule
Son Nguyen
 
Expression language in mule
Expression language in muleExpression language in mule
Expression language in mule
Son Nguyen
 
Mule with data weave
Mule with data weaveMule with data weave
Mule with data weave
Son Nguyen
 
Using spring scheduler mule
Using spring scheduler muleUsing spring scheduler mule
Using spring scheduler mule
Son Nguyen
 
Composite source in bound and out-bound
Composite source in bound and out-boundComposite source in bound and out-bound
Composite source in bound and out-bound
Son Nguyen
 
Batch job processing
Batch job processingBatch job processing
Batch job processing
Son Nguyen
 
Using message enricher
Using message enricherUsing message enricher
Using message enricher
Son Nguyen
 
Finance connectors with mule
Finance connectors with muleFinance connectors with mule
Finance connectors with mule
Son Nguyen
 
Google drive connection
Google drive connectionGoogle drive connection
Google drive connection
Son Nguyen
 
Using properties in mule
Using properties in muleUsing properties in mule
Using properties in mule
Son Nguyen
 
Mule integrate with microsoft
Mule integrate with microsoftMule integrate with microsoft
Mule integrate with microsoft
Son Nguyen
 
Jms queue
Jms queueJms queue
Jms queue
Son Nguyen
 
Anypoint connectors
Anypoint connectorsAnypoint connectors
Anypoint connectors
Son Nguyen
 
Mule esb basic introduction
Mule esb basic introductionMule esb basic introduction
Mule esb basic introduction
Son Nguyen
 

More from Son Nguyen (20)

Wsdl connector introduction
Wsdl connector introductionWsdl connector introduction
Wsdl connector introduction
 
Android intergrate with mule
Android intergrate with muleAndroid intergrate with mule
Android intergrate with mule
 
Mule flow overview
Mule flow overviewMule flow overview
Mule flow overview
 
Mule flow and filter
Mule flow and filterMule flow and filter
Mule flow and filter
 
Handle exceptions in mule
Handle exceptions in muleHandle exceptions in mule
Handle exceptions in mule
 
Spring security integrate with mule
Spring security integrate with muleSpring security integrate with mule
Spring security integrate with mule
 
Message processor in mule
Message processor in muleMessage processor in mule
Message processor in mule
 
Expression language in mule
Expression language in muleExpression language in mule
Expression language in mule
 
Mule with data weave
Mule with data weaveMule with data weave
Mule with data weave
 
Using spring scheduler mule
Using spring scheduler muleUsing spring scheduler mule
Using spring scheduler mule
 
Composite source in bound and out-bound
Composite source in bound and out-boundComposite source in bound and out-bound
Composite source in bound and out-bound
 
Batch job processing
Batch job processingBatch job processing
Batch job processing
 
Using message enricher
Using message enricherUsing message enricher
Using message enricher
 
Finance connectors with mule
Finance connectors with muleFinance connectors with mule
Finance connectors with mule
 
Google drive connection
Google drive connectionGoogle drive connection
Google drive connection
 
Using properties in mule
Using properties in muleUsing properties in mule
Using properties in mule
 
Mule integrate with microsoft
Mule integrate with microsoftMule integrate with microsoft
Mule integrate with microsoft
 
Jms queue
Jms queueJms queue
Jms queue
 
Anypoint connectors
Anypoint connectorsAnypoint connectors
Anypoint connectors
 
Mule esb basic introduction
Mule esb basic introductionMule esb basic introduction
Mule esb basic introduction
 

Lập trình web với các công nghệ phổ biến

  • 1. Lập trình mạng – Chương 6 1 LẬP TRÌNH WEB VỚI CÁC CÔNG NGHỆ PHỔ BIẾN 1.1 Giới thiệu Servlet/JSP 1.2 Lập trình web với Servlet 1.3 Lập trình web với JSP 1.4 Giới thiệu ASP 1.5 Lập trình web với ASP
  • 2. Lập trình mạng – Chương 6 2 1.1 Giới thiệu Servlet/JSP • Servlet là một ứng dụng (class) Java chạy trên nền web server. • Cơ chế hoạt động theo mô hình CGI mở rộng. • Chương trình phải được dịch ra ở dạng byte-code(.class), khai báo với web server. Web server phải hỗ trợ Java. • Phải extends class HttpServlet. Không có method main.
  • 3. Lập trình mạng – Chương 6 3 1.1 Giới thiệu Servlet/JSP • Cần có package servlet.jar để biên dịch (http://java.sun.com/products/servlet/) • Các server hiện hỗ trợ Servlet: • Apache Tomcat (http://jakarta.apache.org) • Sun’s Java Web Server, free, hiện không cho download (http://wwws.sun.com/software/jwebserver/) • New Atlanta’s ServletExec, tích hợp ServletEngine vào các web server(http://newatlanta.com) • http://www.macromedia.com/software/jrun/trial/ • … • Tham khảo các tài liệu về Servlet: http://java.sun.com/products/servlet/docs.html
  • 4. Lập trình mạng – Chương 6 4 1.1 Giới thiệu Servlet/JSP • Cấu trúc đơn giản của một Servlet: import java.io.*; import java.servlet.*; import java.servlet.http.*; public class Sample extends HttpServlet{ public doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{ //dùng đối tượng “request” để đọc dữ liệu từ client //dùng đối tượng “response” để xuất dữ liệu cho client PrintWriter out = response.getWriter(); //dùng đối tượng out để ghi (method print) dữ liệu cho client } }
  • 5. Lập trình mạng – Chương 6 5 1.1 Giới thiệu Servlet/JSP • Biên dịch như một class Java. • File *.class dịch được phải đặt vào đúng thư mục quy định sẵn của web server. • Tomcat: $/webpages/WEB-INF/classes • JWS: $/servlets • Cấu hình cho web server đối với mỗi servlet: • Tomcat: hiệu chỉnh file web.xml trong thư mục $/webpages/WEB-INF theo DTD http://java.sun.com/j2ee/dtds/web-app_2_2.dtd • JWS: Cấu hình bằng web-based tool được cung cấp.
  • 6. Lập trình mạng – Chương 6 6 1.1 Giới thiệu Servlet/JSP • Cơ chế hoạt động của một servlet: • Web server nhận yêu cầu triệu gọi servlet từ client. • Nếu servlet chạy lần đầu, web server load file servlet tương ứng, khởi tạo các thông số bằng qua method init() • Nếu servlet đã được khởi tạo, tạo một thread để xử lý yêu cầu. • Gọi methods doXxx() để xử lý các request tương ứng theo giao thức HTTP. • doGet(..) cho HTTP GET, doPost cho HTTP POST
  • 7. Lập trình mạng – Chương 6 7 1.2 Lập trình web với Servlet • Lấy dữ liệu từ web client gởi đến bằng servlet: • Dùng đối tượng của class HttpServletRequest • Các methods để lấy thông số: • getParameter(“para-name”) • getParameterValues(“para-name”) String username= request.getParameter(“username”); String[] choice = request.getParameterValues(“comments”); • Dùng đối tượng của class HttpServletRequest để lấy các thông tin HTTP header
  • 8. Lập trình mạng – Chương 6 8 1.2 Lập trình web với Servlet • Ví dụ lấy tất cả các thông số từ client Enumeration parameter_names = request.getParameterNames(); while(parameter_names.hasMoreElements()){ String para = parameter_names.nextElement(); out.print(para + “ = ”); String[] paraValues = getParameterValues(para); if(paraValues.lenght()==1){ out.println(paraValues[0]); }else{ for(int i = 0, i< paraValues.lenght(),i++){ out.print(paraValues[i]+ “-”); } } }
  • 9. Lập trình mạng – Chương 6 9 1.2 Lập trình web với Servlet • Lấy các thông số HTTP request header: class HttpServletRequest cung cấp các method để lấy các thông số request header. • String getHeader(header-name): lấy nội dung của header-name • Enumeration getHeaderNames(): lấy tất cả các header-name. • Một số method điển hình: • Cookie[] getCookies(): dãy Cookie từ client • int getContentLength(): trả giá trị Content-Length • int getContentType(): trả giá trị Content-Type • int getRemoteUser(): giá trị username nếu có authenticate
  • 10. Lập trình mạng – Chương 6 10 1.2 Lập trình web với Servlet • Lấy các thông số HTTP request header: • Lấy các giá trị của biến môi trường CGI: • QUERY_STRING: getQueryString() • REMOTE_ADDR: getRemoteAddr() • REMOTE_HOST: getRemoteHost() • REQUEST_METHOD: getMethod() • PATH_INFO: getPathInfo() • SCRIPT_NAME: getServletPath() • SERVER_NAME: getServerName() • SERVER_PORT: getServerPort() • HTTP_XXX_YYY: getHeader(“Xxx-Yyy”) • …
  • 11. Lập trình mạng – Chương 6 11 1.2 Lập trình web với Servlet • Gởi dữ liệu cho web client: dùng đối tượng của class HttpServletResponse: • Tạo đối tượng PrintWriter để ghi dữ liệu gởi • PrintWriter out = response.getWriter(); • Xử lý các mã HTTP trả về với các method của class HttpServletResponse: • void setStatus(int statusCode): gởi các mã response • void sendError(int errorCode,String msg): gởi mã lỗi theo giao thức HTTP và message • void sendRedirect(String URL): chuyển đến một trang URL khác • Các mã có thể theo giao thức HTTP hoặc dùng các hằng số trong class HttpServletResponse.
  • 12. Lập trình mạng – Chương 6 12 1.2 Lập trình web với Servlet • Xử lý Cookie với web browser: • Chức năng Cookie • Kết hợp với web browser để lưu các thông số cần thiết. • Thông tin có thể dùng để thiết lập phiên làm việc(session) trong các ứng dụng thương mại điện tử(e-commerce). • Lưu trữ username, password • Thông tin để customize web site cho user hay dùng cho cơ chế personalization • …
  • 13. Lập trình mạng – Chương 6 13 1.2 Lập trình web với Servlet • Ghi thông tin Cookie lên máy client: • Thông tin được truyền đi trong field Set-Cookie HTTP header • Dùng method addCookie(Cookie cookie) của class HttpServletResponse. • Các thuộc tính quan trọng trong class Cookie: • Cookie name: setName(String name) – getName() • Cookie value: setValue(String value) – getValue() • Max Age: setMaxAge(int seconds) – getMaxAge()
  • 14. Lập trình mạng – Chương 6 14 1.2 Lập trình web với Servlet • Ví dụ: String user=“”,pass=“”; Cookie[] cookies = request.getCookies(); if(cookies.length==0){ user = request.getParameter(“username”); pass = request.getParameter(“password”); Cookie name_cookie = new Cookie(“username”,user); response.addCookie(name_cookie); Cookie pass_cookie = new Cookie(“password”,pass); response.addCookie(pass_cookie); }else{ for(int i=0;i<cookies.length;i++){ Cookie cookie = cookies[i]; if(cookie.getName().equals(“username”)) user=cookie.getValue(); if(cookie.getName().equals(“password”)) pass=cookie.getValue(); } }
  • 15. Lập trình mạng – Chương 6 15 1.2 Lập trình web với Servlet • Lưu thông tin về phiên làm việc của user: class HttpSession. • Có thể dùng để lưu bất kỳ đối tượng nào. • Đối tượng của class HttpSession được trả về từ method getSession() của class HttpServletRequest. • Các method thường sử dụng: • Object getValue(String name) [2.2: getAttribute] • void putValue(String name,Object object) [2.2: putAttribute] • void removeValue(String name) [2.2: removeAttribute] • String[] getValueNames() [Enumeration getAttributeNames()] • String getId() • void setMaxInactiveInterval(int seconds)
  • 16. Lập trình mạng – Chương 6 16 1.2 Lập trình web với Servlet • Ví dụ lưu ShoppingCart vào session HttpSession session = request.getSession(true); ShoppingCart cart = (ShoppingCart)session.getValue(“ShoppingCart”); if(cart==null){ cart = new ShoppingCart(); session.putValue(“ShoppingCart”,cart); } //process(cart)
  • 17. Lập trình mạng – Chương 6 17 1.2 Lập trình web với Servlet • Xử lý kết nối database • Dùng JDBC (Java DataBase Connectivity) để kết nối và thao tác với database. • Quy trình xử lý: • Tạo JDBC driver và URL database • Thiết lập connection đến URL database • Tạo đối tượng statement • Thực thi các câu lệnh SQL • Xử lý kết quả thực thi • Đóng kết nối đến database.
  • 18. Lập trình mạng – Chương 6 18 1.2 Lập trình web với Servlet • Kết nối đến database thông qua OBDC trên Windows: • Tạo DataSourceName trong ODBC Connection con = null; Statement stmt = null; ResultSet rs = null; String driver = “sun.jdbc.odbc.JdbcOdbcDriver”; String databaseURL = “jdbc:odbc:DataSourceName”; try{ Class.forName(driver); con = DriverManager.getConnection(databaseURL); stmt = con.createStatement() rs = stmt.executeQuery(“SELECT * FROM Products”); while(rs.next()){ out.println(rs.getString[1]+”-” getInt(“quantity”));//… } con.close(); }cacth(SQLException se){ con.close(); }
  • 19. Lập trình mạng – Chương 6 19 1.2 Lập trình web với Servlet • Có thể kết nối database server bất kỳ có driver hỗ trợ. • Kết nối đến Oracle Database Server: driver=“oracle.jdbc.driver.OracleDriver” databaseURL =“jdbc:oracle:thin@localhost:1521:”+dbName con = DriverManager.getConnection(databaseURL,user,password) • Kết nối đến Sysbase: driver=“com.sysbase.jdbc.SysDriver” databaseURL = “jdbc:sysbase:Tds:localhost:1521?SERVICENAME=“+dbName con = DriverManager.getConnection(databaseURL,user,password)
  • 20. Lập trình mạng – Chương 6 20 1.2 Lập trình web với Servlet • Dùng Prepared Statements trong các câu lệnh thay đổi dữ liệu: String preSQLString = “UPDATE students SET score = ? WHERE ID=?”; PreparedStatement pre_stmt= connection.prepareStatement(preSQLString); float[] scores = getScores(); String[] studentIDs = getStudentIDs(); for(int i=0;i< studentIDs.length;i++){ pre_stmt.setFloat(1,scores[i]); pre_stmt.setString(2, studentIDs[i]); pre_stmt.execute(); }
  • 21. Lập trình mạng – Chương 6 21 1.2 Lập trình web với Servlet • Dùng cơ chế Connection Pooling • Tạo một dãy các Connection sẵn sàng. • Dùng cơ chế thread và đồng bộ để chia xẻ các Connection. public synchronized Connection getConnection() throws SQLException{ if(!availableConnections.isEmpty()){ Connection con = availableConnections.lastElement(); availableConnections.removeElementAt( availableConnections.size()-1); busyConnections.addElement(con); return con; }else{ //… } }
  • 22. Lập trình mạng – Chương 6 22 1.3 Lập trình web với JSP • JSP (Java Server Pages) là một trang HTML xen các đoạn mã Java. • Trang JSP sẽ được web server biên dịch theo thành bytecode, cơ chế hoạt động tương tự như Servlet. • Được tạo sẵn các đối tượng của các class HttpServletRequest và HttpServletResponse để xử lý giao tiếp với web client.
  • 23. Lập trình mạng – Chương 6 23 1.3 Lập trình web với JSP • Các đoạn mã Java trong trang JSP được đặt trong tag: <% %> • Giá trị biểu thức: <%= biểu thức %> • Khai báo các biếm <%! [type variable;]+ %> • Java code <% Java code %> • Chú thích <%-- comments --%> • Các khai báo chỉ thị (derective): • <%@ page import=“[package][,package]*” %> • <%@ page isThreadSafe=“{true|false}” %> • <%@ page session=“{true|false}” %> • <%@ include file=“filename” %>
  • 24. Lập trình mạng – Chương 6 24 1.3 Lập trình web với JSP Ví dụ trang JSP <html> <body bgcolor="white"> <h1> Request Information </h1> <font size="4"> JSP Request Method: <jsp:expr> request.getMethod() </jsp:expr> <br> Request URI: <jsp:expr> request.getRequestURI() </jsp:expr> <br> Request Protocol: <jsp:expr> request.getProtocol() </jsp:expr> <br> Servlet path: <jsp:expr> request.getServletPath() </jsp:expr> <br> Path info: <jsp:expr> request.getPathInfo() </jsp:expr> <br> Path translated: <%= request.getPathTranslated() %> …
  • 25. Lập trình mạng – Chương 6 25 1.3 Lập trình web với JSP <%@ page import=“beans.*" session="true" autoFlush="true" buffer="none" %> <%! Const con = new Const();%> <jsp:useBean id="check" scope="page" class="beans.CheckAdmin" /> <html> <head> <SCRIPT language="JavaScript" src="Scripts/ImagesOver.js" type="text/javascript"></SCRIPT> <title>Check admin account</title> <META content="text/html; charset=x-user-defined" http-equiv=Content-Type> <LINK href=“Images/linkref.css" rel=stylesheet> </head> <body background="Images/StarStuds.gif"> <% out.println(con.getHeader()); check.processRequest(request); if(check.check()==true){ out.println("Hello administrator <b>"+check.getName()+"</b>"); } else{ %> <br>Invalid password.Please <a href="admin_logon.jsp">try</a> again <%} out.println(con.getFooter()); %>
  • 26. Lập trình mạng – Chương 6 26 1.3 Lập trình web với JSP • Các đối tượng được xây dựng sẵn trong một trang JSP: • request: đối tượng class HttpServletRequest • response: đối tượng class HttpServletResponse • out: đối tượng class PrintWriter • session: đối tượng class HttpSession tạo ra từ method getSession() của đối tượng request • application: đối tượng class ServletContext • config: đối tượng class ServletConfig
  • 27. Lập trình mạng – Chương 6 27 1.4 Giới thiệu ASP • ASP là một trang HTML có chứa các mã script (VBScript hay JavaScript). Các script này có thể: • Lấy thông tin từ user. • Sinh nội dung động. • Thao tác với database. • … • Trang ASP được chạy trên web-server hỗ trợ (server-side)
  • 28. Lập trình mạng – Chương 6 28 1.4 Giới thiệu ASP • Các công cụ: • Soạn thảo : • Có thể dùng trình soạn thảo văn bản text bất kỳ. • Các công cụ trực quan : Ms. Visual InterDev, Ms. FrontPage, Macromedia Dreamweaver… • Web server: • Win9x : Personal Web Server • Win NT/2000 : Internet Information Services. • Chili!Soft : http://www.ChiliSoft.com (UNIX support) • HalcyonSoft : http://www.halcyonsoft.com
  • 29. Lập trình mạng – Chương 6 29 1.4 Giới thiệu ASP • Thêm script xử lý vào trang ASP: • Đặt mã trong cặp dấu : <%...%> • Ví dụ : <HTML><BODY> <% REM Hello World ! ASP %> </BODY></HTML> • Dùng tag SCRIPT : • <SCRIPT RUNAT=“SERVER”>….</SCRIPT> • Ví dụ : <HTML><BODY> <SCRIPT RUNAT=“SERVER”> REM Hello World </SCRIPT> </BODY></HTML>
  • 30. Lập trình mạng – Chương 6 30 1.5 Lập trình web với ASP • Đối tượng xử lý request sẵn có của ASP: Request. • Lấy thông tin người dùng nhập từ Form: • Request.Form(“field_name”) • Request.Form(index) • Một số field đặc biệt : checkbox, ratio, các field cùng tên…
  • 31. Lập trình mạng – Chương 6 31 6.5 Lập trình web với ASP •Đối tượng xử lý response sẵn có của ASP: Response •Các phương thức chính: • Reponse.Write(“String”) • Reponse.Redirect(“URL”)
  • 32. Lập trình mạng – Chương 6 32 1.5 Lập trình web với ASP • Đối tượng Application: • Quản lý thông tin về ứng dụng. Có thể dùng để lưu trữ dữ liệu, đối tượng. • Đối tượng Session: • Quản lý thông tin về phiên làm việc(session), có thể lưu dữ liệu, đối tượng của một session • Đố tượng Server: • Đặt các thuộc tính, tạo đối tượng mới…
  • 33. Lập trình mạng – Chương 6 33 1.5 Lập trình web với ASP • Thao tác database: có thể dùng ADO để thao tác. • Ví dụ về đọc dữ liệu từ database Dim objRecordset Set objRecordset = Server.CreateObject(“ADODB.Recordset”) objRecordset.Open “table-name”, “DSN=dsn” Do While NOT objRecordset.EOF Response.Write objRecordset(“field-name”) objRecordset.MoveNext Loop
  • 34. Lập trình mạng – Chương 6 34 1.5 Lập trình web với ASP • Đọc dữ liệu bằng câu lệnh SQL: strSQL = “Select * FROM table WHERE ….” objRecordset.Open strSQL, “DSN=dsn” • Dùng in dữ liệu theo dạng bảng, danh sách, listbox… • Có thể dùng cách này để hiện thực việc tìm kiếm.
  • 35. Lập trình mạng – Chương 6 35 1.5 Lập trình web với ASP • Thêm mới record: Set obj-Recordset-name = Server.CreateObject(“ADODB.Recordset”) objRecordset-name.Open “table-name”, “DSN=dsn”, _ adOpenDynamic, adLockOptimistic obj-Recordset-name.AddNew obj-Recordset-name.Fields(“field-name”) = … obj-Recordset-name.Update ‘…. obj-Recordset-name.Close
  • 36. Lập trình mạng – Chương 6 36 1.5 Lập trình web với ASP • Cập nhật thông tin trong record: strSQLUpdate = “UPDATE table SET field1=…, field2=… WHERE …” objRecordset. Excute strSQLUpdate