Võ Văn Hải's blog

Chỉ có một điều tuyệt đối đó là mọi thứ đều tương đối…

Ví dụ Logon với Struts 2 trên Eclipse Ganymede

Trong ví dụ này chúng ta sẽ thực hiện cấu hình để có thể làm việc vói struts 2 trên Eclipse và thêm vào đó là trang đăng nhập như là 1 ví dụ đầu tiên với struts2.

A. Yêu cầu phần mềm:

  1. Struts 2 Framework: download tại http://struts.apache.org/2.0.14/index.html
  2. Eclipse Ganymede J2EE: download tại http://www.eclipse.org/downloads/

Sau khi download struts2, giải nén ra 1 thưc mục nào đó, ví dụ C:\javasoft\struts2x.x.x.

Download Eclipse, giải nén ra và thực thi nó(dĩ nhiên là bạn đã cài JDK rồi).

B. Làm việc với struts2 trên eclipse

Ví dụ của chúng ta bao gồm 2 trang jsp. Trang thứ nhất có tên là login.jsp hiển thị trang cho chúng ta gõ vào username và password, nếu đăng nhập thành công (username=admin, password=admin) thì sẽ chuyển đến trang thứ 2 có tên là index.jsp hiển thị 1 thông điệp chào mừng. Dĩ nhiên, ở trang index bạn có thể thiết kế tùy thích, hay việc đăng nhập phải khớp với thông tin trong database nào đó thì bạn phải customize lại ty chút là OK.

1. Tạo Dynamic Web project trong Eclipse

Khởi động eclipse, trong cửa sổ chính, vào menu File->New->Dynamic Web Project

(Nếu không thấy thì vào Menu File->New->Project, chọn đến mục Web->Dynamic Web Project).

Đặt tên cho project là Struts2_Login như hình

struts2_login_01

Nhấn Finish để kế thúc bước tạo Project.

2. Thêm các thư viện của Struts2 vào Web project.

Các thư viện cần được yêu cầu để Struts 2 có thể làm việc cơ bản đó là các file jar sau (tìm nó trong thư mục lib của thư mục  strust2 mà bạn giải nén sau khi download ở phần trên đã nói):

  • commons-beanutils-1.6.jar
  • commons-logging-1.0.4.jar
  • freemarker-2.3.8.jar,
  • ognl-2.6.11.jar,
  • oro-2.0.8.jar
  • struts2-core-2.0.11.jar
  • xwork-2.0.4.jar.

Phiên bản của các gói trên có thể khác tùy vào version của gói struts mà bạn download.

Bạn cần phải copy các file trên vào thư mục WebContent\WEB-INF\lib của ứng dụng struts2_login.

(Copy các gói trên windows explorer và paste nó vào trực tiếp trên môi trường eclipse).

3. Viết các trang và code cho ứng dụng:

a. Tạo Struts configuration file trong thư mục src  –  struts.xml

<?xml version=”1.0″ encoding=”UTF-8″ ?>
<!DOCTYPE struts PUBLIC
“-//Apache Software Foundation//DTD Struts Configuration 2.0//EN”
http://struts.apache.org/dtds/struts-2.0.dtd”&gt;
<struts>
<package name=”loginDemo” extends=”struts-default”>
<action name=”Login” class=”struts2demo.login.action.Login”>
<result>/home.jsp</result>
<result name=”error”>/login.jsp</result>
</action>
</package>
</struts>

b. Cấu hình ứng dụng web trong thư mục WEB-INF, tập tin web.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xmlns=”http://java.sun.com/xml/ns/javaee&#8221; xmlns:web=”http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221;
xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221;
id=”WebApp_ID” version=”2.5″>
<display-name>Struts2_login</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<display-name>struts2demo</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>

c. Tạo trang login.jsp với nội dung sau:

<%@ taglib prefix=”s” uri=”/struts-tags”%>
<html>
<head>
<title>Welcome to Struts2 with Eclipse Ganymede</title>
</head>
<body>
<s:form action=”Login”>
<s:textfield label=”User Id” name=”userid“></s:textfield>
<s:password label=”Password” name=”password“></s:password>
<s:submit label=”Login” name=”Login”></s:submit>
</s:form>
</body>
</html>

Ở đây yêu cầu của chương trình là hiển thị 2 textfield để nhập username và passporw cùng 1 nút login.

d. Tạo trang home.jsp với nội dung sau

<%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”&gt;
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>Insert title here</title>
</head>
<body>
<h1>Welcome to Home Page</h1>
</body>
</html>

Sau khi tạo các trang, chúng ta tiến hành viết code

e. Controller class

Lớp dùng để thao tác với việc submit thông tin logon. Trong Struts 2 nó thường được gọi là Action. Ở đây chúng ta lưu ý là nó extends từ  com.opensymphony.xwork2.ActionSupport. Lớp này tương ứng với 2 class trong struts 1 là ActionForm và Action.

Ta tạo lớp Login.java trong package có tên struts2demo.login.action. Code như sau

package struts2demo.login.action;
import com.opensymphony.xwork2.ActionSupport;

public class Login extends ActionSupport
{
private static final long serialVersionUID = -8936128602835626717L;
private String userid;
private String password;

public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String execute() {
if(userid.equals(“admin”) && password.equals(“admin”))
return SUCCESS;
else
return ERROR;
}
}

f. Cấu trúc project sau khi viết xong như hình sau:
https://vovanhai.files.wordpress.com/2008/12/struts2_login_02.png

Bây giờ chúng ta có thể thực thi trang để xem kết quả được rồi.

4. Thực thi ứng dụng

Nhấn phải chuột lên trang login.jsp, chọn Run As-> Run on Server, chọn server thực thi (Tomcat). Kết quả như hình sau:
https://vovanhai.files.wordpress.com/2008/12/struts2_login_03.png
Nếu nhập vào user name và password đều là “admin” thì trang sẽ được chuyển sang home.jsp còn bằng không thì trang login sẽ load lại.
https://vovanhai.files.wordpress.com/2008/12/struts2_login_04.png

Chúc các bạn thành công!

11 Responses to “Ví dụ Logon với Struts 2 trên Eclipse Ganymede”

  1. hi said

    Thanks bạn nhiều.

  2. Thầy ơi!
    em lam thu voi Struts 2 phiên bản 2.1.6 thấy có mộ số điểm khác biệt với phiên bản của thầy.e post lên không biết có đúng không.có gì thầy cho e ý kiến nhé:

    thứ nhất là với phiên bản 2.1.6 cũng như các phiên bản của struts 2 không thể add toàn bộ lib của struts2 vào lib của web được (theo em nghĩ chắc là có sự đụng độ giữa lib của struts2 nếu add chung).nếu add toàn bộ lib của struts 2 vào sẽ có thông báo lỗi đầu tiên là:

    “Unable to load configuration. – bean – jar:file:/E:/JavaSoft/eclipse-Project/Project/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/struts2-blank-2.1.6/WEB-INF/lib/struts2-convention-plugin-2.1.6.jar!/struts-plugin.xml:30:119”

    điểm thứ 2 là với phiên bản 2.1.6 các lib add vào sẽ khác lib của thầy.có sự thay đổi trong phiên bản struts 2.1.6 nên các lib add sẽ là:

    commons-fileupload-1.2.1.jar
    commons-io-1.3.2.jar
    commons-logging-1.1.jar
    freemarker-2.3.13.jar
    junit-3.8.1.jar
    ognl-2.6.11.jar
    spring-test-2.5.6.jar
    struts2-core-2.1.6.jar
    xwork-2.1.2.jar

    nếu add theo lib cũ của thầy sẽ báo lỗi

    “Unable to load configuration. – bean – jar:file:/E:/JavaSoft/eclipse-Project/Project/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/struts2-blank-2.1.6/WEB-INF/lib/struts2-core-2.1.6.jar!/struts-default.xml:46:178”

    em thử với “struts2-blank-2.1.6” (lấy từ trang chủ của Struts)

  3. vovanhai said

    mình cũng chưa thử với bản 2.1.6. bản 2.1.4 thì OK rồi. Để mình thử lại xem.

  4. Ngoc said

    sao minh cau hinh file struts.xml bi loi ko nhan dc thu vien ,ban chi ro cach tao file xml dc ko,
    Thank!!!

  5. mrquangbk307 said

    Cảm ơn bạn rất nhiều.^^.

  6. Em chào thầy ạ,
    Rất ít web có Cách chỉ dẫn của thầy rất tường tận như thầy, e mới đang tìm hiểu về liferay portal và đang mày mò viết portal, struts ạ. Em làm theo hướng dẫn của thầy, cấu trúc project đúng như thế, e viết trên eclipse helios. Nhưng các file đều bị báo lỗi, chắc lỗi nhỏ nhặt thôi nhưng e còn bỡ ngỡ quá k biết sửa, mong thầy giúp và sớm hồi âm ạ.
    file web.xml dòng đầu tiên báo lỗi: The value following “version” in the XML declaration must be a quoted string.
    file struts.xml cũng thế ạ.
    file login.java lỗi ở dòng if(userid.equals(“admin”) && password.equals(“admin”))

    error: The method equals(Object) in the type String is not applicable for the arguments ()
    và error: Syntax error on tokens, delete these tokens

  7. file web.xml e đã sửa dc nhưng file struts và login e vẫn k sửa dc..

  8. vovanhai said

    Khi bạn copy từ web xuống, các dấu ” đều bị sai. bạn replace hết là OK.

  9. Guest said

    chào thầy
    e thao tác giống như bạn nhưng mà nó báo The requested resource () is not available.
    ở trình duyệt
    thanks thầy

  10. minh said

    Help me fix this bug:
    java.lang.ClassNotFoundException: org.apache.struts2.dispatcher.FilterDispatcher
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1713)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1558)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:527)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:509)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:137)
    at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:260)
    at org.apache.catalina.core.ApplicationFilterConfig.(ApplicationFilterConfig.java:107)
    at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4746)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5399)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

  11. Võ Văn Hải said

    Thư viện strut bị thiếu.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.