01: // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
02:
03: package jodd.bean.loader;
04:
05: import jodd.bean.BeanUtil;
06: import jodd.servlet.upload.MultipartRequest;
07: import jodd.servlet.upload.FileUpload;
08:
09: /**
10: * Populates java bean from {@link MultipartRequest} objects.
11: */
12: public class MultipartRequestBeanLoader implements BeanLoader {
13:
14: private boolean trim;
15:
16: public MultipartRequestBeanLoader() {
17: }
18:
19: public MultipartRequestBeanLoader(boolean trim) {
20: this .trim = trim;
21: }
22:
23: public static void loadBean(Object bean, Object request,
24: boolean trim) {
25: if (request instanceof MultipartRequest) {
26: MultipartRequest mrequest = (MultipartRequest) request;
27: for (Object o : mrequest.getParameterNames()) {
28: String paramName = (String) o;
29: String[] paramValues = mrequest
30: .getParameterValues(paramName);
31: if (paramValues == null) {
32: continue;
33: }
34: if (paramValues.length == 0) {
35: continue;
36: }
37: if (trim == true) {
38: for (int i = 0; i < paramValues.length; i++) {
39: paramValues[i] = paramValues[i].trim();
40: }
41: }
42: try {
43: if (paramValues.length == 1) {
44: // send just String
45: BeanUtil.setPropertyForced(bean, paramName,
46: paramValues[0]);
47: } else {
48: // send String array
49: BeanUtil.setPropertyForced(bean, paramName,
50: paramValues);
51: }
52: } catch (Exception bex) {
53: // ignore exception
54: }
55: }
56:
57: for (Object o1 : mrequest.getFileParameterNames()) {
58: String paramName = (String) o1;
59: FileUpload[] uf = mrequest.getFiles(paramName);
60: if (uf == null) {
61: continue;
62: }
63: if (uf.length == 0) {
64: continue;
65: }
66: try {
67: if (uf.length == 1) {
68: BeanUtil.setPropertyForcedSilent(bean,
69: paramName, uf[0]);
70: } else {
71: BeanUtil.setPropertyForcedSilent(bean,
72: paramName, uf);
73: }
74: } catch (Exception ex) {
75: // ignore exception
76: }
77: }
78: }
79: }
80:
81: public void load(Object bean, Object request) {
82: loadBean(bean, request, trim);
83: }
84: }
|