- Servlet & JSP là công nghệ tạo ra cá trang web động được Sun phát triển, nó tương tự như ASP của Microsoft
- Servlet & JSP được phát triển dự trên kiến trúc MVC
o Các trang JSP đóng vai trò hiển thị các kết quả của người dùng (thành phần View)
o Servlet sẽ đóng vai trò là các Controller, điều khiển các yêu cầu được gửi lên từ các trang JSP
o Các class khác: bean, process thực hiện các chức năng nghiệp vụ: đọc, lưu dữ liệu sẽ thuộc vào thành phần Model
- Sơ lược về các xây dựng ứng dụng web với Servlet & JSP
o Ta xét một ví dụ đơn giản: xây dựng một trang login vào hệ thống. Người dùng nhập username và password, hệ thống kết nối cơ sở dữ liệu để xác nhận, nếu đăng nhập thành công thì hệ thống sẽ tạo một đối tượng thông tin người dùng và đối tượng này được hiển thị cho người dùng.
o Với ứng dụng này ta xây dựng với webserver [Chỉ có thành viên mới thấy links này. ]
o Ta xây dựng:
View: trang login.jsp và trang loginsuccess.jsp
Controller: servlet login.java
Model: lớp xử lý loginprocess.java, lớp bean thông tin user.java
Code:
package test;
public class User {
/**
* Ten dang nhap
*/
private String username;
/**
* Ten day du cua nguoi dung
*/
private String fullName;
/**
* Dia chi cua nguoi dung
*/
private String address;
public String getUsername() {
return username;
}
public String getFullName() {
return fullName;
}
public String getAddress() {
return address;
}
public void setUsername(String username) {
this.username = username;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public void setAddress(String address) {
this.address = address;
}
}
Lớp User là lớp lưu thông tin của một người dùng sau khi đăng nhập thành công
Code:
package test;
import java.sql.*;
public class LoginProcessor {
public User login(String username, String password){
try{
Connection con = … // connect database
CallableStatement cs = con.prepareCall("{call spLogin(?,?)}");
cs.setString(1, username);
cs.setString(2, password);
ResultSet rs = cs.executeQuery();
User user = null;
if (rs.next()){
//Lay cac thong tin sau khi thuc hien SP spLogin trong CSDL
String fullName = rs.getString("FullName");
String address = rs.getString("Address");
user = new User();
user.setUsername(username);
user.setFullName(fullName);
user.setAddress(address);
}
return user;
}catch(Exception e){
return null;
}
}
}
Lớp LoginProcessor có một phương thức login() phương thức này kết nối DB, gọi store procedure để login, nếu thành công thì sẽ trả về một đối tượng User, ngược lại thì trả về null
Tiếp theo ta sẽ xây dựng Controller login
Code:
package test;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class Login
extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=UTF-8";
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType(CONTENT_TYPE);
String username = request.getParameter("username");
String password = request.getParameter("password");
LoginProcessor process = new LoginProcessor();
User user = process.login(username, password);
if (user != null){
/**
* dang nhap thanh cong, chuyen sang trang loginsucccess.jsp
* ta thiet lap them doi tuong user vao request de send sang cho trang loginsucccess.jsp
*/
request.setAttribute("UserInfor", user);
getServletConfig().getServletContext().
getRequestDispatcher("loginsuccess.jsp").forward(request, response);
}else{
/**
* dang nhap khong thanh cong, chuyen lai trang login.jsp
*/
getServletConfig().getServletContext().
getRequestDispatcher("login.jsp").forward(request, response);
}
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
//Clean up resources
public void destroy() {
}
}
Lưu ý:
- Tên của 2 textbox: username và password phải trùng với chuỗi tham số trong các câu lệnh
String username = request.getParameter("username");
String password = request.getParameter("password");
- Action=’login’ của form sẽ điều khiển các yêu cầu của form đến đích ‘login’, ở đây login sẽ là servlet login ánh xạ đến lớp login.java. Ta sẽ gặp ở bước sau, khi cấu hình file web.xml
- Trang loginsuccess.jsp
Code:
<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
<%@ page import="test.User"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<%
User user = (User)request.getAttribute("UserInfor");
if (user == null)
user = new User();
%>
<body>
<table>
<tr>
<td>Username:</td>
<td><%= user.getUsername()%></td>
</tr>
<tr>
<td>FullName</td>
<td><%= user.getFullName()%></td>
</tr>
<tr>
<td>Address</td>
<td><%= user.getAddress()%></td>
</tr>
</table>
</body>
</html>
Lưu ý: ở trang loginsucess.jsp ta getAttribute(“UserInfor”) để nhận đối tượng User mà servlet đã thiết lập truyền sang khi đăng nhập thành công
Thiết lập file web.xml
Trong file web.xml ta sẽ cấu hình thông tin của servlet login như sau
Code:
Action form điều hướng đến servlet này thông qua url-pattern, đó là lý do tại sao ta thiết lập action form là login
Đến đây ta đã có thể chạy ứng dụng của mình
Bạn ơi ! Cách cấu hình file web.xml mình không hiểu lắm , bạn chĩ rõ được không ?
Thank nhiều nhé !
File web.xml thường được gọi là deployment descriptor
Dưới đây là 1 ví dụ để bạn tham khảo thêm nhé
Code:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>
The name of the application
</display-name>
<description>
C'mon, you know what goes into a description, don't you?
</description>
<context-param>
<param-name>name_of_context_initialization_parameter</param-name>
<param-value>value_of_context_initializtion_parameter</param-value>
<description> Again, some description </description>
</context-param>
<servlet>
<servlet-name>guess_what_name_of_servlet</servlet-name>
<description>Again, some description</description>
<servlet-class>com.foo-bar.somepackage.TheServlet</servlet-class>
<init-param>
<param-name>foo</param-name>
<param-value>bar</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>name_of_a_servlet</servlet-name>
<url-pattern>*.some_pattern</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>image</servlet-name>
<url-pattern>/image</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
Trong đó:
context-param
The values within the context-param element can be accessed like so:
Code:
String value = getServletContext().getInitParameter("name_of_context_initialization_parameter");
Servlet initialization parameters (that is: the values within the servlet element) can be retrieved in a servlet or JSP page by calling:
Code:
String value = getServletConfig().getInitParameter("foo");
session-timeout
<session-timeout>: The timeout for a session in minutes. servlet
For each servlet in the web application, there is a <servlet> element. The name identifies the servlet (<servlet-name>). servlet-mapping
Each servlet in the web application gets a servlet mapping. The url pattern is used to map URI to servlets.
Obviously, the order of the elements matters!