Ví dụ Hello World trong Struts 2 sử dụng Annotation, không cần file struts.xml
5 phút đọc11/08/2025
Chris Pham
Technical Writer
0 lượt xem
0 lượt xem
Reading Time: 5minutes
Đây là bài viết thứ hai trong loạt hướng dẫn về. Ở bài trước, chúng ta đã tìm hiểu về kiến trúc Struts 2, các thành phần chính của nó và đã xây dựng một ứng dụng web đơn giản sử dụng Struts 2 với cấu hình dựa trên XML (struts.xml).
Trong bài viết này, chúng ta sẽ tìm hiểu cách loại bỏ hoàn toàn file cấu hình Struts bằng cách sử dụng annotations hoặc quy ước đặt tên.
Khái niệm Convention trong Struts 2
Struts 2 sử dụng hai phương pháp để xác định các lớp action và result. Để sử dụng bất kỳ phương pháp nào trong số này, chúng ta cần sử dụng thư viện struts2-convention-plugin.
Nếu bạn đang xây dựng một ứng dụng web thông thường, bạn có thể tải file jar của plugin này và đặt vào thư mục lib của ứng dụng. Còn với các dự án maven, bạn chỉ cần thêm phần dependency như sau:
Với phương pháp này, chúng ta chỉ định package cần được quét để tìm các lớp action. Việc cấu hình cần được thực hiện trong file web.xml cho Struts 2 filter, như ví dụ dưới đây:
Bất kỳ lớp nào được chú thích bằng @Action hoặc @Action .
Bất kỳ lớp nào cài đặt interface Action hoặc kế thừa lớp ActionSupport.
Bất kỳ lớp nào có tên kết thúc bằng “Action” và có chứa phương thức execute(). Với các lớp này naming convention sẽ được sử dụng để xác định action và result.
2. Quy ước đặt tên:
Struts 2 sẽ tự động tạo action cho những lớp có tên kết thúc bằng “Action”. Tên action được xác định bằng cách bỏ hậu tố “Action” và viết thường chữ cái đầu tiên.
Ví dụ: nếu tên lớp là HomeAction, thì tên action tương ứng sẽ là “home”.
Nếu các lớp này không được chú thích bằng @Result để chỉ định trang kết quả, thì Struts 2 sẽ tìm các trang kết quả trong thư mục WEB-INF/content, và tên file JSP phải có dạng: {action}-{return_string}.jsp.
Ví dụ: nếu lớp HomeAction trả về chuỗi “success” thì request sẽ được chuyển hướng đến trang: WEB-INF/content/home-success.jsp
Tuy nhiên, việc chỉ sử dụng quy ước đặt tên có thể gây nhầm lẫn, và không thể dùng chung một trang JSP cho nhiều action khác nhau. Do đó, bạn nên tránh phụ thuộc vào cách này và nên sử dụng cấu hình dựa trên annotation để rõ ràng và dễ quản lý hơn.
Giờ đây, chúng ta đã sẵn sàng để tạo ứng dụng Hello World với Struts 2 sử dụng annotation và sẽ không cần dùng file cấu hình Struts 2.
Hãy tạo một Dynamic Web Project trong Eclipse với tên Struts2AnnotationHelloWorld, sau đó chuyển thành Maven project.
Dự án sau khi hoàn tất sẽ có cấu trúc như hình dưới đây.
Cấu hình Maven
Chúng ta đã thêm các dependency struts2-core và struts2-convention-plugin vào file pom.xml. Dưới đây là nội dung hoàn chỉnh của file pom.xml:
Bây giờ, hãy tạo các lớp Action và sử dụng annotation để cấu hình action cùng với các trang kết quả.
Các lớp Action sử dụng Annotation
package com.journaldev.struts2.actions;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Namespaces;
import org.apache.struts2.convention.annotation.Result;
import com.opensymphony.xwork2.ActionSupport;
/**
* An empty class for default Action implementation for:
*
*
* /login.jsp
*
* HomeAction class will be automatically mapped for home.action
* Default page is login.jsp which will be served to client
* @author pankaj
*
*/
@Namespaces(value={@Namespace("/User"),@Namespace("/")})
@Result(location="/login.jsp")
@Actions(value={@Action(""),@Action("home")})
public class HomeAction extends ActionSupport {
}
Lưu ý rằng lớp HomeAction là một lớp rỗng, với mục đích duy nhất là chuyển tiếp request đến trang login.jsp.
package com.journaldev.struts2.actions;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Namespaces;
import org.apache.struts2.convention.annotation.Result;
/**
* Notice the @Action annotation where action and result pages are declared
* Also notice that we don't need to implement Action interface or extend ActionSupport
* class, only we need is an execute() method with same signature
* @author pankaj
*
*/
@Action(value = "login", results = {
@Result(name = "SUCCESS", location = "/welcome.jsp"),
@Result(name = "ERROR", location = "/error.jsp") })
@Namespaces(value={@Namespace("/User"),@Namespace("/")})
public class LoginAction {
public String execute() throws Exception {
if("pankaj".equals(getName()) && "admin".equals(getPwd()))
return "SUCCESS";
else return "ERROR";
}
//Java Bean to hold the form parameters
private String name;
private String pwd;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
Lưu ý việc sử dụng các annotation như @Action, @Actions, @Result, @Namespace và @Namespaces , cách sử dụng của chúng khá rõ ràng và dễ hiểu.
Giờ đây, khi chúng ta chạy ứng dụng, các trang phản hồi sau sẽ được hiển thị.
Nếu bạn đã đọc bài viết trước, nơi chúng ta xây dựng cùng một ứng dụng nhưng sử dụng cấu hình với struts.xml, bạn sẽ nhận thấy rằng mọi thứ gần như giống nhau.
Điểm khác biệt duy nhất là cách chúng ta liên kết các lớp action và các trang kết quả trong ứng dụng.
Về tác giả
Chris PhamTechnical Writer
I have over 5 years of experience writing technical documentation for tech products, making them accessible and user-friendly. My focus is always on providing clear and precise information.
@#@
Tôi đã có hơn 5 năm kinh nghiệm viết tài liệu kỹ thuật cho các sản phẩm công nghệ, giúp người dùng dễ dàng tiếp cận và sử dụng. Tôi luôn tập trung vào việc cung cấp thông tin chính xác và dễ hiểu.
Cập nhật thông tin mới nhấtNhận các thông tin mới nhất về mối đe dọa, báo cáo an ninh mạng từ CyStack về hòm thư điện tử của bạn
Thảo luận (0)
Đăng nhập để thảo luận
Bài viết liên quan
{"success":true,"head":"<title>Ví dụ Hello World trong Struts 2 sử dụng Annotation, không cần file struts.xml - CyStack Tutorial</title>\n<meta name=\"description\" content=\"Giờ đây, chúng ta đã sẵn sàng để tạo ứng dụng Hello World với Struts 2 sử dụng annotation và sẽ không cần dùng file cấu hình Struts 2.\"/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-video-preview:-1, max-image-preview:large\"/>\n<link rel=\"canonical\" href=\"https://blog.cystack.org/tutorial/2025/08/11/hello-world-trong-struts2/\" />\n<meta property=\"og:locale\" content=\"en_US\" />\n<meta property=\"og:type\" content=\"article\" />\n<meta property=\"og:title\" content=\"Ví dụ Hello World trong Struts 2 sử dụng Annotation, không cần file struts.xml - CyStack Tutorial\" />\n<meta property=\"og:description\" content=\"Giờ đây, chúng ta đã sẵn sàng để tạo ứng dụng Hello World với Struts 2 sử dụng annotation và sẽ không cần dùng file cấu hình Struts 2.\" />\n<meta property=\"og:url\" content=\"https://blog.cystack.org/tutorial/2025/08/11/hello-world-trong-struts2/\" />\n<meta property=\"og:site_name\" content=\"CyStack Tutorial\" />\n<meta property=\"article:tag\" content=\"vi\" />\n<meta property=\"article:section\" content=\"Chuyên gia\" />\n<meta property=\"og:updated_time\" content=\"2025-08-11T17:53:30+07:00\" />\n<meta property=\"og:image\" content=\"https://s2.cystack.net/tutorial/11175247/hello-world-trong-struts2.jpg\" />\n<meta property=\"og:image:secure_url\" content=\"https://s2.cystack.net/tutorial/11175247/hello-world-trong-struts2.jpg\" />\n<meta property=\"og:image:width\" content=\"1200\" />\n<meta property=\"og:image:height\" content=\"630\" />\n<meta property=\"og:image:alt\" content=\"Hello World trong Struts 2\" />\n<meta property=\"og:image:type\" content=\"image/jpeg\" />\n<meta property=\"article:published_time\" content=\"2025-08-11T17:53:19+07:00\" />\n<meta property=\"article:modified_time\" content=\"2025-08-11T17:53:30+07:00\" />\n<meta name=\"twitter:card\" content=\"summary_large_image\" />\n<meta name=\"twitter:title\" content=\"Ví dụ Hello World trong Struts 2 sử dụng Annotation, không cần file struts.xml - CyStack Tutorial\" />\n<meta name=\"twitter:description\" content=\"Giờ đây, chúng ta đã sẵn sàng để tạo ứng dụng Hello World với Struts 2 sử dụng annotation và sẽ không cần dùng file cấu hình Struts 2.\" />\n<meta name=\"twitter:image\" content=\"https://s2.cystack.net/tutorial/11175247/hello-world-trong-struts2.jpg\" />\n<meta name=\"twitter:label1\" content=\"Written by\" />\n<meta name=\"twitter:data1\" content=\"Chris Pham\" />\n<meta name=\"twitter:label2\" content=\"Time to read\" />\n<meta name=\"twitter:data2\" content=\"9 minutes\" />\n<script type=\"application/ld+json\" class=\"rank-math-schema\">{\"@context\":\"https://schema.org\",\"@graph\":[{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https://blog.cystack.org/tutorial/#person\",\"name\":\"CyStack Tutorial\"},{\"@type\":\"WebSite\",\"@id\":\"https://blog.cystack.org/tutorial/#website\",\"url\":\"https://blog.cystack.org/tutorial\",\"name\":\"CyStack Tutorial\",\"publisher\":{\"@id\":\"https://blog.cystack.org/tutorial/#person\"},\"inLanguage\":\"en-US\"},{\"@type\":\"ImageObject\",\"@id\":\"https://s2.cystack.net/tutorial/11175247/hello-world-trong-struts2.jpg\",\"url\":\"https://s2.cystack.net/tutorial/11175247/hello-world-trong-struts2.jpg\",\"width\":\"1200\",\"height\":\"630\",\"caption\":\"Hello World trong Struts 2\",\"inLanguage\":\"en-US\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https://blog.cystack.org/tutorial/2025/08/11/hello-world-trong-struts2/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":\"1\",\"item\":{\"@id\":\"https://blog.cystack.org/tutorial\",\"name\":\"Home\"}},{\"@type\":\"ListItem\",\"position\":\"2\",\"item\":{\"@id\":\"https://blog.cystack.org/tutorial/category/chuyen-gia/\",\"name\":\"Chuy\\u00ean gia\"}},{\"@type\":\"ListItem\",\"position\":\"3\",\"item\":{\"@id\":\"https://blog.cystack.org/tutorial/2025/08/11/hello-world-trong-struts2/\",\"name\":\"V\\u00ed d\\u1ee5 Hello World trong Struts 2 s\\u1eed d\\u1ee5ng Annotation, kh\\u00f4ng c\\u1ea7n file struts.xml\"}}]},{\"@type\":\"WebPage\",\"@id\":\"https://blog.cystack.org/tutorial/2025/08/11/hello-world-trong-struts2/#webpage\",\"url\":\"https://blog.cystack.org/tutorial/2025/08/11/hello-world-trong-struts2/\",\"name\":\"V\\u00ed d\\u1ee5 Hello World trong Struts 2 s\\u1eed d\\u1ee5ng Annotation, kh\\u00f4ng c\\u1ea7n file struts.xml - CyStack Tutorial\",\"datePublished\":\"2025-08-11T17:53:19+07:00\",\"dateModified\":\"2025-08-11T17:53:30+07:00\",\"isPartOf\":{\"@id\":\"https://blog.cystack.org/tutorial/#website\"},\"primaryImageOfPage\":{\"@id\":\"https://s2.cystack.net/tutorial/11175247/hello-world-trong-struts2.jpg\"},\"inLanguage\":\"en-US\",\"breadcrumb\":{\"@id\":\"https://blog.cystack.org/tutorial/2025/08/11/hello-world-trong-struts2/#breadcrumb\"}},{\"@type\":\"Person\",\"@id\":\"https://blog.cystack.org/tutorial/author/codeweaver/\",\"name\":\"Chris Pham\",\"url\":\"https://blog.cystack.org/tutorial/author/codeweaver/\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https://secure.gravatar.com/avatar/7a3584c941fa360ac061b2a8f15684ced7b92daa1f09481be135a684d989e9b9?s=96&d=mm&r=g\",\"url\":\"https://secure.gravatar.com/avatar/7a3584c941fa360ac061b2a8f15684ced7b92daa1f09481be135a684d989e9b9?s=96&d=mm&r=g\",\"caption\":\"Chris Pham\",\"inLanguage\":\"en-US\"}},{\"@type\":\"BlogPosting\",\"headline\":\"V\\u00ed d\\u1ee5 Hello World trong Struts 2 s\\u1eed d\\u1ee5ng Annotation, kh\\u00f4ng c\\u1ea7n file struts.xml - CyStack Tutorial\",\"keywords\":\"Hello World,Struts 2,Annotation\",\"datePublished\":\"2025-08-11T17:53:19+07:00\",\"dateModified\":\"2025-08-11T17:53:30+07:00\",\"articleSection\":\"Chuy\\u00ean gia\",\"author\":{\"@id\":\"https://blog.cystack.org/tutorial/author/codeweaver/\",\"name\":\"Chris Pham\"},\"publisher\":{\"@id\":\"https://blog.cystack.org/tutorial/#person\"},\"description\":\"Gi\\u1edd \\u0111\\u00e2y, ch\\u00fang ta \\u0111\\u00e3 s\\u1eb5n s\\u00e0ng \\u0111\\u1ec3 t\\u1ea1o \\u1ee9ng d\\u1ee5ng Hello World v\\u1edbi Struts 2 s\\u1eed d\\u1ee5ng annotation v\\u00e0 s\\u1ebd kh\\u00f4ng c\\u1ea7n d\\u00f9ng file c\\u1ea5u h\\u00ecnh Struts 2.\",\"name\":\"V\\u00ed d\\u1ee5 Hello World trong Struts 2 s\\u1eed d\\u1ee5ng Annotation, kh\\u00f4ng c\\u1ea7n file struts.xml - CyStack Tutorial\",\"@id\":\"https://blog.cystack.org/tutorial/2025/08/11/hello-world-trong-struts2/#richSnippet\",\"isPartOf\":{\"@id\":\"https://blog.cystack.org/tutorial/2025/08/11/hello-world-trong-struts2/#webpage\"},\"image\":{\"@id\":\"https://s2.cystack.net/tutorial/11175247/hello-world-trong-struts2.jpg\"},\"inLanguage\":\"en-US\",\"mainEntityOfPage\":{\"@id\":\"https://blog.cystack.org/tutorial/2025/08/11/hello-world-trong-struts2/#webpage\"}}]}</script>\n"}