Example usage for org.springframework.web.bind WebDataBinder bind

List of usage examples for org.springframework.web.bind WebDataBinder bind

Introduction

In this page you can find the example usage for org.springframework.web.bind WebDataBinder bind.

Prototype

public void bind(PropertyValues pvs) 

Source Link

Document

Bind the given property values to this binder's target.

Usage

From source file:org.opentides.web.processor.FormBindMethodProcessor.java

/**
 * Resolve the argument from the model or if not found instantiate it with
 * its default. The model attribute is then populated with request values 
 * via data binding and validated. If no validation error, the model
 * is retrieved from database and merged with the submitted form.
 *   /*w ww .j av  a  2s.  c o  m*/
 * @throws BindException if data binding and validation result in an error
 * @throws Exception if WebDataBinder initialization fails.
 */
@SuppressWarnings("unchecked")
public final Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest nativeRequest, WebDataBinderFactory binderFactory) throws Exception {

    FormBind annot = parameter.getParameterAnnotation(FormBind.class);
    Class<?> clazz = parameter.getDeclaringClass();
    String name = getName(annot, parameter);
    HttpServletRequest request = (HttpServletRequest) nativeRequest.getNativeRequest();

    Method addForm = CacheUtil.getNewFormBindMethod(clazz);
    Object controller = beanFactory.getBean(parameter.getContainingClass());
    Object target = (addForm != null) ? addForm.invoke(controller, request)
            : BeanUtils.instantiateClass(parameter.getParameterType());
    MutablePropertyValues mpvs = new MutablePropertyValues(nativeRequest.getParameterMap());
    WebDataBinder binder = binderFactory.createBinder(nativeRequest, target, name);
    if (binder.getTarget() != null) {
        binder.bind(mpvs);
        if (binder.getValidator() != null)
            binder.validate();
        if (binder.getBindingResult().hasErrors()) {
            throw new BindException(binder.getBindingResult());
        }
        String method = request.getMethod().toLowerCase();

        // id should be the last segment of the uri
        String uri = request.getRequestURI();
        String sid = uri.substring(uri.lastIndexOf("/") + 1);
        Long id = StringUtil.convertToLong(sid, 0);

        // if target extends BaseEntity and for update, link target to database record
        if (("put".equals(method) || "post".equals(method)) && id > 0
                && BaseEntity.class.isAssignableFrom(parameter.getParameterType())) {
            // now retrieve record from database for updating
            Method updateForm = CacheUtil.getUpdateFormBindMethod(clazz);

            BaseEntity record = null;
            if (updateForm == null) {
                // no annotation, invoke from service
                Method getService = controller.getClass().getMethod("getService");
                if (getService == null) {
                    String message = "Cannot find method with @FormBind with update mode. "
                            + "Also, unable to find service associated to controller."
                            + "Please specify one that retrieves record from database.";
                    throw new InvalidImplementationException(message);
                }
                BaseCrudService<? extends BaseEntity> service = (BaseCrudService<? extends BaseEntity>) getService
                        .invoke(controller);
                record = (BaseEntity) service.load(sid);
            } else {
                // with annotation, invoke annotation
                record = (BaseEntity) updateForm.invoke(controller, sid, request);
            }

            if (record != null) {
                WebDataBinder updateBinder = binderFactory.createBinder(nativeRequest, record, name);
                updateBinder.bind(mpvs);
                mavContainer.addAllAttributes(updateBinder.getBindingResult().getModel());
                return updateBinder.getTarget();
            } else {
                String message = "Unable to find " + parameter.getParameterType().getSimpleName() + " with id="
                        + sid + " for update.";
                throw new DataAccessException(message);
            }
        } else if ("post".equals(method)) {
            mavContainer.addAllAttributes(binder.getBindingResult().getModel());
            return binder.getTarget();
        } else {
            throw new InvalidImplementationException(
                    "@FormBind argument annotation can only be used on POST or PUT methods.");
        }
    }
    mavContainer.addAllAttributes(binder.getBindingResult().getModel());
    return binder.getTarget();
}

From source file:com.trenako.web.infrastructure.SearchRequestArgumentResolver.java

@Override
public Object resolveArgument(MethodParameter param, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

    if (param.getParameterType().equals(SearchRequest.class)) {
        SearchRequest searchRequest = new SearchRequest();

        WebDataBinder webBinder = binderFactory.createBinder(webRequest, searchRequest, "");

        HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
        PropertyValues pvs = new ServletRequestPathVariablesPropertyValues(request);
        webBinder.bind(pvs);
        return searchRequest;
    }/*  www  . j a  va  2  s. c  om*/

    return UNRESOLVED;
}

From source file:org.terasoluna.gfw.web.el.ObjectToMapConverterTest.java

@Test
public void testConvert0_SimpleJavaBean() throws Exception {
    Map<String, String> map = converter.convert(new SearchUserForm0("yamada", 20));
    assertThat(map.size(), is(2));/*from w  w w  .j  a v  a  2 s.  c  om*/
    assertThat(map, hasEntry("name", "yamada"));
    assertThat(map, hasEntry("age", "20"));

    // check reverse conversion
    SearchUserForm0 form = new SearchUserForm0();
    WebDataBinder binder = new WebDataBinder(form);
    binder.bind(new MutablePropertyValues(map));
    assertThat(form.getName(), is("yamada"));
    assertThat(form.getAge(), is(20));
}

From source file:org.terasoluna.gfw.web.el.ObjectToMapConverterTest.java

@Test
public void testConvert1_NestedJavaBean() throws Exception {
    Map<String, String> map = converter
            .convert(new SearchUserForm1(new SearchUserCriteriaForm1("yamada", 20), true));
    assertThat(map.size(), is(3));//  w  w w.  j  ava2  s .  c  o m
    assertThat(map, hasEntry("criteria.name", "yamada"));
    assertThat(map, hasEntry("criteria.age", "20"));
    assertThat(map, hasEntry("rememberCriteria", "true"));

    // check reverse conversion
    SearchUserForm1 form = new SearchUserForm1();
    WebDataBinder binder = new WebDataBinder(form);
    binder.bind(new MutablePropertyValues(map));
    assertThat(form.getCriteria(), is(notNullValue()));
    assertThat(form.getCriteria().getName(), is("yamada"));
    assertThat(form.getCriteria().getAge(), is(20));
    assertThat(form.isRememberCriteria(), is(true));
}

From source file:org.zht.framework.web.bind.resolver.FormModelMethodArgumentResolver.java

/**
 * {@inheritDoc}//from   w  w w  . j a  v a2 s.c o  m
 * <p>Downcast {@link org.springframework.web.bind.WebDataBinder} to {@link org.springframework.web.bind.ServletRequestDataBinder} before binding.
 *
 * @throws Exception
 * @see org.springframework.web.servlet.mvc.method.annotation.ServletRequestDataBinderFactory
 */

protected void bindRequestParameters(ModelAndViewContainer mavContainer, WebDataBinderFactory binderFactory,
        WebDataBinder binder, NativeWebRequest request, MethodParameter parameter) throws Exception {

    Map<String, Boolean> hasProcessedPrefixMap = new HashMap<String, Boolean>();

    Class<?> targetType = binder.getTarget().getClass();
    ServletRequest servletRequest = prepareServletRequest(binder.getTarget(), request, parameter);
    WebDataBinder simpleBinder = binderFactory.createBinder(request, null, null);

    if (Collection.class.isAssignableFrom(targetType)) {//bind collection or array

        Type type = parameter.getGenericParameterType();
        Class<?> componentType = Object.class;

        Collection target = (Collection) binder.getTarget();

        List targetList = new ArrayList(target);

        if (type instanceof ParameterizedType) {
            componentType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
        }

        if (parameter.getParameterType().isArray()) {
            componentType = parameter.getParameterType().getComponentType();
        }

        for (Object key : servletRequest.getParameterMap().keySet()) {
            String prefixName = getPrefixName((String) key);

            //?prefix ??
            if (hasProcessedPrefixMap.containsKey(prefixName)) {
                continue;
            } else {
                hasProcessedPrefixMap.put(prefixName, Boolean.TRUE);
            }

            if (isSimpleComponent(prefixName)) { //bind simple type
                Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest,
                        prefixName);
                Matcher matcher = INDEX_PATTERN.matcher(prefixName);
                if (!matcher.matches()) { //? array=1&array=2
                    for (Object value : paramValues.values()) {
                        targetList.add(simpleBinder.convertIfNecessary(value, componentType));
                    }
                } else { //? array[0]=1&array[1]=2
                    int index = Integer.valueOf(matcher.group(1));

                    if (targetList.size() <= index) {
                        growCollectionIfNecessary(targetList, index);
                    }
                    targetList.set(index, simpleBinder.convertIfNecessary(paramValues.values(), componentType));
                }
            } else { //? votes[1].title=votes[1].title&votes[0].title=votes[0].title&votes[0].id=0&votes[1].id=1
                Object component = null;
                //? ?????
                Matcher matcher = INDEX_PATTERN.matcher(prefixName);
                if (!matcher.matches()) {
                    throw new IllegalArgumentException("bind collection error, need integer index, key:" + key);
                }
                int index = Integer.valueOf(matcher.group(1));
                if (targetList.size() <= index) {
                    growCollectionIfNecessary(targetList, index);
                }
                Iterator iterator = targetList.iterator();
                for (int i = 0; i < index; i++) {
                    iterator.next();
                }
                component = iterator.next();

                if (component == null) {
                    component = BeanUtils.instantiate(componentType);
                }

                WebDataBinder componentBinder = binderFactory.createBinder(request, component, null);
                component = componentBinder.getTarget();

                if (component != null) {
                    ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(
                            servletRequest, prefixName, "");
                    componentBinder.bind(pvs);
                    validateIfApplicable(componentBinder, parameter);
                    if (componentBinder.getBindingResult().hasErrors()) {
                        if (isBindExceptionRequired(componentBinder, parameter)) {
                            throw new BindException(componentBinder.getBindingResult());
                        }
                    }
                    targetList.set(index, component);
                }
            }
            target.clear();
            target.addAll(targetList);
        }
    } else if (MapWapper.class.isAssignableFrom(targetType)) {

        Type type = parameter.getGenericParameterType();
        Class<?> keyType = Object.class;
        Class<?> valueType = Object.class;

        if (type instanceof ParameterizedType) {
            keyType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
            valueType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[1];
        }

        MapWapper mapWapper = ((MapWapper) binder.getTarget());
        Map target = mapWapper.getInnerMap();
        if (target == null) {
            target = new HashMap();
            mapWapper.setInnerMap(target);
        }

        for (Object key : servletRequest.getParameterMap().keySet()) {
            String prefixName = getPrefixName((String) key);

            //?prefix ??
            if (hasProcessedPrefixMap.containsKey(prefixName)) {
                continue;
            } else {
                hasProcessedPrefixMap.put(prefixName, Boolean.TRUE);
            }

            Object keyValue = simpleBinder.convertIfNecessary(getMapKey(prefixName), keyType);

            if (isSimpleComponent(prefixName)) { //bind simple type
                Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest,
                        prefixName);

                for (Object value : paramValues.values()) {
                    target.put(keyValue, simpleBinder.convertIfNecessary(value, valueType));
                }
            } else {

                Object component = target.get(keyValue);
                if (component == null) {
                    component = BeanUtils.instantiate(valueType);
                }

                WebDataBinder componentBinder = binderFactory.createBinder(request, component, null);
                component = componentBinder.getTarget();

                if (component != null) {
                    ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(
                            servletRequest, prefixName, "");
                    componentBinder.bind(pvs);

                    validateComponent(componentBinder, parameter);

                    target.put(keyValue, component);
                }
            }
        }
    } else {//bind model
        ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder;
        servletBinder.bind(servletRequest);
    }
}

From source file:org.terasoluna.gfw.web.el.ObjectToMapConverterTest.java

@Test
public void testConvert2_ListOfJavaBean() throws Exception {
    Map<String, String> map = converter.convert(new BatchUpdateUserForm2(
            Arrays.asList(new UpdateUserCriteriaForm2("yamada", 20), new UpdateUserCriteriaForm2("tanaka", 50)),
            LogicalOperator2.AND));//w ww .  j a  v a  2s .  co  m
    assertThat(map.size(), is(5));
    assertThat(map, hasEntry("criteria[0].name", "yamada"));
    assertThat(map, hasEntry("criteria[0].age", "20"));
    assertThat(map, hasEntry("criteria[1].name", "tanaka"));
    assertThat(map, hasEntry("criteria[1].age", "50"));
    assertThat(map, hasEntry("operator", "AND"));

    // check reverse conversion
    BatchUpdateUserForm2 form = new BatchUpdateUserForm2();
    WebDataBinder binder = new WebDataBinder(form);
    binder.bind(new MutablePropertyValues(map));
    assertThat(form.getCriteria(), is(notNullValue()));
    assertThat(form.getCriteria().size(), is(2));
    assertThat(form.getCriteria().get(0).getName(), is("yamada"));
    assertThat(form.getCriteria().get(0).getAge(), is(20));
    assertThat(form.getCriteria().get(1).getName(), is("tanaka"));
    assertThat(form.getCriteria().get(1).getAge(), is(50));
    assertThat(form.getOperator(), is(LogicalOperator2.AND));
}

From source file:org.terasoluna.gfw.web.el.ObjectToMapConverterTest.java

@Test
public void testConvert4_MapOfJavaBean() throws Exception {
    Map<String, String> map = converter.convert(new SearchForm4(new LinkedHashMap<String, String>() {
        {//w  w  w  .  j  ava  2 s .  c o  m
            put("aaa", "111");
            put("bbb", "222");
            put("ccc", "333");
        }
    }));
    assertThat(map.size(), is(3));
    assertThat(map, hasEntry("etc[aaa]", "111"));
    assertThat(map, hasEntry("etc[bbb]", "222"));
    assertThat(map, hasEntry("etc[ccc]", "333"));

    // check reverse conversion
    SearchForm4 form = new SearchForm4();
    WebDataBinder binder = new WebDataBinder(form);
    binder.bind(new MutablePropertyValues(map));
    assertThat(form.getEtc(), is(notNullValue()));
    assertThat(form.getEtc().size(), is(3));
    assertThat(form.getEtc(), hasEntry("aaa", "111"));
    assertThat(form.getEtc(), hasEntry("bbb", "222"));
    assertThat(form.getEtc(), hasEntry("ccc", "333"));
}

From source file:org.terasoluna.gfw.web.el.ObjectToMapConverterTest.java

@Test
public void testConvert3_SimpleJavaBeanAndListOfJavaBean() throws Exception {
    Map<String, String> map = converter
            .convert(new SearchAndBatchUpdateUserForm3(new SearchUserCriteriaForm3("suzuki", 30),
                    Arrays.asList(new User3("yamada", 20), new User3("tanaka", 50))));
    assertThat(map.size(), is(6));/*from   ww w . j a  v  a2s. c o m*/
    assertThat(map, hasEntry("criteria.name", "suzuki"));
    assertThat(map, hasEntry("criteria.age", "30"));
    assertThat(map, hasEntry("users[0].name", "yamada"));
    assertThat(map, hasEntry("users[0].age", "20"));
    assertThat(map, hasEntry("users[1].name", "tanaka"));
    assertThat(map, hasEntry("users[1].age", "50"));

    // check reverse conversion
    SearchAndBatchUpdateUserForm3 form = new SearchAndBatchUpdateUserForm3();
    WebDataBinder binder = new WebDataBinder(form);
    binder.bind(new MutablePropertyValues(map));
    assertThat(form.getCriteria(), is(notNullValue()));
    assertThat(form.getCriteria().getName(), is("suzuki"));
    assertThat(form.getCriteria().getAge(), is(30));
    assertThat(form.getUsers(), is(notNullValue()));
    assertThat(form.getUsers().size(), is(2));
    assertThat(form.getUsers().get(0).getName(), is("yamada"));
    assertThat(form.getUsers().get(0).getAge(), is(20));
    assertThat(form.getUsers().get(1).getName(), is("tanaka"));
    assertThat(form.getUsers().get(1).getAge(), is(50));
}

From source file:org.terasoluna.gfw.web.el.ObjectToMapConverterTest.java

@Test
public void testConvert5_at_DateTimeFormat() throws Exception {
    LocalDate date1 = new LocalDate(2015, 4, 1);
    LocalDate localDate1 = new LocalDate(2015, 6, 10);
    LocalDate date2 = new LocalDate(2015, 5, 1);
    LocalDate localDate2 = new LocalDate(2015, 7, 10);

    Map<String, String> map = converter
            .convert(new DateForm5(date1.toDate(), localDate1, new DateFormItem5(date2.toDate(), localDate2)));
    assertThat(map.size(), is(4));// w  w w.  j  a  v a  2  s  . co  m
    assertThat(map, hasEntry("date", "2015-04-01"));
    assertThat(map, hasEntry("localDate", "2015-06-10"));
    assertThat(map, hasEntry("item.date", "2015-05-01"));
    assertThat(map, hasEntry("item.localDate", "2015-07-10"));

    DateForm5 form = new DateForm5();
    WebDataBinder binder = new WebDataBinder(form);
    binder.setConversionService(new DefaultFormattingConversionService());
    binder.bind(new MutablePropertyValues(map));
    assertThat(form.getDate(), is(date1.toDate()));
    assertThat(form.getLocalDate(), is(localDate1));
    assertThat(form.getItem().getDate(), is(date2.toDate()));
    assertThat(form.getItem().getLocalDate(), is(localDate2));
}

From source file:org.terasoluna.gfw.web.el.ObjectToMapConverterTest.java

@Test
public void testConvert6_Array() throws Exception {
    Map<String, String> map = converter.convert(new ArrayForm6(new int[] { 1, 2, 3 }, new double[] { 1.1, 1.2 },
            new byte[] { 4, 5, 6 }, new String[] { "a", "b", "c" }, new ArrayFormItem6(new int[] { 11, 12, 13 },
                    new double[] { 11.1, 11.2 }, new byte[] { 14, 15, 16 }, new String[] { "d", "e", "f" })));
    assertThat(map.size(), is(22));/* w w  w.  j  a va  2 s. co  m*/
    assertThat(map, hasEntry("array1[0]", "1"));
    assertThat(map, hasEntry("array1[1]", "2"));
    assertThat(map, hasEntry("array1[2]", "3"));
    assertThat(map, hasEntry("array2[0]", "1.1"));
    assertThat(map, hasEntry("array2[1]", "1.2"));
    assertThat(map, hasEntry("array3[0]", "4"));
    assertThat(map, hasEntry("array3[1]", "5"));
    assertThat(map, hasEntry("array3[2]", "6"));
    assertThat(map, hasEntry("array4[0]", "a"));
    assertThat(map, hasEntry("array4[1]", "b"));
    assertThat(map, hasEntry("array4[2]", "c"));
    assertThat(map, hasEntry("item.array1[0]", "11"));
    assertThat(map, hasEntry("item.array1[1]", "12"));
    assertThat(map, hasEntry("item.array1[2]", "13"));
    assertThat(map, hasEntry("item.array2[0]", "11.1"));
    assertThat(map, hasEntry("item.array2[1]", "11.2"));
    assertThat(map, hasEntry("item.array3[0]", "14"));
    assertThat(map, hasEntry("item.array3[1]", "15"));
    assertThat(map, hasEntry("item.array3[2]", "16"));
    assertThat(map, hasEntry("item.array4[0]", "d"));
    assertThat(map, hasEntry("item.array4[1]", "e"));
    assertThat(map, hasEntry("item.array4[2]", "f"));

    ArrayForm6 form = new ArrayForm6();
    WebDataBinder binder = new WebDataBinder(form);
    binder.setConversionService(new DefaultFormattingConversionService());
    binder.bind(new MutablePropertyValues(map));
    assertThat(form.getArray1().length, is(3));
    assertThat(form.getArray1()[0], is(1));
    assertThat(form.getArray1()[1], is(2));
    assertThat(form.getArray1()[2], is(3));
    assertThat(form.getArray2().length, is(2));
    assertThat(form.getArray2()[0], is(1.1));
    assertThat(form.getArray2()[1], is(1.2));
    assertThat(form.getArray3().length, is(3));
    assertThat(form.getArray3()[0], is((byte) 4));
    assertThat(form.getArray3()[1], is((byte) 5));
    assertThat(form.getArray3()[2], is((byte) 6));
    assertThat(form.getArray4().length, is(3));
    assertThat(form.getArray4()[0], is("a"));
    assertThat(form.getArray4()[1], is("b"));
    assertThat(form.getArray4()[2], is("c"));
    assertThat(form.getItem(), is(notNullValue()));
    assertThat(form.getItem().getArray1().length, is(3));
    assertThat(form.getItem().getArray1()[0], is(11));
    assertThat(form.getItem().getArray1()[1], is(12));
    assertThat(form.getItem().getArray1()[2], is(13));
    assertThat(form.getItem().getArray2().length, is(2));
    assertThat(form.getItem().getArray2()[0], is(11.1));
    assertThat(form.getItem().getArray2()[1], is(11.2));
    assertThat(form.getItem().getArray3().length, is(3));
    assertThat(form.getItem().getArray3()[0], is((byte) 14));
    assertThat(form.getItem().getArray3()[1], is((byte) 15));
    assertThat(form.getItem().getArray3()[2], is((byte) 16));
    assertThat(form.getItem().getArray4().length, is(3));
    assertThat(form.getItem().getArray4()[0], is("d"));
    assertThat(form.getItem().getArray4()[1], is("e"));
    assertThat(form.getItem().getArray4()[2], is("f"));
}