IT Research Department @BKAP 2015 Page 1 / 15 Lab 01 Introduction to Struts Framework Mục tiêu - Hiểu rõ kiến trúc mô hình MVC - Nắm vững luồng dữ liệu đi trong framework Struts 1 - Tạo
Trang 1IT Research Department @BKAP 2015 Page 1 / 15
Lab 01 Introduction to Struts Framework Mục tiêu
- Hiểu rõ kiến trúc mô hình MVC
- Nắm vững luồng dữ liệu đi trong framework Struts 1
- Tạo ứng dụng đơn giản với framework Struts 1
Phần I Bài tập step by step
Bài 1.1 Tạo Project với Struts 1
- Tạo Project Web Application trên Netbeans
- Sử dụng framwork Struts 1 tích hợp sẵn trên Java EE 7
Step 1: Tạo project mới trong Netbeans
File New Project Web Web Application
Trang 2 Name and Location:
Project: Đặt tên Project là Lab01
Project Location: Trỏ đến thư mục đặt thư mục của Project
Project Folder: Thư mục Project
Server and Settings: Chọn GlassFish server
Trang 3IT Research Department @BKAP 2015 Page 3 / 15
Frameworks: Chọn Struts 1.3.10 được tích hợp trong Netbeans
Kiến trúc project sau khi hoàn thành
Step 2: Cấu hình chạy Project
Lab01 RC Properties
Trang 4 Sources:
Source/Binary Format: Chọn JDK đã cài
Encoding: Chọn UTF8
Frameworks: Các framework dùng trong project
Libraries: Các thư viện dùng trong project
Run: Browser: IDE dùng để chạy Project
Step 3: Build and Run Ứng dụng
Bài 1.2 Xây dựng trang đăng nhập cho User
- Trang đăng nhập có 2 thông tin: User Name và Passwork
- Người dùng nhập thông tin và submit
- Nếu User Name có giá trị bằng Passwork: Hiển thị Login Success Wellcome UserName
- Nếu User Name có giá trị khác Passwork: Hiển thị Invalid
UserName
Step 1: Tạo các trang đăng nhập, hiển thị thông báo (VIEW)
Trang đang nhập login.jsp
Lab01 Web Pages RC New Other Web JSP
Trang 5IT Research Department @BKAP 2015 Page 5 / 15
Tạo form đăng nhập
Trang 6<%@ pagecontentType="text/html" pageEncoding="UTF-8"%>
<%@ tagliburi="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ tagliburi="http://struts.apache.org/tags-html" prefix="html" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<h1> STRUTS FRAMEWORK - LOGIN </h1>
< html:formaction="/login">
<table width="515" border="0" align="center">
<tr>
<td width="144"> </td>
<td width="313"> </td>
</tr>
<tr>
<td>UserName</td>
<td>< html:textproperty="userName"></ html:text ></td>
</tr>
<tr>
<td>Passwork</td>
<td>< html:textproperty="password"></ html:text ></td>
</tr>
<tr>
<td> </td>
<td>< html:submitvalue="Login"></ html:submit ></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</ html:form >
</body>
</html>
Tạo trang hiển thị thông báo thành công success.jsp
<%@ pagecontentType="text/html" pageEncoding="UTF-8"%>
<%@ tagliburi="http://struts.apache.org/tags-bean" prefix="bean" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
Trang 7IT Research Department @BKAP 2015 Page 7 / 15
</head>
<body>
<div style="color: black" align="center">
<h1>Login Success Welcome <bean:writename="LoginForm"
property="userName"></ bean:write ></h1>
</div>
</body>
</html>
Tạo trang hiển thị thông báo thất bại failure.jsp
<%@ pagecontentType="text/html" pageEncoding="UTF-8"%>
<%@ tagliburi="http://struts.apache.org/tags-bean" prefix="bean" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div style="color: black" align="center">
<h1>Invalid User Name <bean:writename="LoginForm"
property="userName"></ bean:write ></h1>
</div>
</body>
</html>
Step 2: Tạo ActionForm Bean để chứa thông tin UserName và Password nhập từ form đăng nhập
Lab01 Source Packages New Other Struts Struts ActionForm Bean
Trang 8 1: Tên ActionForm Bean LoginForm
2: Package actionForm
3: Kế thừa lớp org.apache.struts.action.ActionForm
4: Khi tạo cấu hình trong struts-config.xml
5: Finish Kết thúc tạo ActionForm Bean
Sau khi thành công, ActionForm Bean sẽ được tự động khai báo trong
struts-config.xml (Web Pages WEB-INF struts-struts-config.xml)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="LoginForm" type="actionForm.LoginForm"/>
Trang 9IT Research Department @BKAP 2015 Page 9 / 15
</form-beans>
<global-exceptions>
</global-exceptions>
<global-forwards>
<forward name="welcome" path="/Welcome.do"/>
</global-forwards>
<action-mappings>
<action path="/Welcome" forward="/welcomeStruts.jsp"/>
</action-mappings>
<controller processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>
<message-resources parameter="com/myapp/struts/ApplicationResource"/>
<! ========================= Tiles plugin =============================== > <!
This plugin initialize Tiles definition factory This later can takes some
parameters explained here after The plugin first read parameters from
web.xml, thenoverload them with parameters defined here All parameters
are optional
The plugin should be declared in each struts-config file
- definitions-config: (optional)
Specify configuration file names There can be several comma
separated file names (default: ?? )
- moduleAware: (optional - struts1.1)
Specify if the Tiles definition factory is module aware If true
(default), there will be one factory for each Struts module
If false, there will be one common factory for all module In this
later case, it is still needed to declare one plugin per module
The factory will be initialized with parameters found in the first
initialized plugin (generally the one associated with the default
module)
true : One factory per module (default)
false : one single shared factory for all modules
- definitions-parser-validate: (optional)
Specify if xml parser should validate the Tiles configuration file
true : validate DTD should be specified in file header (default)
false : no validation
Trang 10Paths found in Tiles definitions are relative to the main context
>
<plug-in className="org.apache.struts.tiles.TilesPlugin" >
<set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" /> <set-property property="moduleAware" value="true" />
</plug-in>
<! ========================= Validator plugin
================================= >
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property
property="pathnames"
value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>
Code LoginForm.java
Khai báo và tạo các phương thức get/set cho 3 thuộc tính userName, password và error
Tạo phương thức validate bắt buộc nhập UserName và Password
package actionForm;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
/**
*
* @author Quang
*/
public class LoginForm extends org.apache.struts.action.ActionForm {
private String userName;
private String password;
private String error;
/**
*
*/
Trang 11IT Research Department @BKAP 2015 Page 11 / 15
public LoginForm() {
super();
// TODO Auto-generated constructor stub
}
/**
* This is the action called from the Struts framework
*
* @param mapping The ActionMapping used to select this instance
* @param request The HTTP Request we are processing
* @return
*/
@Override
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors();
if (getUserName() == null || getUserName().length() < 1) {
errors.add("userName", new ActionMessage("error.userName.required"));
// TODO: add 'error.name.required' key to your resources
}
if (getPassword() == null || getPassword().length() < 1) {
errors.add("password", new ActionMessage("error.password.required"));
// TODO: add 'error.name.required' key to your resources
}
return errors;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getError() {
Trang 12return error;
}
public void setError(String error) {
this.error = error;
}
}
Step 3: Tạo lớp action
Chứa business login (Model) của ứng dụng nhận dữ liệu từ ActionForm Bean
Thực thi hàm Excecute(): Kiểm tra tính hợp lệ của UserName và Password nhập vào
Dựa vào kết quả nhận được xác định trang jsp (View) nào sẽ được thực hiện
Tạo Struts Action
Lab01 Source Packages New Other Struts Struts Action
1: Tên Action LoginAction
2: Package action
Trang 13IT Research Department @BKAP 2015 Page 13 / 15
3: Configuration File /WEB-INF/struts-config.xml: Tự động khai báo action trong file struts-config.xml
4: Action Path: Khai báo đúng tên action ở Form login đã gọi /login
5: Next
Sau khi hoàn thành, action sẽ được khai báo tự động struts-config.xml
<action-mappings>
<action input="/" name="LoginForm" path="/login" scope="request"
type="action.LoginAction"/>
<action path="/Welcome" forward="/welcomeStruts.jsp"/></action-mappings>
Code LoginAction.java
package action;
import actionForm.LoginForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
Trang 14import org.apache.struts.action.ActionMapping;
/**
*
* @author Quang
*/
public class LoginAction extends org.apache.struts.action.Action {
/* forward name="success" path="" */
private static final String SUCCESS = "success";
private static final String FAILURE = "failure";
/**
* This is the action called from the Struts framework
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request
* @param request The HTTP Request we are processing
* @param response The HTTP Response we are processing
* @throws java.lang.Exception
* @return
*/
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginForm loginForm = (LoginForm) form;
String a1 = loginForm.getUserName();
String a2 = loginForm.getPassword();
if (loginForm.getUserName().equals(loginForm.getPassword())) {
return mapping.findForward(SUCCESS);
} else {
return mapping.findForward(FAILURE);
}
}
}
Step 4: Điều chuyển hướng trong thẻ global-forwards của struts-config.xml
<action-mappings>
<action input="/login.jsp" name="LoginForm" path="/login" scope="request"
type="action.LoginAction">
<forward name="failure" path="/failure.jsp"/>
Trang 15IT Research Department @BKAP 2015 Page 15 / 15
<forward name="success" path="/success.jsp"/>
</action>
</action-mappings>
Step 5: Cấu hình web.xml
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
Step 6: Build and Run Ứng dụng
Đăng nhập thành công
Đăng nhập thất bại