KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > web > servlet > mvc > FormControllerTests


1 /*
2  * Copyright 2002-2005 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.web.servlet.mvc;
18
19 import java.io.IOException JavaDoc;
20 import java.util.HashMap JavaDoc;
21 import java.util.Map JavaDoc;
22
23 import javax.servlet.ServletException JavaDoc;
24 import javax.servlet.http.HttpServletRequest JavaDoc;
25 import javax.servlet.http.HttpServletResponse JavaDoc;
26
27 import junit.framework.TestCase;
28
29 import org.springframework.beans.IndexedTestBean;
30 import org.springframework.beans.TestBean;
31 import org.springframework.context.support.StaticApplicationContext;
32 import org.springframework.mock.web.MockHttpServletRequest;
33 import org.springframework.mock.web.MockHttpServletResponse;
34 import org.springframework.mock.web.MockServletContext;
35 import org.springframework.validation.BindException;
36 import org.springframework.validation.Errors;
37 import org.springframework.validation.FieldError;
38 import org.springframework.validation.ObjectError;
39 import org.springframework.validation.Validator;
40 import org.springframework.web.context.support.StaticWebApplicationContext;
41 import org.springframework.web.servlet.ModelAndView;
42
43 /**
44  * @author Rod Johnson
45  * @author Juergen Hoeller
46  */

47 public class FormControllerTests extends TestCase {
48     
49     public void testReferenceDataOnForm() throws Exception JavaDoc {
50         String JavaDoc formView = "f";
51         String JavaDoc successView = "s";
52         
53         RefController mc = new RefController();
54         mc.setFormView(formView);
55         mc.setCommandName("tb");
56         mc.setSuccessView(successView);
57         mc.refDataCount = 0;
58         
59         HttpServletRequest JavaDoc request = new MockHttpServletRequest("GET", "/welcome.html");
60         HttpServletResponse JavaDoc response = new MockHttpServletResponse();
61         ModelAndView mv = mc.handleRequest(request, response);
62         assertTrue("returned correct view name", mv.getViewName().equals(formView));
63         
64         assertTrue("refDataCount == 1", mc.refDataCount == 1);
65         
66         TestBean person = (TestBean) mv.getModel().get(mc.getCommandName());
67         int[] numbers = (int[]) mv.getModel().get(mc.NUMBERS_ATT);
68         assertTrue("model is non null", person != null);
69         assertTrue("numbers is non null", numbers != null);
70     }
71
72     public void testReferenceDataOnResubmit() throws Exception JavaDoc {
73         String JavaDoc formView = "f";
74         String JavaDoc successView = "s";
75         
76         RefController mc = new RefController();
77         mc.setFormView(formView);
78         mc.setCommandName("tb");
79         mc.setSuccessView(successView);
80         mc.refDataCount = 0;
81         
82         MockHttpServletRequest request = new MockHttpServletRequest("POST", "/welcome.html");
83         request.addParameter("age", "23x");
84         HttpServletResponse JavaDoc response = new MockHttpServletResponse();
85         ModelAndView mv = mc.handleRequest(request, response);
86         assertTrue("returned correct view name", mv.getViewName().equals(formView));
87         assertTrue("has errors", mv.getModel().get(BindException.ERROR_KEY_PREFIX + mc.getCommandName()) != null);
88         
89         assertTrue("refDataCount == 1", mc.refDataCount == 1);
90         
91         TestBean person = (TestBean) mv.getModel().get(mc.getCommandName());
92         int[] numbers = (int[]) mv.getModel().get(mc.NUMBERS_ATT);
93         assertTrue("model is non null", person != null);
94         assertTrue("numbers is non null", numbers != null);
95     }
96
97     public void testForm() throws Exception JavaDoc {
98         String JavaDoc formView = "f";
99         String JavaDoc successView = "s";
100         
101         TestController mc = new TestController();
102         mc.setFormView(formView);
103         mc.setSuccessView(successView);
104         
105         MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome.html");
106         request.addParameter("name", "rod");
107         HttpServletResponse JavaDoc response = new MockHttpServletResponse();
108         ModelAndView mv = mc.handleRequest(request, response);
109         assertTrue("returned correct view name", mv.getViewName().equals(formView));
110         
111         TestBean person = (TestBean) mv.getModel().get(TestController.BEAN_NAME);
112         assertTrue("model is non null", person != null);
113         assertTrue("bean age default ok", person.getAge() == TestController.DEFAULT_AGE);
114         assertTrue("name not set", person.getName() == null);
115     }
116
117     public void testBindOnNewForm() throws Exception JavaDoc {
118         String JavaDoc formView = "f";
119         String JavaDoc successView = "s";
120
121         TestController mc = new TestController();
122         mc.setFormView(formView);
123         mc.setSuccessView(successView);
124         mc.setBindOnNewForm(true);
125
126         MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome.html");
127         request.addParameter("name", "rod");
128         HttpServletResponse JavaDoc response = new MockHttpServletResponse();
129         ModelAndView mv = mc.handleRequest(request, response);
130         assertTrue("returned correct view name", mv.getViewName().equals(formView));
131
132         TestBean person = (TestBean) mv.getModel().get(TestController.BEAN_NAME);
133         assertTrue("model is non null", person != null);
134         assertTrue("bean age default ok", person.getAge() == TestController.DEFAULT_AGE);
135         assertTrue("name set", "rod".equals(person.getName()));
136     }
137
138     public void testSubmitWithoutErrors() throws Exception JavaDoc {
139         String JavaDoc formView = "f";
140         String JavaDoc successView = "s";
141         
142         TestController mc = new TestController();
143         mc.setFormView(formView);
144         mc.setSuccessView(successView);
145         
146         String JavaDoc name = "Rod";
147         int age = 32;
148
149         MockHttpServletRequest request = new MockHttpServletRequest("POST", "/welcome.html");
150         request.addParameter("name", name);
151         request.addParameter("age", "" + age);
152         HttpServletResponse JavaDoc response = new MockHttpServletResponse();
153         ModelAndView mv = mc.handleRequest(request, response);
154
155         assertEquals("returned correct view name", successView, mv.getViewName());
156         TestBean person = (TestBean) mv.getModel().get(TestController.BEAN_NAME);
157         Errors errors = (Errors) mv.getModel().get(BindException.ERROR_KEY_PREFIX + TestController.BEAN_NAME);
158         assertTrue("model is non null", person != null);
159         assertTrue("errors is non null", errors != null);
160         assertTrue("bean name bound ok", person.getName().equals(name));
161         assertTrue("bean age bound ok", person.getAge() == age);
162     }
163     
164     public void testSubmitWithoutValidation() throws Exception JavaDoc {
165         String JavaDoc formView = "f";
166         String JavaDoc successView = "s";
167
168         TestController mc = new TestController();
169         mc.setFormView(formView);
170         mc.setSuccessView(successView);
171
172         String JavaDoc name = "Rod";
173         int age = 32;
174
175         MockHttpServletRequest request = new MockHttpServletRequest("POST", "/welcome.html");
176         request.addParameter("name", name);
177         request.addParameter("age", "" + age);
178         request.addParameter("formChange", "true");
179         HttpServletResponse JavaDoc response = new MockHttpServletResponse();
180         ModelAndView mv = mc.handleRequest(request, response);
181
182         assertEquals("returned correct view name", formView, mv.getViewName());
183         TestBean person = (TestBean) mv.getModel().get(TestController.BEAN_NAME);
184         Errors errors = (Errors) mv.getModel().get(BindException.ERROR_KEY_PREFIX + TestController.BEAN_NAME);
185         assertTrue("model is non null", person != null);
186         assertTrue("errors is non null", errors != null);
187         assertTrue("bean name bound ok", person.getName().equals(name));
188         assertTrue("bean age bound ok", person.getAge() == age);
189     }
190
191     public void testSubmitWithCustomOnSubmit() throws Exception JavaDoc {
192         String JavaDoc formView = "f";
193
194         TestControllerWithCustomOnSubmit mc = new TestControllerWithCustomOnSubmit();
195         mc.setFormView(formView);
196
197         String JavaDoc name = "Rod";
198         int age = 32;
199
200         MockHttpServletRequest request = new MockHttpServletRequest("POST", "/welcome.html");
201         request.addParameter("name", name);
202         request.addParameter("age", "" + age);
203         HttpServletResponse JavaDoc response = new MockHttpServletResponse();
204         ModelAndView mv = mc.handleRequest(request, response);
205         assertEquals("returned correct view name", "mySuccess", mv.getViewName());
206         assertTrue("no model", mv.getModel().isEmpty());
207     }
208
209     public void testSubmitPassedByValidator() throws Exception JavaDoc {
210         String JavaDoc formView = "f";
211         String JavaDoc successView = "s";
212         
213         TestController mc = new TestController();
214         mc.setFormView(formView);
215         mc.setSuccessView(successView);
216         mc.setValidator(new TestValidator());
217         
218         String JavaDoc name = "Roderick Johnson";
219         int age = 32;
220
221         MockHttpServletRequest request = new MockHttpServletRequest("POST", "/welcome.html");
222         request.addParameter("name", name);
223         request.addParameter("age", "" + age);
224         HttpServletResponse JavaDoc response = new MockHttpServletResponse();
225         ModelAndView mv = mc.handleRequest(request, response);
226         assertTrue("returned correct view name: expected '" + successView + "', not '" + mv.getViewName() + "'",
227             mv.getViewName().equals(successView));
228         
229         TestBean person = (TestBean) mv.getModel().get(TestController.BEAN_NAME);
230         assertTrue("model is non null", person != null);
231         assertTrue("bean name bound ok", person.getName().equals(name));
232         assertTrue("bean age bound ok", person.getAge() == age);
233     }
234     
235     public void testSubmit1Mismatch() throws Exception JavaDoc {
236         String JavaDoc formView = "fred";
237         String JavaDoc successView = "tony";
238         
239         TestController mc = new TestController();
240         mc.setFormView(formView);
241         mc.setSuccessView(successView);
242         
243         String JavaDoc name = "Rod";
244         String JavaDoc age = "xxx";
245
246         MockHttpServletRequest request = new MockHttpServletRequest("POST", "/foo.html");
247         request.addParameter("name", name);
248         request.addParameter("age", "" + age);
249         HttpServletResponse JavaDoc response = new MockHttpServletResponse();
250         ModelAndView mv = mc.handleRequest(request, response);
251         assertTrue("returned correct view name: expected '" + formView + "', not '" + mv.getViewName() + "'",
252         mv.getViewName().equals(formView));
253         
254         TestBean person = (TestBean) mv.getModel().get(mc.getCommandName());
255         assertTrue("model is non null", person != null);
256         assertTrue("bean name bound ok", person.getName().equals(name));
257         assertTrue("bean age is default", person.getAge() == TestController.DEFAULT_AGE);
258         Errors errors = (Errors) mv.getModel().get(BindException.ERROR_KEY_PREFIX + mc.getCommandName());
259         assertTrue("errors returned in model", errors != null);
260         assertTrue("One error", errors.getErrorCount() == 1);
261         FieldError fe = errors.getFieldError("age");
262         assertTrue("Saved invalid value", fe.getRejectedValue().equals(age));
263         assertTrue("Correct field", fe.getField().equals("age"));
264     }
265     
266     public void testSubmit1Mismatch1Invalidated() throws Exception JavaDoc {
267         String JavaDoc formView = "fred";
268         String JavaDoc successView = "tony";
269         
270         TestController mc = new TestController();
271         mc.setFormView(formView);
272         mc.setSuccessView(successView);
273         mc.setValidators(new Validator[] {new TestValidator(), new TestValidator2()});
274
275         String JavaDoc name = "Rod";
276         // will be rejected
277
String JavaDoc age = "xxx";
278         
279         MockHttpServletRequest request = new MockHttpServletRequest("POST", "/foo.html");
280         request.addParameter("name", name);
281         request.addParameter("age", "" + age);
282         HttpServletResponse JavaDoc response = new MockHttpServletResponse();
283         ModelAndView mv = mc.handleRequest(request, response);
284         assertTrue("returned correct view name: expected '" + formView + "', not '" + mv.getViewName() + "'",
285         mv.getViewName().equals(formView));
286         
287         TestBean person = (TestBean) mv.getModel().get(TestController.BEAN_NAME);
288         assertTrue("model is non null", person != null);
289         
290         // yes, but it was rejected after binding by the validator
291
assertTrue("bean name bound ok", person.getName().equals(name));
292         assertTrue("bean age is default", person.getAge() == TestController.DEFAULT_AGE);
293         Errors errors = (Errors) mv.getModel().get(BindException.ERROR_KEY_PREFIX + mc.getCommandName());
294         assertTrue("errors returned in model", errors != null);
295         assertTrue("3 errors", errors.getErrorCount() == 3);
296         FieldError fe = errors.getFieldError("age");
297         assertTrue("Saved invalid value", fe.getRejectedValue().equals(age));
298         assertTrue("Correct field", fe.getField().equals("age"));
299         
300         // raised by first validator
301
fe = errors.getFieldError("name");
302         assertTrue("Saved invalid value", fe.getRejectedValue().equals(name));
303         assertTrue("Correct field", fe.getField().equals("name"));
304         assertTrue("Correct validation code: expected '" +TestValidator.TOOSHORT + "', not '"
305         + fe.getCode() + "'", fe.getCode().equals(TestValidator.TOOSHORT));
306
307         // raised by second validator
308
ObjectError oe = errors.getGlobalError();
309         assertEquals("test", oe.getCode());
310         assertEquals("testmessage", oe.getDefaultMessage());
311     }
312
313     public void testSessionController() throws Exception JavaDoc {
314         String JavaDoc formView = "f";
315         String JavaDoc successView = "s";
316
317         TestController mc = new TestController();
318         mc.setFormView(formView);
319         mc.setSuccessView(successView);
320         mc.setSessionForm(true);
321
322         // first request: GET form
323
HttpServletRequest JavaDoc request1 = new MockHttpServletRequest("GET", "/welcome.html");
324         HttpServletResponse JavaDoc response1 = new MockHttpServletResponse();
325         ModelAndView mv1 = mc.handleRequest(request1, response1);
326         assertTrue("returned correct view name", mv1.getViewName().equals(formView));
327         TestBean person = (TestBean) mv1.getModel().get(TestController.BEAN_NAME);
328         assertTrue("model is non null", person != null);
329         assertTrue("Bean age default ok", person.getAge() == TestController.DEFAULT_AGE);
330
331         // second request, using same session: POST submit
332
MockHttpServletRequest request2 = new MockHttpServletRequest("POST", "/welcome.html");
333         request2.setSession(request1.getSession(false));
334         HttpServletResponse JavaDoc response2 = new MockHttpServletResponse();
335         ModelAndView mv2 = mc.handleRequest(request2, response2);
336         assertTrue("returned correct view name", mv2.getViewName().equals(successView));
337         TestBean person2 = (TestBean) mv2.getModel().get(TestController.BEAN_NAME);
338         assertTrue("model is same object", person == person2);
339     }
340
341     public void testDefaultInvalidSubmit() throws Exception JavaDoc {
342         String JavaDoc formView = "f";
343         String JavaDoc successView = "s";
344
345         TestController mc = new TestController();
346         mc.setFormView(formView);
347         mc.setSuccessView(successView);
348         mc.setSessionForm(true);
349
350         // invalid request: POST submit
351
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/welcome.html");
352         HttpServletResponse JavaDoc response = new MockHttpServletResponse();
353         ModelAndView mv = mc.handleRequest(request, response);
354         assertTrue("returned correct view name", mv.getViewName().equals(successView));
355         TestBean person = (TestBean) mv.getModel().get(TestController.BEAN_NAME);
356         assertTrue("model is non null", person != null);
357     }
358
359     public void testSpecialInvalidSubmit() throws Exception JavaDoc {
360         String JavaDoc formView = "f";
361         String JavaDoc successView = "s";
362
363         TestController mc = new TestController() {
364             protected ModelAndView handleInvalidSubmit(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
365                 throws ServletException JavaDoc, IOException JavaDoc {
366                 throw new ServletException JavaDoc("invalid submit");
367             }
368         };
369         mc.setFormView(formView);
370         mc.setSuccessView(successView);
371         mc.setSessionForm(true);
372
373         // invalid request: POST submit
374
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/welcome.html");
375         HttpServletResponse JavaDoc response = new MockHttpServletResponse();
376         try {
377             mc.handleRequest(request, response);
378             fail("Should have thrown ServletException");
379         }
380         catch (ServletException JavaDoc ex) {
381             // expected
382
}
383     }
384
385     public void testSubmitWithIndexedProperties() throws Exception JavaDoc {
386         String JavaDoc formView = "fred";
387         String JavaDoc successView = "tony";
388
389         SimpleFormController mc = new SimpleFormController();
390         mc.setCommandClass(IndexedTestBean.class);
391         mc.setFormView(formView);
392         mc.setSuccessView(successView);
393
394         MockHttpServletRequest request = new MockHttpServletRequest("POST", "/foo.html");
395         request.addParameter("array[0].name", "name3");
396         request.addParameter("array[1].age", "name2");
397         request.addParameter("list[0].name", "name1");
398         request.addParameter("list[1].age", "name0");
399         request.addParameter("list[2]", "listobj");
400         request.addParameter("map[key1]", "mapobj1");
401         request.addParameter("map[key3]", "mapobj2");
402         HttpServletResponse JavaDoc response = new MockHttpServletResponse();
403         ModelAndView mv = mc.handleRequest(request, response);
404         assertTrue("returned correct view name: expected '" + formView + "', not '" + mv.getViewName() + "'",
405         mv.getViewName().equals(formView));
406
407         IndexedTestBean bean = (IndexedTestBean) mv.getModel().get(mc.getCommandName());
408         assertTrue("model is non null", bean != null);
409         assertEquals("name3", bean.getArray()[0].getName());
410         assertEquals("name1", ((TestBean) bean.getList().get(0)).getName());
411         Errors errors = (Errors) mv.getModel().get(BindException.ERROR_KEY_PREFIX + mc.getCommandName());
412         assertTrue("errors returned in model", errors != null);
413         assertTrue("2 errors", errors.getErrorCount() == 2);
414         FieldError fe1 = errors.getFieldError("array[1].age");
415         assertTrue("Saved invalid value", fe1.getRejectedValue().equals("name2"));
416         assertTrue("Correct field", fe1.getField().equals("array[1].age"));
417         FieldError fe2 = errors.getFieldError("list[1].age");
418         assertTrue("Saved invalid value", fe2.getRejectedValue().equals("name0"));
419         assertTrue("Correct field", fe2.getField().equals("list[1].age"));
420
421         assertEquals("listobj", bean.getList().get(2));
422         assertEquals("mapobj1", bean.getMap().get("key1"));
423         assertEquals("mapobj2", bean.getMap().get("key3"));
424     }
425
426     public void testFormChangeRequest() throws Exception JavaDoc {
427         String JavaDoc formView = "fred";
428         String JavaDoc successView = "tony";
429
430         TestController mc = new TestController() {
431             protected boolean isFormChangeRequest(HttpServletRequest JavaDoc request) {
432                 return (request.getParameter("formChange") != null);
433             }
434         };
435         mc.setFormView(formView);
436         mc.setSuccessView(successView);
437
438         MockHttpServletRequest request = new MockHttpServletRequest("POST", "/foo.html");
439         request.addParameter("name", "Rod");
440         request.addParameter("age", "99");
441         request.addParameter("formChange", "true");
442         HttpServletResponse JavaDoc response = new MockHttpServletResponse();
443         ModelAndView mv = mc.handleRequest(request, response);
444         assertTrue("returned correct view name: expected '" + formView + "', not '" + mv.getViewName() + "'",
445         mv.getViewName().equals(formView));
446
447         TestBean person = (TestBean) mv.getModel().get(mc.getCommandName());
448         assertTrue("model is non null", person != null);
449         assertTrue("bean name bound ok", person.getName().equals("Rod"));
450         assertTrue("bean age is 99", person.getAge() == 99);
451         Errors errors = (Errors) mv.getModel().get(BindException.ERROR_KEY_PREFIX + mc.getCommandName());
452         assertTrue("errors returned in model", errors != null);
453         assertTrue("No errors", errors.getErrorCount() == 0);
454     }
455
456     public void testFormControllerInWebApplicationContext() {
457         StaticWebApplicationContext ctx = new StaticWebApplicationContext();
458         ctx.setServletContext(new MockServletContext());
459         RefController mc = new RefController();
460         mc.setApplicationContext(ctx);
461         try {
462             mc.invokeWebSpecificStuff();
463         }
464         catch (IllegalStateException JavaDoc ex) {
465             fail("Shouldn't have thrown exception: " + ex.getMessage());
466         }
467     }
468
469     public void testFormControllerInNonWebApplicationContext() {
470         StaticApplicationContext ctx = new StaticApplicationContext();
471         RefController mc = new RefController();
472         mc.setApplicationContext(ctx);
473         try {
474             mc.invokeWebSpecificStuff();
475             fail("Should have thrown IllegalStateException");
476         }
477         catch (IllegalStateException JavaDoc ex) {
478             // expected
479
}
480     }
481
482
483     private static class TestValidator implements Validator {
484
485         public static String JavaDoc TOOSHORT = "tooshort";
486
487         public boolean supports(Class JavaDoc clazz) { return true; }
488
489         public void validate(Object JavaDoc obj, Errors errors) {
490             TestBean tb = (TestBean) obj;
491             if (tb.getName() == null || "".equals(tb.getName()))
492                 errors.rejectValue("name", "needname", null, "need name");
493             else if (tb.getName().length() < 5)
494                 errors.rejectValue("name", TOOSHORT, null, "need full name");
495         }
496     }
497
498
499     private static class TestValidator2 implements Validator {
500
501         public static String JavaDoc TOOSHORT = "tooshort";
502
503         public boolean supports(Class JavaDoc clazz) { return true; }
504
505         public void validate(Object JavaDoc obj, Errors errors) {
506             errors.reject("test", "testmessage");
507         }
508     }
509
510
511     private static class TestController extends SimpleFormController {
512
513         public static String JavaDoc BEAN_NAME = "person";
514
515         public static int DEFAULT_AGE = 52;
516
517         public TestController() {
518             setCommandClass(TestBean.class);
519             setCommandName(BEAN_NAME);
520         }
521
522         protected Object JavaDoc formBackingObject(HttpServletRequest JavaDoc request) throws ServletException JavaDoc {
523             TestBean person = new TestBean();
524             person.setAge(DEFAULT_AGE);
525             return person;
526         }
527
528         protected boolean isFormChangeRequest(HttpServletRequest JavaDoc request) {
529             return (request.getParameter("formChange") != null);
530         }
531     }
532
533
534     private static class TestControllerWithCustomOnSubmit extends TestController {
535
536         protected ModelAndView onSubmit(Object JavaDoc command) throws Exception JavaDoc {
537             return new ModelAndView("mySuccess");
538         }
539     }
540
541
542     private static class RefController extends SimpleFormController {
543         
544         final String JavaDoc NUMBERS_ATT = "NUMBERS";
545         
546         static final int[] NUMBERS = { 1, 2, 3, 4 };
547         
548         int refDataCount;
549         
550         public RefController() {
551             setCommandClass(TestBean.class);
552         }
553         
554         protected Map JavaDoc referenceData(HttpServletRequest JavaDoc request) {
555             ++refDataCount;
556             Map JavaDoc m = new HashMap JavaDoc();
557             m.put(NUMBERS_ATT, NUMBERS);
558             return m;
559         }
560
561         public void invokeWebSpecificStuff() {
562             getTempDir();
563         }
564     }
565
566 }
567
Popular Tags