Võ Văn Hải's blog

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

Cấu hình validation cho Struts 1.29 trong NetBeans 6.1

Đây là 1 cách trong nhiều cách cấu hình Validation với Struts trong Netbeans6.1

Ý tưởng chung:

Viết các kiểm tra trong phương thức validate của ActionFormBean, tương ứng các thông báo lỗi được đặt trong file application.properties.

Bước 1: Tạo project trong NetBeans6.1. Lưu ý trong Framework ta chọn Struts1.29.

Bước 2: Tạo Trang JSP.

Bước 3: Tạo StrutsActionFormBean, override phương thức validate

Bước 4: Tạo StrutsAction

Bước 5: Thêm các thông tin xuất lỗi trong ApplicationResource.properties

Bước 6: Cấu hình file struts-config.xml

Bước 7: Thực thi

Ví dụ mẫu:

Bước 1: tạo project, chọn framework struts1.29

Bước 2: Tạo trang JSP

<%@ taglib uri=”http://struts.apache.org/tags-html&#8221; prefix=”html”%>
<%@ taglib uri=”http://struts.apache.org/tags-bean&#8221; prefix=”bean”%>
<%@page contentType=”text/html” 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>JSP Page</title>
</head>
<body>
<center><h1>Order Form</h1></center>

<html:form action=”order.do”>
<table width=”75%”>
<tr>
<td align=”right”>Item Number:</td>
<td><html:text property=”item_Number” style=”width:’70′”/></td>
</tr>
<tr>
<td align=”right”>Quantity:</td>
<td><html:text  property=”quantity” style=”width:’40′” /></td>
</tr>
<tr>
<td align=”right”>Price each:</td>
<td><html:text property=”price_Each”/></td>
</tr>
<tr><td colspan=”2″><hr/></td></tr>

<tr>
<td align=”right”>First Name:</td>
<td><html:text property=”first_Name” style=”width:’70′”/></td>
</tr>
<tr>
<td align=”right”>Last Name:</td>
<td><html:text property=”last_Name” style=”width:’40′”/></td>
</tr>
<tr>
<td align=”right”>Middle Initial:</td>
<td><html:text property=”middle” style=”width:’40′”/></td>
</tr>
<tr>
<td align=”right”>Shipping Address:</td>
<td><html:textarea  property=”shipping_Address” cols=’40’ rows=”10″/></td>
</tr>
<tr>
<td  align=”right”>Credit Card</td>
<td/>
</tr>
<tr>
<td/>
<td >
<html:radio property=”credit_Card” value=”Visa”>Visa</html:radio><br/>
<html:radio property=”credit_Card” value=”Master Card”>Master Card</html:radio><br/>
<html:radio property=”credit_Card” value=”American Express”>American Express</html:radio><br/>
<html:radio property=”credit_Card” value=”Discover”>Discover</html:radio><br/>
<html:radio property=”credit_Card” value=”Java SmartCard”>Java SmartCard</html:radio><br/>
</td>
</tr>
<tr>
<td align=”right”>Credit Card Number:</td>
<td><html:text property=”credit_Card_Number” style=”width:’40′”/></td>
</tr>
<tr>
<td align=”right”>Repeat Credit Card Number:</td>
<td><html:text property=”repeat_Credit_Card_Number” style=”width:’40′”/></td>
</tr>
<tr><td colspan=”2″/><hr/></tr>
<tr>
<td colspan=”2″ align=”center”>
<html:submit value=”Submit Order”/></td>
</tr>
</table>
</html:form>

<br/>
<hr/>
<br/>
<%–các thông báo lỗi tương ứng với các lỗi bên trong phương thức
validate của OrderActionForm, nội dung thông báo lỗi nằm ở
file ApplicationResource.properties –%>
<font color=”red”>
<html:errors property=”fname”/>
<html:errors property=”lname”/>
<html:errors property=”mname”/>
<html:errors property=”saddress”/>
<html:errors property=”item_Number”/>
<html:errors property=”quantity”/>
<html:errors property=”price_Each”/>
<html:errors property=”credit_Card_Number”/>
<html:errors property=”repeatCCN”/>
<html:errors property=”credit_Card”/>
</font>
</body>
</html>

Bước 3: Tạo StrutsActionFormBean, override phương thức validate

package cnc.aptech;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class OrderActionForm extends org.apache.struts.action.ActionForm
{

private int item_Number = 0;
private int quantity = 0;
private float price_Each = 0f;
private String first_Name = “”;
private String last_Name = “”;
private String middle = “”;
private String initial = “”;
private String shipping_Address = “”;
private String credit_Card = “”;
private String credit_Card_Number = “”;
private String repeat_Credit_Card_Number = “”;

public String getCredit_Card() {
return credit_Card;
}

public void setCredit_Card(String credit_Card) {
this.credit_Card = credit_Card;
}

public String getCredit_Card_Number() {
return credit_Card_Number;
}

public void setCredit_Card_Number(String credit_Card_Number) {
this.credit_Card_Number = credit_Card_Number;
}

public String getFirst_Name() {
return first_Name;
}

public void setFirst_Name(String first_Name) {
this.first_Name = first_Name;
}

public String getInitial() {
return initial;
}

public void setInitial(String initial) {
this.initial = initial;
}

public int getItem_Number() {
return item_Number;
}

public void setItem_Number(int item_Number) {
this.item_Number = item_Number;
}

public String getLast_Name() {
return last_Name;
}

public void setLast_Name(String last_Name) {
this.last_Name = last_Name;
}

public String getMiddle() {
return middle;
}

public void setMiddle(String middle) {
this.middle = middle;
}

public float getPrice_Each() {
return price_Each;
}

public void setPrice_Each(float price_Each) {
this.price_Each = price_Each;
}

public int getQuantity() {
return quantity;
}

public void setQuantity(int quantity) {
this.quantity = quantity;
}

public String getRepeat_Credit_Card_Number() {
return repeat_Credit_Card_Number;
}

public void setRepeat_Credit_Card_Number(String repeat_Credit_Card_Number) {
this.repeat_Credit_Card_Number = repeat_Credit_Card_Number;
}

public String getShipping_Address() {
return shipping_Address;
}

public void setShipping_Address(String shipping_Address) {
this.shipping_Address = shipping_Address;
}

@Override
public void reset(ActionMapping mapping, HttpServletRequest request) {
super.reset(mapping, request);
this.item_Number = 0;
this.quantity = 0;
this.price_Each = 0f;
this.first_Name = “”;
this.last_Name = “”;
this.middle = “”;
this.initial = “”;
this.shipping_Address = “”;
this.credit_Card = “”;
this.credit_Card_Number = “”;
this.repeat_Credit_Card_Number = “”;

}

public OrderActionForm() {
super();
}

@Override
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (getFirst_Name() == null || getFirst_Name().length() < 1) {
errors.add(“fname”, new ActionMessage(“errors.required”,”First Name”));
}
if (getLast_Name() == null || getLast_Name().length() < 1) {
errors.add(“lname”, new ActionMessage(“errors.required”,”Last Name”));
}
if (getMiddle() == null || getMiddle().length() < 1) {
errors.add(“mname”, new ActionMessage(“errors.required”,”Midlle Name”));
}
if (getShipping_Address() == null || getShipping_Address().length() < 1) {
errors.add(“saddress”, new ActionMessage(“errors.required”,”Shipping Address”));
}

//if(credit_Card.equals(“”))
//    errors.add(“credit_Card”, new ActionMessage(“errors.selectone”,”<b>credit_Card</b>”));
if(item_Number<=0)
errors.add(“item_Number”, new ActionMessage(“errors.digit”,”<b>Item Number</b>”,”<b>numeric data</b>”));
if(quantity<=0)
errors.add(“quantity”, new ActionMessage(“errors.digit”,”<b>Quantity</b>”,”<b>numeric data</b>”));
if(price_Each<=0)
errors.add(“price_Each”, new ActionMessage(“errors.digit”,”<b>Price Each</b>”,”<b>numeric data</b>”));
if(credit_Card_Number.trim().equals(“”)
||!isDigit(credit_Card_Number))
errors.add(“credit_Card_Number”, new ActionMessage(“errors.numeric”,”<b>Credit Card Number</b>”,”<b>digits</b>”));
if(repeat_Credit_Card_Number.trim().equals(“”)
||!isDigit(repeat_Credit_Card_Number))
errors.add(“repeatCCN”, new ActionMessage(“errors.numeric”,”<b>Repeat_Credit_Card_Number</b>”,”<b>digits</b>”));
return errors;
}

boolean isDigit(String val){
for(int i=0;i<val.length();i++){
char x=val.charAt(i);
if(!Character.isDigit(x))
return false;
}
return true;
}
}

Bước 4: tạo struts Action

package cnc.aptech;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;

/**
*
* @author Hamy
*/
public class OrderAction 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 {
SaveData order=new SaveData();
OrderActionForm frm=(OrderActionForm)form;
boolean kq=order.UpdateOrder(frm);
if(kq==true)
return mapping.findForward(SUCCESS);
return mapping.findForward(FAILED);

}
}

Ở đây ta có kết nối database để cập nhật dữ liệu lên bảng Orders. Bean dùng để cập nhật như sau

package cnc.aptech;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/**
*
* @author Hamy
*/
public class SaveData {

public SaveData() {
}

public boolean UpdateOrder(OrderActionForm frm) {
try {
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con = DriverManager.getConnection(“jdbc:odbc:Driver={SQL Server};Server=localhost;DatabaseName=JSP_Test;username=sa;password=”);
Statement stmt = con.createStatement();
String sql = “insert into [Orders] values(”
+frm.getItem_Number()+”,”
+frm.getQuantity()+”,”
+frm.getPrice_Each()+”,'”
+frm.getFirst_Name()+”‘,'”
+frm.getLast_Name()+”‘,'”
+frm.getMiddle()+”‘,'”
+frm.getInitial()+”‘,'”
+frm.getShipping_Address()+”‘,'”
+frm.getCredit_Card()+”‘,'”
+frm.getCredit_Card_Number()+”‘,'”
+frm.getRepeat_Credit_Card_Number()
+”‘)”;
System.out.println(sql);
int x = stmt.executeUpdate(sql);
if (x < 1) {
return false;
}
con.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}

Database được cho với script sau:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Orders]’) AND type in (N’U’))
BEGIN
CREATE TABLE [dbo].[Orders](
[Item_Number] [int] NOT NULL,
[Quantity] [int] NULL,
[Price_Each] [float] NULL,
[First_Name] [nvarchar](50) NULL,
[Last_Name] [nvarchar](50) NULL,
[Middle] [nvarchar](50) NULL,
[Initial] [nvarchar](50) NULL,
[Shipping_Address] [nvarchar](50) NULL,
[Credit_Card] [varchar](50) NULL,
[Credit_Card_Number] [varchar](50) NULL,
[Repeat_Credit_Card_Number] [varchar](50) NULL,
CONSTRAINT [PK_Order] PRIMARY KEY CLUSTERED
(
[Item_Number] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END

Bước 5: Thêm các thông tin xuất lỗi trong ApplicationResource.properties

errors.header=<UL>
errors.prefix=<LI>
errors.suffix=</LI>
errors.footer=</UL>
errors.invalid={0} is invalid.
errors.maxlength={0} can not be greater than {1} characters.
errors.minlength={0} can not be less than {1} characters.
errors.range={0} is not in the range {1} through {2}.
errors.required={0} is required.
errors.byte={0} must be an byte.
errors.date={0} is not a date.
errors.double={0} must be an double.
errors.float={0} must be an float.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.short={0} must be an short.
errors.creditcard={0} is not a valid credit card number.
errors.email={0} is an invalid e-mail address.
errors.cancel=Operation cancelled.
errors.detail={0}
errors.general=The process did not complete. Details should follow.
errors.token=Request could not be completed. Operation is not in sequence.
welcome.title=Struts Application
welcome.heading=Struts Applications in Netbeans!
welcome.message=It’s easy to create Struts applications with NetBeans.
!Phần khai báo của chúng ta
errors.selectone=Invalid data at {0}, this field accepts one choice ONLY
errors.numeric=Invalid data at {0}, this field accepts {1} data ONLY
errors.digit=Invalid data at {0}, this field accepts {1} ONLY

Bước 6: Cấu hình file struts-config.xml

<?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=”orderActionForm” type=”cnc.aptech.OrderActionForm”/>
</form-beans>
<global-exceptions>
</global-exceptions>
<global-forwards>
</global-forwards>
<action-mappings>
<action name=”orderActionForm” path=”/order” scope=”session”
input=”/index.jsp” type=”cnc.aptech.OrderAction” validate=”true”>
<forward name=”failed” path=”/failed.jsp”/>
</action>
</action-mappings>
<controller processorClass=”org.apache.struts.tiles.TilesRequestProcessor”/>
<message-resources parameter=”com/myapp/struts/ApplicationResource”/>

<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>
</struts-config>

Bước 7: Thực thi

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

20 Responses to “Cấu hình validation cho Struts 1.29 trong NetBeans 6.1”

  1. minhtu said

    thay co bai demo cua struts jsp cho em xin.

  2. TuanNA said

    Demo struts1 hay struts2 vậy bạn, bạn thích demo trên NetBeans hay trên Eclipse vậy. Đọc địa chỉ mail đi tôi sẽ gửi bài hướng dẫn cho bạn, thầy bận rất nhiều việc nên không phải lúc nào cũng có thể trả lời bạn

  3. hoangtrong said

    nick của bạn TuanNA là gì .
    hay bạn có thể add mick mình vô đê mình có thể hỏi vài vấn đề về lập trình được 0 .
    nick mình là :
    hoang_trong_1988@yahoo.com

  4. Hung said

    Thay co bai demo hay huong dan nao ve viec viet unit test khong cho em xin. Em vua hoc xong mon jsp and Struts va dang tim hieu ve spring. Thay co huong dan nao ve viec su dung Spring khong co the cho em duoc khong.

  5. Thiet said

    em dang hoc struts 1 thay co cai demo cho em xin duoc ko a? Email cua em la :phanthietpc@yahoo.com.vn .Em cam on thay

  6. duc said

    da em cung dang can 1 cai demo struts 1 hay 2 gi cung duoc a

  7. duc said

    mail cua em la quangduc0221@gmail.com

  8. Ngoc said

    Thầy ơi, cho e xin bài demo Struts đăng nhập trên NetBeans được ko ah, mail của e là leluungoc@yahoo.com.vn

  9. Ha Thanh Quang said

    Thầy cho em hỏi mình có thể viết code javascript trong struts hay không?em có thử làm nhưng e ko thể lấy giá trị của textbox bằng lệnh document.form.name.value;

  10. Nam said

    thay cho e xin cai demo nhe!cam on thay nhieu!

  11. vovanhai said

    Viết bình thường, có điều có vẻ hơi ngược ngược chút. Tuy nhiên, các vụ validation trên form,.. thì js la lựa chọn tốt đấy!
    Bạn xem lại cú pháp, khai báo đã viết đúng chưa?

  12. minh co vi du ve struts said

    ban co the lien he voi email cua minh
    minh se goi cac bai demo struts cho ban
    rat vui duoc lam wen voi cac ban!

  13. minh co vi du ve struts said

    mail:trung244@gmail.com

  14. minh co vi du ve struts said

    skype: thusinhgiangho244

  15. Đồng said

    Thầy ơi,khi em ấn submit thi nó báo là not request ạ.nó ko kiểm tra mà nó nhảy thẳng vào luôn ,ko biết em cấu hình sai chỗ nào và em copy bài của Thầy về cũng báo như vậy.Thầy có thể cho em bài demo gửi vào mail cho em được ko a.cảm ơn Thầy nhiều

  16. Việt said

    Thầy có code demo struct cho em xin duoo không ạ!

  17. Võ Văn Hải said

    Bạn muốn code gì? nói rõ nhé

  18. Hoài Giang said

    E chào Thầy, e đang gặp 1 lỗi phát sinh trong khi làm validate ở struts 1.29 mong Thầy giải đáp giúp. Lỗi e là:
    Khi e chạy 1 trang jsp trước rồi mới chuyển đến StrutsAction thì việc validate thực hiện ngon. Nhưng khi e cho StrutsAction chạy trước rồi mới điều hướng đến 1 trang jsp có validate để hiển thị thì gặp lỗi là có điều hướng đến nhưng trang trắng và e xem phần log thì ko thấy báo lỗi gì. E comment phần validate trong StrutsActionFormBean lại thì bài lại chạy tốt. Mong Thầy cho giải đáp giùm e ạ

  19. thuthuy said

    em chao thay . thay oi thay co the cho em xin code vi du ve chuc nang dang ki bang strust k a . nhung theo kieu mvc co 3 goi thay a.em chua lam bao gio len k bit tim tn nao nua hien gio em van k lam duoc

  20. thuthuy said

    thay oi email cua em la :thuynt.319@gmail.com. em rat mong duoc thay giup do 😦

Leave a comment

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