Web Students UML Activity 12 Action Struts 7
Web-проект Students. UML Activity-діаграма (1/2) Action об'єкти Struts 7
Web-проект Students. Валідація Struts 11
Класи Student, Student. Form. User Interface Layer public class Student implements Serializable { private String name; private int course; private String department; . . . // лише set-тери тa get-тери } public class Student. Form extends Action. Form { private String name; Об'єкт-форма private String course; (бін-форма) private String department; public Action. Errors validate( Action. Mapping mapping, Http. Servlet. Request request ) {. . . } // далі лише set-тери тa get-тери Struts 12. . . }
Web-проект Students. Класи Struts 13
Data Transfer Object (DTO) public class Department { private String name; private List student. List; . . . } public class Department. DTO { private String name; private List student. List; . . . } Struts 14
Класи Student, Student. Form та їх взаємодія import org. apache. commons. beanutils. Bean. Utils; . . . public final class Insert. Student. Action extends Action { public Action. Forward execute(Action. Mapping mapping, Action. Form form, Http. Servlet. Request request, Http. Servlet. Response response) throws Exception {. . . Student. Form student. Form = (Student. Form) form; Student student = new Student(); Bean. Utils. copy. Properties (student, student. Form); . . . } } Struts 15
Class Student. Form (1/3) public class Student. Form extends Action. Form { private String name; private String course; private String department; Поля, set-тери тa get -тери public String get. Name() { return name; }. . . public void set. Department(String department) { this. department = department; } Struts 16
Class Student. Form. Валідація (2/3) public Action. Errors validate( Action. Mapping mapping, Http. Servlet. Request request ) { Метод Action. Errors errors = new Action. Errors(); validate if (get. Name()==null || get. Name(). trim(). length()==0 ) { errors. add("name", new Action. Message("errors. required", "Name")); • Message. Resources_uk. properties } • i 18 n – internationalization . . . // if (get. Course()==. . . // Валідація уведеного значення курсу // див. наступний слайд return errors; } } Struts 17
Class Student. Form. Валідація (3/3) if (get. Course()==null || get. Course(). trim(). length()==0 ) { errors. add("course", new Action. Message("errors. required", "Course")); } Метод validate (продовження). else { Валідація уведеного значення курсу (course). try { int i = Integer. parse. Int( get. Course() ); if ((i<1)||(i>5)) { errors. add("course", new Action. Message("errors. int 1 -5", "Course")); } } catch( Number. Format. Exception ne ) { errors. add("course", new Action. Message("errors. integer", "Course")); } } Struts 18
Файл struts-config. xml (фрагменти) (1/2) <struts-config> <form-beans> <form-bean name="student. Form" type="net. cyb. Student. Form"/> </form-beans> Об'єкт-форма (бін) для Action – Action Form <action-mappings> <action path="/set. Up. Student. Form" type="net. cyb. Set. Up. Student. Action" Валідація не проводиться. Готуються початкові дані для форми. name="student. Form" scope="request" за іменами: validate="false" Навігація class Set. Up. Student. Action. . . > return (mapping. find. Forward("continue")) <forward name="continue" path="/student. Form. jsp"/> </action> Struts 19
Файл struts-config. xml (фрагменти) (2/2) <action path="/insert. Student" type="net. cyb. Insert. Student. Action" name="student. Form" Об'єкт-форма для Action Область дії об'єкта-форми (об'єкт-форма scope="request" зберігається протягом запиту) validate="true" Валідація проводиться! input="/student. Form. jsp" JSP з формою для повторного уведення при наявності помилок > <forward name="success" path="/confirmation. jsp"/> </action-mappings>. . . Метод validate об'єкта-форми викликається фреймворком перед делегуванням запитів Action-об'єкту <message-resources parameter="Message. Resources" null="false"/> </struts-config> Struts 20
Локалізація. Файл Message. Resources_uk. properties (фрагменти) #-- titles -title. error=ERROR PAGE title. student. App=STUDENT_APP title. studentform=STUDENT title. student. insert. confirmation=CONFIRMATION #-- messages message. student. insert. success=Successfully added student {0} Доводиться створювати #-- validation errors *_uk. properties файли або errors. required={0} is required. “міняти” country language errors. integer={0} must be a whole number. errors. int 1 -5={0} must be a whole number in [1; 5]. #-- errors headers errors. validation. header=Errors: #-- buttons -button. submit=S U B M Struts I T 21
Валідація. Приклад (1/2). . . Message. Resources_uk. properties #-- validation errors. required={0} is required. errors. integer={0} must be a whole number. errors. int 1 -5={0} must be a whole number in [1; 5]. . . . errors. add("name", new Action. Message ("errors. required", "Name")); . . . errors. add("course", new Action. Message ("errors. required", "Course")); . . . errors. add("course", new Action. Message ("errors. int 1 -5", "Course")); . . . errors. add("course", new Action. Message ("errors. integer", "Course")); . . . Class Student. Form. Метод validate <logic: messages. Present> <div class="error"> <fmt: message key="errors. validation. header"/> <ul> <html: messages id="error"> <li><c: out value="${error}"/></li> </html: messages> </ul> </div> student. Form. jsp Struts 22 </logic: messages. Present>. . .
Використання двох action-класів для input-форм: перший розрахований на уведення даних (плюс деяку ініціалізацію), другий – на валідацію даних <action path="/any. Input" <html: form action="any". . . > type=". . . Action 1". . . name="any. Form" <html: submit>. . . validate="false"> </html: submit> <forward … "/any. Input. jsp"/>. . . </action> </html: form> <action path="/any" type=". . . Action 2" fail name="any. Form" validate="true" input="/any. Input. jsp" > <forward … "/any. Page. jsp"/> </action> Struts any. Input. jsp (сторінка з input-формою) any. Page. jsp 26
Використання двох action-класів для input-форм g Action 1 Action 2 Struts 27
class Set. Up. Student. Action public Action. Forward execute(Action. Mapping mapping, Action. Form form, Http. Servlet. Request request, Http. Servlet. Response response) throws Exception { Student. Service service = new Student. Service(); Collection departments = service. get. Departments(); Http. Session session = request. get. Session(); session. set. Attribute( "departments", departments ); Student. Form student. Form = (Student. Form)form; student. Form. set. Course("1"); return (mapping. find. Forward( "continue")); } Готуються дані для інтерфейсної форми, з якою матиме справу користувач-клієнт. Ініціалізація Struts 28
Файл student. Form. jsp (фрагменти). Struts-теги <%@ taglib prefix="html" uri="http: //struts. apache. org/tags-html" %>. . . <html: form action="insert. Student" focus="name">. . . <html: text property="name"/>. . . <html: text property="course"/>. . . <html: submit><fmt: message key="button. submit"/> </html: submit> </html: form> <a href='<c: url value="set. Up. Student. Form. do"/>'> <c: url> – JSTL-tag Add a student </a> Порівняйте з “класикою JSP-жанру” (для уведення login): <input type="text" name="username" Struts value="<%= login. Bean. get. Username() %>"/> 29
struts taglib <%@ taglib prefix="html" uri="http: //struts. apache. org/tags-html"%> <html: text property="course"/> Ще раз порівняємо <input type="text" name="course" value="<%= student. Form. get. Course() %>"/> Еквівалент за “класикою JSP-жанру” Struts 30
“Автоматична” валідація (Struts) - (2/5). Class Student. Form (нова версія) public class Student. Form extends Validator. Form { private. . . // лише String name; String course; String department; set-тери тa get-тери } Struts Не потрібно “вручну” реалізовувати метод validate 32
“Автоматична” валідація (Struts) - (3/5). Файл struts-config. xml (додатковий фрагмент) <!-- plugins --> <plug-in class. Name= "org. apache. struts. validator. Validator. Plug. In"> <set-property="pathnames" value = "/WEB-INF/validator-rules. xml, /WEB-INF/validation. xml"/> </plug-in> Конфігураційні файли валідації Struts 33
“Автоматична” валідація (Struts) - (4/5). Файл постачається у Файл validator-rules. xml готовому вигляді, # Struts Validator Error Messages містить найбільш errors. required={0} is required. розповсюджені функції валідації: errors. minlength={0} can not be less than {1} characters. required; integer; int. Range тощо. errors. integer={0} must be an integer. errors. range={0} is not in the range {1} through {2}. . Логічне ім'я функції валідації <validator name="int. Range" classname="org. apache. struts. validator. Field. Checks" method="validate. Int. Range" Ім'я метода валідації зазначеного класу method. Params="java. lang. Object, org. apache. commons. validator. Validator. Action, Параметри org. apache. commons. validator. Field, метода org. apache. struts. action. Action. Messages, валідації org. apache. commons. validator. Validator, javax. servlet. http. Http. Servlet. Request" depends="integer" Залежність у застосуванні функцій валідації Файл можна збагачувати “власними” 34 Struts msg="errors. range"/> валідаторами (функціями валідації).
“Автоматична” валідація (Struts) - (5/5). Файл validation. xml. Валідація полів форми <form-validation> errors. range={0} is not in the range {1} through {2}. Повідомлення <formset> <form name="student. Form"> Порядок застосування функцій валідації <field property="course" depends="required, integer, int. Range"> course. displayname=Course <arg 0 key="course. displayname"/> З Message. Resources_uk. properties <arg 1 name="int. Range" key="1" resource="false"/> <arg 2 name="int. Range" key="5" resource="false"/> <var><var-name>min</var-name> • var – параметри <var-value>1</var-value></var> методів валідації; • arg – аргументи у <var><var-name>max</var-name> повідомленнях про <var-value>5</var-value></var> виявлені помилки </field> <field property="name" depends="required"> <arg 0 key="name. displayname"/> </field> </formset> </form-validation> Struts 35
Форма для валідації (файли validation. xml та struts-config. xml Struts 36
Dyna. Action. Form, Dyna. Validator. Form - (1/2). Файл struts-config. xml (фрагмент з біном форми) <form-beans> <form-bean name="student. Form" type= "org. apache. struts. validator. Dyna. Validator. Form"> <form-property name="name" Не треба описувати Javatype="java. lang. String"/> клас форми! Забезпечується можливість <form-property name="course" динамічного способу type="java. lang. String"/> визначення біна-форми <form-property name="department" type="java. lang. String"/> </form-bean> Student. Form student. Form = (Student. Form)form; student. Form. set. Course("1"); Було (з класом форми) </form-beans> Нюанс: Hash. Map. Dyna. Validator. Form student. Form = спадщина! Незвичні (Dyna. Validator. Form)form; get- та set-тери student. Form. set("course", "1"); Варіант із Dyna. Validator. Form Struts String сourse = (String) student. Form. get(“course”) 37
Додаток Struts 39
Арсенал Struts Actions Головна класифікація Struts Actions (org. apache. struts. actions): • Forward Action • Include. Action • Switch. Action • Dispatch. Action – Include. Dispatch. Action Також є: ¾ ¾ ¾ Base. Action Download. Action Event. Dispatch. Action Locale. Action Mapping. Dispatch. Action Struts 40
Файл student. Form. jsp (фрагмент з form) (1/2) <html: form action="insert. Student" focus="name"> <table> <tr> <td >Name: </td> <td><html: text property="name"/></td> </tr> <td>Course: </td> <td><html: text property="course"/></td> </tr> Див. далі Struts 41
Файл student. Form. jsp (фрагмент з form) (2/2) <tr> <td>Department: </td> <html: select property="department"> <c: for. Each var="dept" items="${departments}"> <html: option value="${dept}"> <c: out value="${dept}"/></html: option> </c: for. Each> </html: select> </td> </tr> </table> <br/><br/> <html: submit><fmt: message key="button. submit"/> </html: submit> </html: form> Struts 42
Class Student. Service (фрагмент) public class Student. Service { public Collection get. Departments() { Array. List list = new Array. List(3); list. add( "TTP"); list. add( "TK"); list. add( "MI"); return list; } public Student insert. Student( Student student ) {. . . return student; } } Struts 43
- Slides: 43