KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > bean > loaders > MultipartRequestLoader


1 package jodd.bean.loaders;
2
3 import java.util.Enumeration;
4
5 import jodd.bean.BeanUtil;
6 import jodd.servlet.MultipartRequest;
7 import jodd.servlet.UploadedFile;
8
9 /**
10  * Populates java bean from MultipartRequest objects.
11  * <p>
12  *
13  * Names of requests parameters represents the names of bean properties.
14  * Values of requests parameters represents values of bean properties.
15  * <p>
16  *
17  * By java servlet specifications, parameter values are always String arrays
18  * (String[]). That is how they are sent to BeanUtil.setProperty(),
19  * except in case when this array contains just one String element. In that
20  * case it is sent as a single String.
21  * <p>
22  *
23  * BeanUtil.setProperty() will populate correctly target property.
24  */

25 public class MultipartRequestLoader implements jodd.bean.Loader {
26
27     public void load(Object bean, Object request) {
28         if (request instanceof MultipartRequest) {
29             MultipartRequest mrequest = (MultipartRequest) request;
30             Enumeration paramNames = mrequest.getParameterNames();
31             while (paramNames.hasMoreElements()) {
32                 String paramName = (String) paramNames.nextElement();
33                 String[] paramValues = mrequest.getParameterValues(paramName);
34                 if (paramValues == null) {
35                     continue;
36                 }
37                 if (paramValues.length == 0) {
38                     continue;
39                 }
40                 if (paramValues.length == 1) {
41                     // send just String
42
BeanUtil.setProperty(bean, paramName, paramValues[0]);
43                 } else {
44                     // send String array
45
BeanUtil.setProperty(bean, paramName, paramValues);
46                 }
47             }
48
49             paramNames = mrequest.getUploadedFileNames();
50             while (paramNames.hasMoreElements()) {
51                 String paramName = (String) paramNames.nextElement();
52                 UploadedFile uf = mrequest.getUploadedFile(paramName);
53                 BeanUtil.setProperty(bean, paramName, uf);
54             }
55         }
56         return;
57     }
58 }
59
Popular Tags