001/*
002 * Copyright 2002-2020 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.web.bind.support;
018
019import javax.servlet.http.HttpServletRequest;
020import javax.servlet.http.Part;
021
022import org.springframework.beans.MutablePropertyValues;
023import org.springframework.lang.Nullable;
024import org.springframework.util.LinkedMultiValueMap;
025import org.springframework.util.MultiValueMap;
026import org.springframework.util.StringUtils;
027import org.springframework.validation.BindException;
028import org.springframework.web.bind.WebDataBinder;
029import org.springframework.web.context.request.NativeWebRequest;
030import org.springframework.web.context.request.WebRequest;
031import org.springframework.web.multipart.MultipartException;
032import org.springframework.web.multipart.MultipartRequest;
033
034/**
035 * Special {@link org.springframework.validation.DataBinder} to perform data binding
036 * from web request parameters to JavaBeans, including support for multipart files.
037 *
038 * <p>See the DataBinder/WebDataBinder superclasses for customization options,
039 * which include specifying allowed/required fields, and registering custom
040 * property editors.
041 *
042 * <p>Can also used for manual data binding in custom web controllers or interceptors
043 * that build on Spring's {@link org.springframework.web.context.request.WebRequest}
044 * abstraction: e.g. in a {@link org.springframework.web.context.request.WebRequestInterceptor}
045 * implementation. Simply instantiate a WebRequestDataBinder for each binding
046 * process, and invoke {@code bind} with the current WebRequest as argument:
047 *
048 * <pre class="code">
049 * MyBean myBean = new MyBean();
050 * // apply binder to custom target object
051 * WebRequestDataBinder binder = new WebRequestDataBinder(myBean);
052 * // register custom editors, if desired
053 * binder.registerCustomEditor(...);
054 * // trigger actual binding of request parameters
055 * binder.bind(request);
056 * // optionally evaluate binding errors
057 * Errors errors = binder.getErrors();
058 * ...</pre>
059 *
060 * @author Juergen Hoeller
061 * @author Brian Clozel
062 * @since 2.5.2
063 * @see #bind(org.springframework.web.context.request.WebRequest)
064 * @see #registerCustomEditor
065 * @see #setAllowedFields
066 * @see #setRequiredFields
067 * @see #setFieldMarkerPrefix
068 */
069public class WebRequestDataBinder extends WebDataBinder {
070
071        /**
072         * Create a new WebRequestDataBinder instance, with default object name.
073         * @param target the target object to bind onto (or {@code null}
074         * if the binder is just used to convert a plain parameter value)
075         * @see #DEFAULT_OBJECT_NAME
076         */
077        public WebRequestDataBinder(@Nullable Object target) {
078                super(target);
079        }
080
081        /**
082         * Create a new WebRequestDataBinder instance.
083         * @param target the target object to bind onto (or {@code null}
084         * if the binder is just used to convert a plain parameter value)
085         * @param objectName the name of the target object
086         */
087        public WebRequestDataBinder(@Nullable Object target, String objectName) {
088                super(target, objectName);
089        }
090
091
092        /**
093         * Bind the parameters of the given request to this binder's target,
094         * also binding multipart files in case of a multipart request.
095         * <p>This call can create field errors, representing basic binding
096         * errors like a required field (code "required"), or type mismatch
097         * between value and bean property (code "typeMismatch").
098         * <p>Multipart files are bound via their parameter name, just like normal
099         * HTTP parameters: i.e. "uploadedFile" to an "uploadedFile" bean property,
100         * invoking a "setUploadedFile" setter method.
101         * <p>The type of the target property for a multipart file can be Part, MultipartFile,
102         * byte[], or String. The latter two receive the contents of the uploaded file;
103         * all metadata like original file name, content type, etc are lost in those cases.
104         * @param request the request with parameters to bind (can be multipart)
105         * @see org.springframework.web.multipart.MultipartRequest
106         * @see org.springframework.web.multipart.MultipartFile
107         * @see javax.servlet.http.Part
108         * @see #bind(org.springframework.beans.PropertyValues)
109         */
110        public void bind(WebRequest request) {
111                MutablePropertyValues mpvs = new MutablePropertyValues(request.getParameterMap());
112                if (request instanceof NativeWebRequest) {
113                        MultipartRequest multipartRequest = ((NativeWebRequest) request).getNativeRequest(MultipartRequest.class);
114                        if (multipartRequest != null) {
115                                bindMultipart(multipartRequest.getMultiFileMap(), mpvs);
116                        }
117                        else if (isMultipartRequest(request)) {
118                                HttpServletRequest servletRequest = ((NativeWebRequest) request).getNativeRequest(HttpServletRequest.class);
119                                if (servletRequest != null) {
120                                        bindParts(servletRequest, mpvs);
121                                }
122                        }
123                }
124                doBind(mpvs);
125        }
126
127        /**
128         * Check if the request is a multipart request (by checking its Content-Type header).
129         * @param request the request with parameters to bind
130         */
131        private boolean isMultipartRequest(WebRequest request) {
132                String contentType = request.getHeader("Content-Type");
133                return StringUtils.startsWithIgnoreCase(contentType, "multipart/");
134        }
135
136        private void bindParts(HttpServletRequest request, MutablePropertyValues mpvs) {
137                try {
138                        MultiValueMap<String, Part> map = new LinkedMultiValueMap<>();
139                        for (Part part : request.getParts()) {
140                                map.add(part.getName(), part);
141                        }
142                        map.forEach((key, values) -> {
143                                if (values.size() == 1) {
144                                        Part part = values.get(0);
145                                        if (isBindEmptyMultipartFiles() || part.getSize() > 0) {
146                                                mpvs.add(key, part);
147                                        }
148                                }
149                                else {
150                                        mpvs.add(key, values);
151                                }
152                        });
153                }
154                catch (Exception ex) {
155                        throw new MultipartException("Failed to get request parts", ex);
156                }
157        }
158
159        /**
160         * Treats errors as fatal.
161         * <p>Use this method only if it's an error if the input isn't valid.
162         * This might be appropriate if all input is from dropdowns, for example.
163         * @throws BindException if binding errors have been encountered
164         */
165        public void closeNoCatch() throws BindException {
166                if (getBindingResult().hasErrors()) {
167                        throw new BindException(getBindingResult());
168                }
169        }
170
171}