Võ Văn Hải's blog

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

Struts 1.x với Eclipse

Trong bài này tôi sẽ hướng dẫn cách chúng ta làm việc với strut 1.x trên môi trường Eclipse. Chắc bạn sẽ thắc mắc tại sao không dùng struts 2.x mà lại dùng “đồ cỗ”? tôi cũng xin nói rằng, trong 1 vài trường hợp như chương trình giảng dạy chưa cập nhật kịp hoặc 1 vài công ty chưa sẵn sàng dùng strut 2 và cũng còn khá nhiều lý do khác để dùng struts1. Toi sẽ đề cập đến struts2 trong 1 bài khác.

Trên eclipse, bạn hoàn toàn có thể download các plug-in cho struts để plug vào. Tuy nhiên ở đây tôi không dùng plug-in nào cả nên bạn phải chú ý kỹ vần đề cấu hình.

1.  Đầu tiên, bạn download struts1 library về máy(nhớ là struts 1.x nhé). Bạn download tại url sau: http://struts.apache.org/downloads.html.

Giải nén thư mục bạn mong muốn. Chú ý đến thư mục lib nhé!

Bây giờ bạn có thể làm việc với eclipse được rồi.

2. Khởi động eclipse, tạo 1 project dạng “Dynamic Web Project“, đặt tên là HelloStruts1x, chọn Target runtime là Tomcat, .. như hình sau

strut1hello_01

Nhấn Finish để hoàn tất.

3. Tiếp theo, bạn copy tất cả các file jar trong thư mực lib của thư mục struts mà bạn giải nén ở bước đầu. Sau đó trên Eclipse trong cửa sổ Project Explorer, bạn chọn đến thư mục Web-Content/WEB-INF/lib, bạn paste vào đấy. bây giờ project explorer trông như  sau:

strut1hello_02

4. Copy các file có phần mở rộng tld (tag-lib definition)vào thư  mục WEB-INF. Bạn có thể chỉ chép file tld ứng với tag bạn muốn xài là được. Ở đây nếu bạn muốn dùng hết thì chép tất cả cho chắc ăn! :).

5. Tạo file struts-config.xml trong thư mục WEB-INF, nội dung chúng ta sẽ nói sau.

6. Cấu hình web.xml để có thể làm việc được với struts. Lưu ý đây là bước quan trọng, bạn phải cẩn thận. Nội dung của file web.xml như  sau:

<?xml version=”1.0″ encoding=”UTF-8″?><web-app version=”2.5″ xmlns=”http://java.sun.com/xml/ns/javaee&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”><display-name>Strut1_Demo</display-name><welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file&gt;

<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>

<servlet>

<servlet-name>action</servlet-name>

<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

<init-param>

<param-name>config</param-name>

<param-value>/WEB-INF/struts-config.xml</param-value>

</init-param>

<init-param>

<param-name>debug</param-name>

<param-value>2</param-value>

</init-param>

<init-param>

<param-name>detail</param-name>

<param-value>2</param-value>

</init-param>

<load-on-startup>2</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>action</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

<session-config>

<session-timeout>

30

</session-timeout>

</session-config>

</web-app>

Đây là yêu cầu khai báo để có thể làm việc với struts. Từ nay các file web config khi làm việc với struts1 đều có dạng như thế này.

6. Tạo trang jsp

Ở đây đơn giản chúng ta tạo 1 trang cho người dùng nhập vào tên, tuổi sau đó hiển thị thông tin đã nhập lên 1 trang khác, trong trường hợp dữ liệu nhập thiếu hoặc không đúng sẽ hiển thị trang thông báo.

Tạo trang index.jsp bằng cách nhấn chuột phải lên thư mục Web Content, chọn New->JSP, gõ tên vào rồi nhấn Finish.

Nội dung của trang index.jsp như  sau:

<%@ taglib uri=”http://jakarta.apache.org/struts/tags-html&#8221; prefix=”html”%>

<html>

<body>

<html:form action=”book.do”>

Name:<html:text property=”name”/><br/>

Age:<html:text property=”age”/>

<html:submit/>

</html:form>

</body>

</html>

như vậy chúng ta có 1form với action của form là “book.do” với 2 text có thuộc tính được gắn tương ứng với anme và age.

Chúng ta tiếp tục tạo trang result.jsp để hiển thị kết quả khi người dùng nhập vào tên và tuổi, nội dung trang này như sau:

<%@ taglib uri=”http://jakarta.apache.org/struts/tags-html&#8221; prefix=”html”%>

<%@page contentType=”text/html” pageEncoding=”UTF-8″%>

<html>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>

<title>JSP Page</title>

</head>

<body>

<h2>Hello World!</h2>

<h2>Bạn đã chuyển sang trang result.jsp</h2>

<html:form action=”book”>

Name:<html:text property=”name”/><br/>

Age:<html:text property=”age”/>

</html:form>

</body>

</html>

Trong trường hợp người dùng nhập dữ liệu không hợp lệ sẽ được chuyển sang trang Failed.jsp, nội dung trang này như 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>Failed</title>

</head>

<body>

<h3> xin vui lòng nhập tên và tuổi hợp lệ</h3>

</body>

</html>

7. Các qui tắc chuyển trang

Như vậy, để có thể chuyển từ trang index.jsp sang trang result.jsp chúng ta phải định nghĩa qui tắc chuyển trang. Dữ liệu được chuyển tải giữa các trang thông qua các đối tượng là các bean. Chúng ta sẽ định nghĩa bean cho đối tượng và lớp cho qui luật chuyển trang.

Trong cửa sổ Project Explorer, nhấn phải chuột lên thư mục “Java Resources:src” chọn New->Class. Trong ô package gõ vào vovanhai.wordpress.com, class name gõ vào BookActionForm. Nội dung file này như sau:

package vovanhai.wordpress.com;public class BookActionForm extends org.apache.struts.action.ActionForm {

private static final long serialVersionUID = –6210614082380637094L;

private String name;

private int age;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public BookActionForm(String name, int age) {

this.name = name;

this.age = age;

}

public BookActionForm() {

this(“”,1);

}

}

Lớp này là java bean dùng để lưu trữ thông tin của đối tượng.

Tiếp theo, tạo 1 lớp dùng để chuyển trang theo 1 nguyên tắc do bạn bạn quyết định. Nội dung như sau:

package vovanhai.wordpress.com;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;

import org.apache.struts.action.ActionMapping;

public class BookAction extends org.apache.struts.action.Action {

/* forward name=”success” path=”” */

private final static String SUCCESS = “success”;

private final static String FAILED = “failed”;

/**

* 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 {

BookActionForm frm=(BookActionForm)form;

if(frm.getName().trim().equals(“”)||frm.getAge()<1)

return mapping.findForward(FAILED);

return mapping.findForward(SUCCESS);

}

}

Ở đây, điều kiện chuyển trang của chúng ta phụ thuộc vào gõ tên và tuổi. Trường hợp dữ liệu hợp lệ sẽ được chỉ thị “success”, nếu không sẽ được chỉ thị “failed”.

Để xử lý các chỉ thị chuyển trang này ta cần đến file struts-config.xml. nội dung như  sau:

<?xml version=”1.0″ encoding=”UTF-8″ ?>

<!DOCTYPE struts-config PUBLIC

“-//Apache Software Foundation//DTD Struts Configuration 1.2//EN”

http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd”&gt;

<struts-config>

<form-beans>

<form-bean name=”bookActionForm” type=”vovanhai.wordpress.com.BookActionForm” />

</form-beans>

<global-exceptions>

</global-exceptions>

<global-forwards>

</global-forwards>

<action-mappings>

<action path=”/book” name=”bookActionForm” scope=”session”

type=”vovanhai.wordpress.com.BookAction”>

<forward name=”success” path=”/result.jsp” />

<forward name=”failed” path=”/Failed.jsp” />

</action>

</action-mappings>

</struts-config>

Ở đây, qui tắc chuyển trang  sẽ là: nếu chỉ thị nhận được là “success”->chuyển sang trang result.jsp. nếu chỉ thị là “failed” thì chuyển sang trang Failed.jsp.

Nhìn lại cấu trúc cửa ứng dụng chúng ta như hình sau:
strut1hello_03

8. Thực thi

Nhấn phải chuột lên tập tin index.jsp, chọn “Run As -> Run on Server”. Kết quả trang như sau
strut1hello_04
Nhập dữ liệu đúng, kết quả như sau:
strut1hello_05
Nhập dữ liệu sai kết quả như sau:
strut1hello_06
Chúc thành công!

17 Responses to “Struts 1.x với Eclipse”

  1. tld said

    thua thay sao phan duoi mo rong .tld em down ve la ko co nhi? biet lay o dau day ah?

  2. vovanhai said

    Bạn không cần phải có file tld đâu, bạn có thể không cần dùng nó.
    Nếu bạn vẫn muốn có nó, dùng winrar mở file standard-x.x.x.jar trong thư mục lib của struts. Nó nằm trong thư mục META-INF.

  3. Đức Thủy said

    Em mới tìm hiểu cái này mà em ko biết lỗi này là lỗi gì vậy?

    HTTP Status 500 –
    ——————————————————————————–

    type Exception report

    message

    description The server encountered an internal error () that prevented it from fulfilling this request.

    exception

    org.apache.jasper.JasperException: Exception in JSP: /index.jsp:8

    5: Insert title here
    6:
    7:
    8:
    9:
    10: Name:
    11:

    Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:451)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:373)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)

    root cause

    java.lang.NullPointerException: Module ‘null’ not found.
    org.apache.struts.taglib.TagUtils.getModuleConfig(TagUtils.java:755)
    org.apache.struts.taglib.TagUtils.getModuleConfig(TagUtils.java:735)
    org.apache.struts.taglib.html.FormTag.lookup(FormTag.java:818)
    org.apache.struts.taglib.html.FormTag.doStartTag(FormTag.java:488)
    org.apache.jsp.index_jsp._jspx_meth_html_005fform_005f0(index_jsp.java:91)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:65)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:331)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)

  4. Đức Thủy said

    5: Insert title here
    6:
    7:
    8:
    9:
    10:” Name:”
    11:

  5. takeshi said

    Thanks!

  6. thầy giúp em với said

    em đang làm một module nhỏ.phần edit thông tin em muốn khi mình click vào button edit thì sẽ sang một trang jsp với form hiển thị thông tin của sản phẩm cần edit đó.em làm bằng struts và hibernate.em làm được với Object của table trong hibernate.nhưng em muốn là khi mình xác định được sản phẩm cần edit thông tin,thông tin từ Object table sẽ đổ vào form vào show lên jsp mà ko cần phải request Object table sang trang jsp để show nữa.

  7. Hoàng said

    em chào Thầy, dạo này Thầy vẫn khỏe chứ !. Thầy cho em hỏi có cách nào khi lam với struts trong eclipse em chỉ cần config build path đến thư viện struts mà không cần copy vào thư mục lib không vậy Thầy ? Em cảm ơn thầy

  8. Quân said

    Anh ơi… Cho em hỏi… Em dùng Struts có sẵn trong netbean bản 1.3.8
    Ở phần cấu hình struts-config Nếu em làm chẳng hạn thì nó sẽ đưa ra trang Insdex ở web Pages!
    Nhưng giờ em có một trang Index.jsp ở trong Foder ADMIN thì không biết cách Forward đến… Nếu dùng
    thì nó sẽ lỗi CSS hoặc Khi bấm vào link nó chỉ link dc các trang ngoài thư mục… Anh giúp em với!!

  9. Hoài Giang said

    E chào Thầy. E mới dùng eclipse nên hơi ngố:D Thầy cho e hỏi phần cấu hình web.xml mình phải tự code = tay ạ?

  10. Hoài Giang said

    Ở netbean là tự sinh thứ trong web.xml. Ở eclipse ơhari tự gõ hả Thầy?

  11. Giangvt said

    Em gặp phải lỗi này thì sửa sao thầy ơi !!!
    —————————————————–

    HTTP Status 500 –

    type Exception report

    message

    description The server encountered an internal error () that prevented it from fulfilling this request.

    exception

    org.apache.jasper.JasperException: javax.servlet.ServletException: javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:548)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:456)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:389)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

    root cause

    javax.servlet.ServletException: javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection
    org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:911)
    org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:840)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:90)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:433)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:389)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

    root cause

    javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection
    org.apache.struts.taglib.html.FormTag.lookup(FormTag.java:798)
    org.apache.struts.taglib.html.FormTag.doStartTag(FormTag.java:506)
    org.apache.jsp.index_jsp._jspx_meth_html_005fform_005f0(index_jsp.java:107)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:78)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:433)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:389)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

  12. Võ Văn Hải said

    Lỗi nè: “Cannot find ActionMappings or ActionFormBeans collection”.
    Bạn xem trong file config đã cấu hình ActionMappings chưa?

  13. phương said

    thưa thầy tại sao mình cần phải có file web.xml: Strut.xml
    cảm ơn thày nhiều!

  14. Tinh Nguyen said

    Missing message for key “label.userName” in bundle “(default bundle)” for locale vi_VN

    Em config tất cả bằng tay, tới phần config file .properties để :write ra mesage bị lỗi này mà chưa biết sửa chỗ nào

    .
    .

  15. Ngọc Anh said

    em đã add các thư viện và các tld. nhưng vẫn bị lỗi này cannot find the tag library descriptor for http //struts.apache.org/tags-html.
    Thầy chỉ giúp em đc ko ak?

  16. Ngọc Anh said

    sau 1 thời gian hý hoáy e đã làm xong.

  17. nam said

    thay` co tai lieu trut 1 va 2 gui e voi.

Leave a comment

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