오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷 실무전문 강의)
이번 예제는 이전의 강좌인 "Struts를 이용한 간단한 로그인 예제”의 기능에 Validation 기능을 간단히 추가해 보도록 하겠습니다. "Struts를 이용한 간단한 로그인 예제” 강좌에 나와 있는 내용에 대해서는 이번 강좌에서는 언급하지 않고 Validation을 위해 추가되는 코드 부분만 기술토록 하겠습니다.
혹시 "Struts를 이용한 간단한 로그인 예제”부분이 궁금하신 분들은 해당 강좌를 참고 하시기 바랍니다.
[검증 조건]
사용자 ID는 필수입력, 5~10자를 넘을 수 없으며, 시작은 알파벳으로
비밀번호는 필수입력이며 10자를 넘을 수 없음, 시작은 알파벳, 숫자로…
=========================================================
1.Struts 설정 파일에 Validator Plug-in을 Add 합니다. (메시지 리소스 설정 다음에 추가 합니다.)
<plug-in
className="org.apache.struts.validator.ValidatorPlugIn">
<set-property
property="pathnames"
value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>
----------------------------------------------------------------
2.Blank Struts Web Application에서 validator-rules.xml 과 validation.xml 파일을 복사 합니다. (struts 배포판안에 struts-blank.war 파일이 포함되어 있으며 이 파일을 TOMCAT_HOME/webapps 아래에 둔 후 톰캣을 실행하면 저절로 압축이 풀리며 /WEB-INF/ 아래에 보시면 두개의 파일이 있습니다.)
-----------------------------------------------------------------
참고로 파일의 내용은 다음과 같습니다.
-------------------------------
validation.xml
-------------------------------
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
<form-validation>
<!--
This is a minimal Validator form file with a couple of examples.
-->
<global>
<!-- An example global constant
<constant>
<constant-name>postalCode</constant-name>
<constant-value>^\d{5}\d*$</constant-value>
</constant>
end example-->
</global>
<formset>
<!-- An example form -->
<form name="logonForm">
<field
property="username"
depends="required">
<arg key="logonForm.username"/>
</field>
<field
property="password"
depends="required,mask">
<arg key="logonForm.password"/>
<var>
<var-name>mask</var-name>
<var-value>^[0-9a-zA-Z]*$</var-value>
</var>
</field>
</form>
</formset>
<!-- An example formset for another locale -->
<formset language="fr">
<constant>
<constant-name>postalCode</constant-name>
<constant-value>^[0-9a-zA-Z]*$</constant-value>
</constant>
<!-- An example form -->
<form name="logonForm">
<field
property="username"
depends="required">
<arg key="logonForm.username"/>
</field>
<field
property="password"
depends="required,mask">
<arg key="logonForm.password"/>
<var>
<var-name>mask</var-name>
<var-value>^[0-9a-zA-Z]*$</var-value>
</var>
</field>
</form>
</formset>
</form-validation>
-------------------------------
validator-rule.xml
-------------------------------
<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
<!--
$Id: validator-rules.xml 54932 2004-10-16 17:02:16Z germuska $
This file contains the default Struts Validator pluggable validator
definitions. It should be placed somewhere under /WEB-INF and
referenced in the struts-config.xml under the plug-in element
for the ValidatorPlugIn.
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
/WEB-INF/validation.xml"/>
</plug-in>
These are the default error messages associated with
each validator defined in this file. They should be
added to your projects ApplicationResources.properties
file or you can associate new ones by modifying the
pluggable validators msg attributes in this file.
# Struts Validator Error Messages
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
errors.invalid={0} is invalid.
errors.byte={0} must be a byte.
errors.short={0} must be a short.
errors.integer={0} must be an integer.
errors.long={0} must be a long.
errors.float={0} must be a float.
errors.double={0} must be a double.
errors.date={0} is not a date.
errors.range={0} is not in the range {1} through {2}.
errors.creditcard={0} is an invalid credit card number.
errors.email={0} is an invalid e-mail address.
Note: Starting in Struts 1.2.0 the default javascript definitions have
been consolidated to commons-validator. The default can be overridden
by supplying a <javascript> element with a CDATA section, just as
in struts 1.1.
-->
<form-validation>
<global>
<validator name="required"
classname="org.apache.struts.validator.FieldChecks"
method="validateRequired"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
javax.servlet.http.HttpServletRequest"
msg="errors.required"/>
<validator name="requiredif"
classname="org.apache.struts.validator.FieldChecks"
method="validateRequiredIf"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest"
msg="errors.required"/>
<validator name="validwhen"
msg="errors.required"
classname="org.apache.struts.validator.validwhen.ValidWhen"
method="validateValidWhen"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest"/>
<validator name="minlength"
classname="org.apache.struts.validator.FieldChecks"
method="validateMinLength"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
javax.servlet.http.HttpServletRequest"
depends=""
msg="errors.minlength"
jsFunction="org.apache.commons.validator.javascript.validateMinLength"/>
<validator name="maxlength"
classname="org.apache.struts.validator.FieldChecks"
method="validateMaxLength"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
javax.servlet.http.HttpServletRequest"
depends=""
msg="errors.maxlength"
jsFunction="org.apache.commons.validator.javascript.validateMaxLength"/>
<validator name="mask"
classname="org.apache.struts.validator.FieldChecks"
method="validateMask"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
javax.servlet.http.HttpServletRequest"
depends=""
msg="errors.invalid"/>
<validator name="byte"
classname="org.apache.struts.validator.FieldChecks"
method="validateByte"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
javax.servlet.http.HttpServletRequest"
depends=""
msg="errors.byte"
jsFunctionName="ByteValidations"/>
<validator name="short"
classname="org.apache.struts.validator.FieldChecks"
method="validateShort"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
javax.servlet.http.HttpServletRequest"
depends=""
msg="errors.short"
jsFunctionName="ShortValidations"/>
<validator name="integer"
classname="org.apache.struts.validator.FieldChecks"
method="validateInteger"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
javax.servlet.http.HttpServletRequest"
depends=""
msg="errors.integer"
jsFunctionName="IntegerValidations"/>
<validator name="long"
classname="org.apache.struts.validator.FieldChecks"
method="validateLong"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
javax.servlet.http.HttpServletRequest"
depends=""
msg="errors.long"/>
<validator name="float"
classname="org.apache.struts.validator.FieldChecks"
method="validateFloat"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
javax.servlet.http.HttpServletRequest"
depends=""
msg="errors.float"
jsFunctionName="FloatValidations"/>
<validator name="double"
classname="org.apache.struts.validator.FieldChecks"
method="validateDouble"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
javax.servlet.http.HttpServletRequest"
depends=""
msg="errors.double"/>
<validator name="date"
classname="org.apache.struts.validator.FieldChecks"
method="validateDate"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
javax.servlet.http.HttpServletRequest"
depends=""
msg="errors.date"
jsFunctionName="DateValidations"/>
<validator name="intRange"
classname="org.apache.struts.validator.FieldChecks"
method="validateIntRange"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
javax.servlet.http.HttpServletRequest"
depends="integer"
msg="errors.range"/>
<validator name="floatRange"
classname="org.apache.struts.validator.FieldChecks"
method="validateFloatRange"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
javax.servlet.http.HttpServletRequest"
depends="float"
msg="errors.range"/>
<validator name="creditCard"
classname="org.apache.struts.validator.FieldChecks"
method="validateCreditCard"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
javax.servlet.http.HttpServletRequest"
depends=""
msg="errors.creditcard"/>
<validator name="email"
classname="org.apache.struts.validator.FieldChecks"
method="validateEmail"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
javax.servlet.http.HttpServletRequest"
depends=""
msg="errors.email"/>
<validator name="url"
classname="org.apache.struts.validator.FieldChecks"
method="validateUrl"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
javax.servlet.http.HttpServletRequest"
depends=""
msg="errors.url"/>
<!--
This simply allows struts to include the validateUtilities into a page, it should
not be used as a validation rule.
-->
<validator name="includeJavaScriptUtilities"
classname=""
method=""
methodParams=""
depends=""
msg=""
jsFunction="org.apache.commons.validator.javascript.validateUtilities"/>
</global>
</form-validation>
--------------------------------------------------------------
3.ActionForm 클래스(LoginForm.java)를 다음과 같이 수정 합니다. LoginForm 클래스가 ValidatorForm 클래스를 상속 받도록 구성 합니다. 물론 import org.apache.struts.validator.ValidatorForm; 문장도 추가 하구요…
혹시 validate() 메소드가 재정의 되어 있다면 주석으로 막으세요~
--------------------------------------------------------------
import org.apache.struts.validator.ValidatorForm;
public class LoginForm extends ValidatorForm {
-----------------------------------------------------------------
4.validation.xml 파일을 다음처럼 수정 합니다. minlength, maxlength인 경우 오류 출력시 매개변수가 두 개 필요 합니다.
-----------------------------------------------------------------
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
그래서 아래 설정에서 매개변수가 2개로 되어 있으니 참고 바랍니다.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
<form-validation>
<!--
This is a minimal Validator form file with a couple of examples.
-->
<global>
<!-- An example global constant
<constant>
<constant-name>postalCode</constant-name>
<constant-value>^\d{5}\d*$</constant-value>
</constant>
end example-->
</global>
<formset>
<!-- An example form -->
<form name="loginForm">
<field
property="id"
depends="required, minlength, maxlength, mask">
<arg0 key="prompt.id"/>
<arg1 key="${var:maxlength}"
name="maxlength"
resource="false"/>
<arg1 key="${var:minlength}"
name="minlength"
resource="false"/>
<var>
<var-name>minlength</var-name>
<var-value>5</var-value>
</var>
<var>
<var-name>maxlength</var-name>
<var-value>10</var-value>
</var>
<var>
<var-name>mask</var-name>
<var-value>^[a-zA-Z]*$</var-value>
</var>
</field>
<field
property="pwd"
depends="required,mask">
<arg0 key="prompt.password"/>
<arg1 key="${var:maxlength}"
name="maxlength"
resource="false"/>
<var>
<var-name>mask</var-name>
<var-value>^[0-9a-zA-Z]*$</var-value>
</var>
<var>
<var-name>maxlength</var-name>
<var-value>10</var-value>
</var>
</field>
</form>
</formset>
</form-validation>
-----------------------------------------------
5.validator-rule.xml 파일은 그대로 사용 합니다.
-----------------------------------------------
--------------------------------------------------------------------
6.application.properties 파일은 리소스 번들 파일로서 에러 메시지 출력을 위해 사용 합니다.
--------------------------------------------------------------------
login.title = LogIn
login.login = Login
login.reset = Cancel
prompt.id= User ID :
prompt.password=Password :
main.title=Main
user.depttitle=DeptNo
user.ename=ENAME
user.job=JOB
jdbc.error=SAVE FAIL!!!
# Struts Validator Error Messages
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
errors.invalid={0} is invalid.
errors.byte={0} must be a byte.
errors.short={0} must be a short.
errors.integer={0} must be an integer.
errors.long={0} must be a long.
errors.float={0} must be a float.
errors.double={0} must be a double.
errors.date={0} is not a date.
errors.range={0} is not in the range {1} through {2}.
errors.creditcard={0} is an invalid credit card number.
errors.email={0} is an invalid e-mail address.
###############################################3
error.id.required=<li>ID REQUIRED.</li>
error.pwd.required=<li>PASSWORD REQUIRED</li>
error.login.invalid=<li>ID/PASSWORD NOT CORRECT</li>
errors.header=<h3><font color="red">ERROR!</font></h3>
You must correct the following error(s) before proceeding:<UL>
errors.footer=</ul><hr>
--------------------------
7.struts-config.xml
--------------------------
<!-- Form Bean Definitions -->
<form-beans>
<form-bean name="loginForm" type="login2.LoginForm"/>
</form-beans>
<!--Action Mapping Definitions -->
<action-mappings>
<!-- loginAction에 대한 정의 -->
<action
path="/LoginSubmit"
type="login2.LoginAction"
name="loginForm"
input="/login.jsp"
/>
</action-mappings>
댓글 없음:
댓글 쓰기