Thứ Sáu, 25 tháng 6, 2010

Struts 2 helloWorld

:D Bài viết là tổng hợp những gì đã đọc, thấy hay post lại, nên nhiều chỗ chưa dịch :D

I. Struts:

Trước tiên nhắc lại JSP và Servlet:

Một servlet là một chương trình viết bằng java chạy trên máy ảo Java (JVM) ở phía máy chủ (Web Server). các Servlet nhận và phản hồi từ Web client, thường thường sử dụng giao thức HTTP- Hyper Text Transfer Protocol. Để hiển thị một trang web với định dạng html, nếu chỉ dùng Servlet thì sẽ phải println() các mã html về client.

Khi có một request đến, servlet container sẽ kiểm tra xem có servlet nào đã đăng ký cho request đó chưa. Nếu có, request sẽ chuyển tới servlet. Nếu không, request sẽ trả về HTTP server.

Filter nằm ở giữa client và servlet. Request gửi lên và response trả về sẽ phải đi qua filter . Tương tự như một servlet phụ, filter không thực thi một chức năng điều khiển riêng biệt, mà nó chỉ cùng tham gia vào quá trình xử lý các request.

Công nghệ JSP là một phần mở rộng của công nghệ Java Servlet. Tập tin .jsp có cấu trúc giống như tập tin .html truyền thống, nhưng khác ở chỗ là tập tin .jsp có xen lẫn mã Java. Mã Java được tách biệt với phần HTML thông thường bằng cặp dấu <% và %>. Trang JSP khi chạy, mã Java sẽ được được tách ra khỏi nội dung bình thường của trang JSP biên dịch thành Java Servlet . Kết quả xử lý của Servlet được thay vào chỗ biểu thức JSP trong trang Web ban đầu. Trang Web mà trình duyệt nhận được là trang HTML thuần túy.

Struts:
Nếu tất cả mọi thứ đều gói gọi trong servlet hoặc JSP thì sẽ không phù hợp cho việc phát triển các ứng dụng quy mô lớn do:
- Do các tính năng bị lặp lại -> code lặp lại
- Code mỗi người có một phong cách riêng, không biết đâu mà lần...
...
--> MVC (Model-View-Control) giải quyết các vấn đề trên do có sự phân tách rõ ràng trong ứng dụng.
Struts là một framework sử dụng mẫu thiết kế MVC, nó có các thư viện tiện ích để làm cho việc phát triển MVC được nhanh hơn và dễ dàng hơn.
Struts2 có nhiều tính năng nổi trội hơn Struts1 (nghe nói vậy :D)
MVC thể hiện trong Struts như thế nào?
View component: presentation logic. Ví dụ như các trang jsp hay html đơn giản....
Model component: business logic và data. Các model component cung cấp một giao diện với dữ liệu và/hoặc các dịch vụ được sử dụng bởi ứng dụng. Theo cách này, các controller component không cần phải chứa code để thao tác với dữ liệu của ứng dụng. Thay vào đó, chúng giao tiếp với các model component để thực hiện truy cập và thao tác dữ liệu. Các model component có thể ở nhiều dạng từ các Java bean đến các EJB hay các Web service.
Controller component: Struts 2 sử dụng filter làm nền tảng cho controller, thay vì dùng servlet. Chúng  nằm trong gói thư viện struts2-core. Controller quản lý sự tương tác giữa Model và View.

II. Struts 2 HelloWorld

HelloWorld exaple:
Vào nguồn link sau để xem hướng dẫn dầy đủ, download source + lib:  http://www.vaannila.com/struts-2/struts-2-example/struts-2-hello-world-example-1.html

Ngó qua ví dụ:

Người dùng ở trang index.jsp, nhập username, nhấn submit, sẽ chuyển đến trang success.jsp hiện ra dòng  "Hello [username]".

Để làm ví dụ trên, phải có 3 thứ:

  1. Có một trang để hiện message

  2. Tạo Action class để sinh message

  3. Mapping giữa action và message page.


1. Trang hiển thị message: success.jsp


<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World</title>
</head>
<body>
<h1><s:property value="message" /></h1>
</body>
</html>


2. Action class sinh message: HelloWorld.java
package vaannila;

public class HelloWorld {
private String message;

private String userName;

public HelloWorld() {
}

public String execute() {
setMessage("Hello " + getUserName());
return "SUCCESS";
}
.......
// các hàm get, set cho các thuộc tính message, userName
.......
}

3. Mapping giữa action và message page.
<struts>
<package name="test" extends="struts-default">
<action name="HelloWorld">
<result name="SUCCESS">/success.jsp</result>
</action>
</package>
</struts>

Sau khi nhập username và submit từ trang "/index.jsp" , sẽ gửi request đến URL "/HellWorld.action" và message "Hello [username]" hiện ra.

Code trên hoạt động thế nào?

(Trích nguyên văn trong bài hướng dẫn, mọi người tự dịch :D)

  1. The container receives from the web server a request for the resource HelloWorld.action. According to the settings loaded from the web.xml, the container finds that all requests are being routed to org.apache.struts2.dispatcher.FilterDispatcher, including the *.action requests. The FilterDispatcher is the entry point into the framework.

  2. The framework looks for an action mapping named "HelloWorld", and it finds that this mapping corresponds to the class "HelloWorld". The framework instantiates the Action and calls the Action's execute method.

  3. The execute method sets the message and returns SUCCESS. The framework checks the action mapping to see what page to load if SUCCESS is returned. The framework tells the container to render as the response to the request, the resource HelloWorld.jsp.

  4. As the page HelloWorld.jsp is being processed, the <s:property value="message" /> tag calls the getter getMessage of the HelloWorld Action, and the tag merges into the response the value of the message.

  5. A pure HMTL response is sent back to the browser.


III. Các thành phần config:

Vào đây để xem tài liệu đẩy đủ.

Một web application sử dụng deployment descriptor để khởi tạo các  resources như servlets, taglibs. Deployment descriptor có dạng xml được đặt tên là "web.xml".

Cũng như vậy, framework struts sử dụng file config để khởi tạo các resources của nó. bao gồm:

  • Interceptors that can preprocess and postprocess a request

  • Action classes that can call business logic and data access code

  • Results that can prepare views, like JavaServer Pages and FreeMarker templates


Trước lúc runtime, configuration được định nghĩa từ 1 hoặc nhiều XML document, bao gồm cả struts.xml. Khi runtime sẽ có một configuration duy nhất cho một application. Có nhiểu element được configure bao gồm packages, namespaces, includes, actions, results, interceptors, and exceptions.

1. web.xml

Trong ví dụ HelloWorld trên:



web.xml :
<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>

Filter và filter-mapping dùng để  setup filter. Ở đây dùng FilterDispatcher. Ở đây filter được map tới URL pattern "/*" . Có nghĩa tất cả các request tới Struts 2 action sẽ được xử lý bởi FilterDispatcher class.


2. struts.xml

Trong ví dụ HelloWorld trên:


struts.xml :
<struts>
<package name="test" extends="struts-default">
<action name="HelloWorld">
<result name="SUCCESS">/success.jsp</result>
</action>
</package>
</struts>


a. Administrative Elements

Bean Configuration:



<struts>
<bean type="com.opensymphony.xwork2.ObjectFactory" name="myfactory" class="com.company.myapp.MyObjectFactory" />
...
</struts>

Constant Configuration: có thể được khai báo ở nhiều file:


struts.xml



<struts>
<constant name="struts.devMode" value="true" />
...
</struts>

struts.properties



struts.devMode = true

web.xml



<web-app id="WebApp_9" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
<init-param>
<param-name>struts.devMode</param-name>
<param-value>true</param-value>
</init-param>
</filter>
...
</web-app>

Package Configuration
Namespace Configuration



<package name="default">
<action name="foo" class="mypackage.simpleAction">
<result name="success" type="dispatcher">greeting.jsp</result>
</action>

<action name="bar" class="mypackage.simpleAction">
<result name="success" type="dispatcher">bar1.jsp</result>
</action>
</package>

<package name="mypackage1" namespace="/">
<action name="moo" class="mypackage.simpleAction">
<result name="success" type="dispatcher">moo.jsp</result>
</action>
</package>

<package name="mypackage2" namespace="/barspace">
<action name="bar" class="mypackage.simpleAction">
<result name="success" type="dispatcher">bar2.jsp</result>
</action>
</package>

Namespace are not hierarchical like a file system path. There is one namespace level. For example if the URL /barspace/myspace/bar.action is requested, the framework will first look for namespace /barspace/myspace. If the action does not exist at /barspace/myspace, the search will immediately fall back to the default namespace "".


Include Configuration:



<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<include file="Home.xml"/>
<include file="Hello.xml"/>
<include file="Simple.xml"/>
<include file="/util/POJO.xml"/>
<include file="/com/initech/admin/admin-struts.xml"/>
</struts>


b.Request Handling Elements

Interceptor Configuration:


Interceptors allow you to define code to be executed before and/or after the execution of an Action method. (The "Filter" pattern.) Interceptors can be a powerful tool when developing applications. There are many, many use cases for Interceptors, including validation, property population, security, logging, and profiling.



Registering Interceptors

<interceptors>
<interceptor name="security" class="com.company.security.SecurityInterceptor"/>
<interceptor-stack name="secureStack">
<interceptor-ref name="security"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>

Action Configuration



<package name="Hello" extends="action-default">

<default-action-ref name="UnderConstruction">

<action name="UnderConstruction">
<result>/UnderConstruction.jsp</result>
</action>

...


Wildcard Mappings


"action=Crud_input"
"action=Crud_delete"



<action name="Crud_*" class="example.Crud" method="{1}">

<action name="*">
<result>/{1}.jsp</result>
</action>

Result Configuration:


Most often, results are nested with the action element. But some results apply to multiple actions. In a secure application, a client might try to access a page without being authorized, and many actions may need access to a "logon" result.



<global-results>
<result name="error">/Error.jsp</result>
<result name="invalid.token">/Error.jsp</result>
<result name="login" type="redirectAction">Logon!input</result>
</global-results>


c. Error Handling

Exception Configuration:

Interceptor is needed to activate the exception mapping functionality. Điểu này đã được làm mặc định trong struts-default.xml
<struts>
<package name="default">
...
<global-results>
<result name="login" type="redirect">/Login.action</result>
<result name="Exception">/Exception.jsp</result>
</global-results>

<global-exception-mappings>
<exception-mapping exception="java.sql.SQLException" result="SQLException"/>
<exception-mapping exception="java.lang.Exception" result="Exception"/>
</global-exception-mappings>
...
<action name="DataAccess" class="com.company.DataAccess">
<exception-mapping exception="com.company.SecurityException" result="login"/>
<result name="SQLException" type="chain">SQLExceptionAction</result>
<result>/DataAccess.jsp</result>
</action>
...
</package>
</struts>



By default, the ExceptionMappingInterceptor adds the following values to the Value Stack:











exceptionThe exception object itself
exceptionStackThe value from the stack trace


Sample JSP using Error and Exception Values

<h2>An unexpected error has occurred</h2>
<p>
Please report this error to your system administrator
or appropriate technical support personnel.
Thank you for your cooperation.
</p>
<hr/>
<h3>Error Message</h3>
<s:actionerror/>
<p>
<s:property value="%{exception.message}"/>
</p>
<hr/>
<h3>Technical Details</h3>
<p>
<s:property value="%{exceptionStack}"/>
</p>

III. Tài liệu đã dùng trong bài:

http://www.vaannila.com/struts/struts-tutorial/struts-tutorial.html

http://www.humg.edu.vn/cntt/forum?func=view&id=437&catid=21

http://struts.apache.org/2.0.14/docs/configuration-elements.html

32 nhận xét:

  1. Đề nghị tác giả tìm hiểu thêm về MVC lẫn Struts để hoàn thiện bài viết .

    Trả lờiXóa
  2. Đọc xong chả hiểu viết về vđ gì luôn .... Vân ơi tớ 'sờ chút' ... :))

    Trả lờiXóa
  3. vãi hàng comment của ông Tuấn =))

    Trả lờiXóa
  4. A person essentially help to make severely posts I would state. That is the first time I frequented your website page and up to now? I surprised with the research you made to make this actual submit extraordinary. Excellent job!

    Trả lờiXóa
  5. Can I ask you something - and let's be frank for a second - if I told you that you will wake up with a minimum of $278 net in comissions tomorrow, would you be interested? If so, stop what you're doing *right now* and go here >--->> http://earn7800permonth.com That moment when everything just clicks and you "get it" is what every beginner is looking for. You don't have to wait for months going through a 10 hour course, you only need the basics to get paid. No bs and no tricks, take it or leave it: http://earn7800permonth.com

    Trả lờiXóa
  6. We absolutely love your blog and find most of your post's to be just what I'm looking for. can you offer guest writers to write content for you personally? I wouldn't mind composing a post or elaborating on many of the subjects you write in relation to here. Again, awesome web site!

    Trả lờiXóa
  7. I really like your blog.. very nice colors & theme. Did you make this website yourself or did you hire someone to do it for you? Plz reply as I'm looking to construct my own blog and would like to find out where u got this from. appreciate it

    Trả lờiXóa
  8. cialis 10 mg whether Viagra is the actual cause of vision loss.

    Trả lờiXóa
  9. viagra thailand enrich their muscles. In turn, they believe that it will enhance their performance.1]

    Trả lờiXóa
  10. I just could not depart your website prior to suggesting that I really enjoyed the standard info a person provide for your visitors? Is gonna be back often to check up on new posts

    Trả lờiXóa
  11. I've got a few minutes then I'm going out for a swim, but I just wanted to say to anyone trying to earn a living online, you can do it!! It's been 8 weeks since I began and I'm finally stabilizing at about $100-$150 a day with http://earn-1100-weekly.info So it certainly is working. Hint: start with the main video..

    Trả lờiXóa
  12. When I originally commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added I get four e-mails with the same comment. Is there any way you can remove me from that service? Many thanks!

    Trả lờiXóa
  13. cheap female viagra multiple reasons, one of them being that I didn’t want her to worry about me for next to nothing which, in turn,

    Trả lờiXóa
  14. cialis and women sildenafil, increasing the incidence and severity of side effects. It is recommended that patients using

    Trả lờiXóa
  15. cialis dosage injury. cialis best price mergency medical attention if your erection is painful or lasts longer than 4 hours. A prolonged erection (priapism) generic cialis overnight delivery Sulfonation to the chlorosulfonyl derivative cialis free trial tablets after a consultation with a pharmacist.3] low cost cialis,compare generic cialis prices,brand name cialis,cialis mexico

    Trả lờiXóa
  16. Between me and my husband we've owned more MP3 players over the years than I can count, including Sansas, iRivers, iPods (classic & touch), the Ibiza Rhapsody, etc. But, the last few years I've settled down to one line of players. Why? Because I was happy to discover how well-designed and fun to use the underappreciated (and widely mocked) Zunes are.

    Trả lờiXóa
  17. what does cialis look like sildenafil, increasing the incidence and severity of side effects. It is recommended that patients using cialis professional review from degradation by cGMP-specific phosphodiesterase type 5 (PDE5) in the corpus cavernosum. Nitric oxide cialis and women to its recreational use.5] The reasons behind such use include the belief that the drug increases libido, cialis dosage 40 mg pressure) and angina pectoris (a symptom of ischaemic heart disease). The first clinical trials were conducted lowest price cialis,cialis without prescription in canada,online generic cialis,brand cialis for sale

    Trả lờiXóa
  18. I made a about $3 million last year just looting the hell out of http://make1250weekly.info Man I love my life. Knowledge is power.

    Trả lờiXóa
  19. You've heard of finders fees? How would you like to earn $500 to $1,000 in as little as 24 hours? The system helps you find certain types of opportunities and then cash in on them. As soon as you spot an opportunity, all you have to do is pass it off to some other individual, and they are going to be more than happy to give you $500 to $1,000, sort of like a finders fee. This is something entirely new and not the sale old methods that so many others are attempting to use to earn money online. Go check it out... http://tinyurl.com/7n5fkpn

    Trả lờiXóa
  20. was able to improve sexual function in female patients on antidepressants as well.] cialis without prescription being taken off the market.3] cialis daily side effects A UK patent held by Pfizer on the use of PDE5 inhibitors (see below) as treatment of impotence was cialis soft tab reported a sudden decrease or loss of vision. It is not possible to determine whether these events are

    Trả lờiXóa
  21. ... [Trackback]...

    [...] Informations on that Topic: i-php.net/2010/06/struts-2-helloworld/ [...]...

    Trả lờiXóa
  22. Truthfully, http://themostpowerfulincomestrategy.info really works holy hell. I'm still in shock - yesterday I was blessed with $348.77 in earnings. I just can't believe it's taken me so long to get it.

    Trả lờiXóa
  23. Okay, I have a little secret that I can't keep any longer. I discovered something pretty nifty. This really is something which you could get started with right away and better yet, see the results within hours. It will be done from anywhere in the entire world and does not require any technical skills. No, you do not even need to truly have a website and you do not have to rely on Google for anything. Okay, I'll share it with you. Go ahead and have a look... http://tinyurl.com/ckgcdlo

    Trả lờiXóa
  24. In contrast to what many people think about the drug, Viagra isn't a magic solution to all of your problems usa cialis Many men come to a point in life when they have to admit to themselves they’re not performing in bed like they cialis soft tabs generic advised me to avoid them because she thinks there are too many scams and it’s easy to get fooled these days. erectile quality, but did reduce the post-ejaculatory refractory time.6] This study also noted a significant

    Trả lờiXóa
  25. Hello there! I hope you are having a great sunday! These last few days have too good, I've made about $1,750 thus far in comissions, swear to God!! :) Each hour and minute you're not spending on http://make1351perweek.info is one more you are spending without freedom.

    Trả lờiXóa