@Test public void uriTemplateVarAndRequestParam() throws Exception { request.addParameter("age", "35"); Map<String, String> uriTemplateVars = new HashMap<String, String>(); uriTemplateVars.put("name", "nameValue"); uriTemplateVars.put("age", "25"); request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars); TestBean target = new TestBean(); WebDataBinder binder = new ExtendedServletRequestDataBinder(target, ""); ((ServletRequestDataBinder) binder).bind(request); assertEquals("nameValue", target.getName()); assertEquals(35, target.getAge()); }
@Test public void bindTagWithoutErrors() throws JspException { PageContext pc = createPageContext(); Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult(); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors); BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb"); assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); assertTrue("Has status variable", status != null); assertTrue("Correct expression", status.getExpression() == null); assertTrue("Correct value", status.getValue() == null); assertTrue("Correct displayValue", "".equals(status.getDisplayValue())); assertTrue("Correct isError", !status.isError()); assertTrue("Correct errorCodes", status.getErrorCodes().length == 0); assertTrue("Correct errorMessages", status.getErrorMessages().length == 0); assertTrue("Correct errorCode", "".equals(status.getErrorCode())); assertTrue("Correct errorMessage", "".equals(status.getErrorMessage())); assertTrue("Correct errorMessagesAsString", "".equals(status.getErrorMessagesAsString(","))); }
@Test public void bindTagWithIndexedProperties() throws JspException { PageContext pc = createPageContext(); IndexedTestBean tb = new IndexedTestBean(); Errors errors = new ServletRequestDataBinder(tb, "tb").getBindingResult(); errors.rejectValue("array[0]", "code1", "message1"); errors.rejectValue("array[0]", "code2", "message2"); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors); BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.array[0]"); assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); assertTrue("Has status variable", status != null); assertTrue("Correct expression", "array[0]".equals(status.getExpression())); assertTrue("Value is TestBean", status.getValue() instanceof TestBean); assertTrue("Correct value", "name0".equals(((TestBean) status.getValue()).getName())); assertTrue("Correct isError", status.isError()); assertTrue("Correct errorCodes", status.getErrorCodes().length == 2); assertTrue("Correct errorMessages", status.getErrorMessages().length == 2); assertTrue("Correct errorCode", "code1".equals(status.getErrorCodes()[0])); assertTrue("Correct errorCode", "code2".equals(status.getErrorCodes()[1])); assertTrue("Correct errorMessage", "message1".equals(status.getErrorMessages()[0])); assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessages()[1])); }
@Test public void bindTagWithMappedProperties() throws JspException { PageContext pc = createPageContext(); IndexedTestBean tb = new IndexedTestBean(); Errors errors = new ServletRequestDataBinder(tb, "tb").getBindingResult(); errors.rejectValue("map[key1]", "code1", "message1"); errors.rejectValue("map[key1]", "code2", "message2"); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors); BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.map[key1]"); assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); assertTrue("Has status variable", status != null); assertTrue("Correct expression", "map[key1]".equals(status.getExpression())); assertTrue("Value is TestBean", status.getValue() instanceof TestBean); assertTrue("Correct value", "name4".equals(((TestBean) status.getValue()).getName())); assertTrue("Correct isError", status.isError()); assertTrue("Correct errorCodes", status.getErrorCodes().length == 2); assertTrue("Correct errorMessages", status.getErrorMessages().length == 2); assertTrue("Correct errorCode", "code1".equals(status.getErrorCodes()[0])); assertTrue("Correct errorCode", "code2".equals(status.getErrorCodes()[1])); assertTrue("Correct errorMessage", "message1".equals(status.getErrorMessages()[0])); assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessages()[1])); }
@Test public void nestedPathWithBindTagWithIgnoreNestedPath() throws JspException { PageContext pc = createPageContext(); Errors errors = new ServletRequestDataBinder(new TestBean(), "tb2").getBindingResult(); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb2", errors); NestedPathTag tag = new NestedPathTag(); tag.setPath("tb"); tag.setPageContext(pc); tag.doStartTag(); BindTag bindTag = new BindTag(); bindTag.setPageContext(pc); bindTag.setIgnoreNestedPath(true); bindTag.setPath("tb2.name"); assertTrue("Correct doStartTag return value", bindTag.doStartTag() == Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); assertTrue("Has status variable", status != null); assertEquals("tb2.name", status.getPath()); }
@Test public void transformTagNonExistingValue() throws JspException { // first set up the pagecontext and the bean PageContext pc = createPageContext(); TestBean tb = new TestBean(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); ServletRequestDataBinder binder = new ServletRequestDataBinder(tb, "tb"); CustomDateEditor l = new CustomDateEditor(df, true); binder.registerCustomEditor(Date.class, l); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", binder.getBindingResult()); // try with non-existing value BindTag bind = new BindTag(); bind.setPageContext(pc); bind.setPath("tb.name"); bind.doStartTag(); TransformTag transform = new TransformTag(); transform.setPageContext(pc); transform.setValue(null); transform.setParent(bind); transform.setVar("theString2"); transform.doStartTag(); assertNull(pc.getAttribute("theString2")); }
/** * Look current Thread for {@link ServletRequestDataBinder} created by * {@link DataBinderMappingJackson2HttpMessageConverter}, if found return * it, otherwise it delegates on parent method. * * @param target * @param objectName * @param request * @return ServletRequestDataBinder */ @Override protected ServletRequestDataBinder createBinderInstance(Object target, String objectName, NativeWebRequest request) { try { ServletRequestDataBinder binder = (ServletRequestDataBinder) ThreadLocalUtil .getThreadVariable(BindingResult.MODEL_KEY_PREFIX .concat("JSON_DataBinder")); if (binder != null) { return binder; } return super.createBinderInstance(target, objectName, request); } finally { ThreadLocalUtil.destroy(); } }
@Test public void testInitBinder() { // Mock HTTP servlet request. HttpServletRequest request = mock(HttpServletRequest.class); // Mock servlet request data binder. ServletRequestDataBinder binder = mock(ServletRequestDataBinder.class); // Call the method under test. herdRestControllerAdvice.initBinder(request, binder); // Verify the external calls. verify(binder).registerCustomEditor(DelimitedFieldValues.class, delimitedFieldValuesEditor); verify(binder).registerCustomEditor(DateTime.class, dateTimeEditor); verifyNoMoreInteractions(binder); verifyNoMoreInteractionsHelper(); }
private Map<String, ?> parseValues(ServletRequest request, ServletRequestDataBinder binder) { Map<String, Object> params = Maps.newTreeMap(); Assert.notNull(request, "Request must not be null!"); Map<String, String> parameterMappings = getParameterMappings(request, binder); Enumeration<String> paramNames = request.getParameterNames(); while (paramNames != null && paramNames.hasMoreElements()) { String paramName = paramNames.nextElement(); String[] values = request.getParameterValues(paramName); String fieldName = parameterMappings.get(paramName); // no annotation exists, use the default - the param name=field name if (fieldName == null) { fieldName = paramName; } if (values == null || values.length == 0) { // Do nothing, no values found at all. } else if (values.length > 1) { params.put(fieldName, values); } else { params.put(fieldName, values[0]); } } return params; }
@Override protected void bindRequestParameters(WebDataBinder binder, NativeWebRequest request) { // Object target = binder.getTarget(); // Class<?> targetClass = target.getClass(); // if (!replaceMap.containsKey(targetClass)) { // Map<String, String> mapping = analyzeClass(targetClass); // replaceMap.put(targetClass, mapping); // } // Map<String, String> mapping = replaceMap.get(targetClass); // SuishenWebDataBinder paramNameDataBinder = new SuishenWebDataBinder(target, binder.getObjectName(), mapping, // doUnderScoreTrans); // // requestMappingHandlerAdapter.getWebBindingInitializer().initBinder(paramNameDataBinder, nativeWebRequest); // initBinder(paramNameDataBinder); // // super.bindRequestParameters(paramNameDataBinder, nativeWebRequest); ServletRequest servletRequest = request.getNativeRequest(ServletRequest.class); ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder; bind(servletRequest, servletBinder); }
/** * Allows for Integers to be used as values in input tags. Normally, only strings and lists are * expected * * @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder(javax.servlet.http.HttpServletRequest, * org.springframework.web.bind.ServletRequestDataBinder) */ protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { super.initBinder(request, binder); binder.registerCustomEditor(java.lang.Integer.class, new CustomNumberEditor(java.lang.Integer.class, true)); binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(Context.getDateFormat(), true)); binder.registerCustomEditor(java.util.Date.class, "valueDatetime", new CustomDateEditor(Context.getDateTimeFormat(), true)); binder.registerCustomEditor(java.util.Date.class, "valueTime", new CustomDateEditor(Context.getTimeFormat(), true)); binder.registerCustomEditor(Location.class, new LocationEditor()); binder.registerCustomEditor(java.lang.Boolean.class, new CustomBooleanEditor(true)); //allow for an empty boolean value binder.registerCustomEditor(Person.class, new PersonEditor()); binder.registerCustomEditor(Order.class, new OrderEditor()); binder.registerCustomEditor(Concept.class, new ConceptEditor()); binder.registerCustomEditor(Location.class, new LocationEditor()); binder.registerCustomEditor(Encounter.class, new EncounterEditor()); binder.registerCustomEditor(Drug.class, new DrugEditor()); }
/** * Allows for other Objects to be used as values in input tags. Normally, only strings and lists * are expected * * @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder(javax.servlet.http.HttpServletRequest, * org.springframework.web.bind.ServletRequestDataBinder) */ @Override protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { super.initBinder(request, binder); ConceptFormBackingObject commandObject = (ConceptFormBackingObject) binder.getTarget(); NumberFormat nf = NumberFormat.getInstance(Context.getLocale()); binder.registerCustomEditor(java.lang.Integer.class, new CustomNumberEditor(java.lang.Integer.class, nf, true)); binder.registerCustomEditor(java.lang.Double.class, new CustomNumberEditor(java.lang.Double.class, nf, true)); binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT, Context.getLocale()), true)); binder.registerCustomEditor(org.openmrs.ConceptClass.class, new ConceptClassEditor()); binder.registerCustomEditor(org.openmrs.ConceptDatatype.class, new ConceptDatatypeEditor()); binder.registerCustomEditor(java.util.Collection.class, "concept.conceptSets", new ConceptSetsEditor(commandObject .getConcept().getConceptSets())); binder.registerCustomEditor(java.util.Collection.class, "concept.answers", new ConceptAnswersEditor(commandObject .getConcept().getAnswers(true))); binder.registerCustomEditor(org.openmrs.ConceptSource.class, new ConceptSourceEditor()); binder.registerCustomEditor(ConceptMapType.class, new ConceptMapTypeEditor()); binder.registerCustomEditor(ConceptReferenceTerm.class, new ConceptReferenceTermEditor()); }
@Override public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { super.initBinder(request, binder); NumberFormat nf = NumberFormat.getInstance(request.getLocale()); // Register the binders. binder.registerCustomEditor(Long.class, "selectedPermission", new CustomNumberEditor(Long.class, nf, true)); binder.registerCustomEditor(java.util.Date.class, "startDate", DateUtils.get().getFullDateEditor(true)); binder.registerCustomEditor(java.util.Date.class, "endDate", DateUtils.get().getFullDateEditor(true)); // If the session model is available, we want to register the Permission's // authorising agency editor. if(getEditorContext(request) != null) { //binder.registerCustomEditor(AuthorisingAgent.class, new PermissionAuthAgencyEditor(sessionModel.getAuthorisingAgents())); binder.registerCustomEditor(AuthorisingAgent.class, "authorisingAgent", new EditorContextObjectEditor(getEditorContext(request), AuthorisingAgent.class)); binder.registerCustomEditor(Set.class, "urls", new UrlPatternCollectionEditor(Set.class, true, getEditorContext(request))); } }
/** * Prepare the given binder, applying the specified MessageCodesResolver, * BindingErrorProcessor and PropertyEditorRegistrars (if any). * Called by {@link #createBinder}. * @param binder the new binder instance * @see #createBinder * @see #setMessageCodesResolver * @see #setBindingErrorProcessor */ protected final void prepareBinder(ServletRequestDataBinder binder) { if (useDirectFieldAccess()) { binder.initDirectFieldAccess(); } if (this.messageCodesResolver != null) { binder.setMessageCodesResolver(this.messageCodesResolver); } if (this.bindingErrorProcessor != null) { binder.setBindingErrorProcessor(this.bindingErrorProcessor); } if (this.propertyEditorRegistrars != null) { for (int i = 0; i < this.propertyEditorRegistrars.length; i++) { this.propertyEditorRegistrars[i].registerCustomEditors(binder); } } }
/** * Set up a custom property editor for converting form inputs to real * objects * * @param request * the current request * @param binder * the data binder */ @InitBinder protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) { binder.registerCustomEditor(Integer.class, null, new CustomNumberEditor(Integer.class, null, true)); binder.registerCustomEditor(Long.class, null, new CustomNumberEditor( Long.class, null, true)); binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor()); log.trace(request.getLocale()); log.trace(getText("date.format", request.getLocale())); SimpleDateFormat dateFormat = new SimpleDateFormat(getText( "date.format", request.getLocale())); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, null, new CustomDateEditor( dateFormat, true)); }
/** * Command(s) */ /* * Auth Command. */ public ModelAndView authHandler(HttpServletRequest request, HttpServletResponse resp) throws Exception { getLog().info("AuthHandler()"); AuthCommand command = new AuthCommand(this.onecmdb); ServletRequestDataBinder binder = new ServletRequestDataBinder(command); binder.bind(request); try { String token = command.getToken(); resp.setContentLength(token.length()); resp.setContentType("text/plain"); resp.getOutputStream().write(token.getBytes()); } catch (Exception e) { resp.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE, "Authentication Failed!"); } return(null); }
@Test public void testBind() { command = new RouteAssignmentCommand(); request = new MockHttpServletRequest(); request.addParameter("legs[0].voyageNumber", "CM01"); request.addParameter("legs[0].fromUnLocode", "AAAAA"); request.addParameter("legs[0].toUnLocode", "BBBBB"); request.addParameter("legs[1].voyageNumber", "CM02"); request.addParameter("legs[1].fromUnLocode", "CCCCC"); request.addParameter("legs[1].toUnLocode", "DDDDD"); request.addParameter("trackingId", "XYZ"); ServletRequestDataBinder binder = new ServletRequestDataBinder(command); binder.bind(request); assertThat(command.getLegs()).hasSize(2).extracting("voyageNumber", "fromUnLocode", "toUnLocode") .containsAll(Arrays.asList(Tuple.tuple("CM01", "AAAAA", "BBBBB"), Tuple.tuple("CM02", "CCCCC", "DDDDD"))); assertThat(command.getTrackingId()).isEqualTo("XYZ"); }
/** * Validate assertion. * * @param request the request * @param serviceTicketId the service ticket id * @param assertion the assertion * @return the boolean */ private boolean validateAssertion(final HttpServletRequest request, final String serviceTicketId, final Assertion assertion) { final ValidationSpecification validationSpecification = this.getCommandClass(); final ServletRequestDataBinder binder = new ServletRequestDataBinder(validationSpecification, "validationSpecification"); initBinder(request, binder); binder.bind(request); if (!validationSpecification.isSatisfiedBy(assertion)) { logger.debug("Service ticket [{}] does not satisfy validation specification.", serviceTicketId); return false; } return true; }
/** * Validate assertion. * * @param request the request * @param serviceTicketId the service ticket id * @param assertion the assertion * @return true/false */ private boolean validateAssertion(final HttpServletRequest request, final String serviceTicketId, final Assertion assertion) { this.validationSpecification.reset(); final ServletRequestDataBinder binder = new ServletRequestDataBinder(this.validationSpecification, "validationSpecification"); initBinder(request, binder); binder.bind(request); if (!this.validationSpecification.isSatisfiedBy(assertion, request)) { LOGGER.warn("Service ticket [{}] does not satisfy validation specification.", serviceTicketId); return false; } return true; }
/** * {@inheritDoc} * Sets the require fields and the disallowed fields from the * HttpServletRequest. * * @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder(javax.servlet.http.HttpServletRequest, * org.springframework.web.bind.ServletRequestDataBinder) */ @Override protected void initBinder(final HttpServletRequest request, final ServletRequestDataBinder binder) throws Exception { binder.setRequiredFields(new String[] {"description", "serviceId", "name", "allowedToProxy", "enabled", "ssoEnabled", "anonymousAccess", "evaluationOrder"}); binder.setDisallowedFields(new String[] {"id"}); binder.registerCustomEditor(String.class, new StringTrimmerEditor(true)); }
@InitBinder protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { binder.registerCustomEditor(Category.class, "categorySet", new PropertyEditorSupport() { @Override public void setAsText(String text) { Category category = categoryService.findByPK(Long.parseLong(text)); setValue(category); } }); }
@InitBinder protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { binder.registerCustomEditor(Role.class, "roles", new PropertyEditorSupport() { @Override public void setAsText(String text) { Role role = roleService.findByPK(Long.parseLong(text)); setValue(role); } }); }
@InitBinder protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) { binder.registerCustomEditor(Role.class, "roles", new PropertyEditorSupport() { @Override public void setAsText(String text) { Role role = roleService.findByPK(Long.parseLong(text)); setValue(role); } }); }
@InitBinder public void initBinder(ServletRequestDataBinder binder) { /** * 自动转换日期类型的字段格式 */ binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true)); /** * 防止XSS攻击 */ binder.registerCustomEditor(String.class, new StringEscapeEditor()); }
/** * Bind request parameters onto the given command bean * @param request request from which parameters will be bound * @param command command object, that must be a JavaBean * @throws Exception in case of invalid state or arguments */ protected void bind(HttpServletRequest request, Object command) throws Exception { logger.debug("Binding request parameters onto MultiActionController command"); ServletRequestDataBinder binder = createBinder(request, command); binder.bind(request); if (this.validators != null) { for (Validator validator : this.validators) { if (validator.supports(command.getClass())) { ValidationUtils.invokeValidator(validator, command, binder.getBindingResult()); } } } binder.closeNoCatch(); }
/** * This implementation downcasts {@link WebDataBinder} to * {@link ServletRequestDataBinder} before binding. * @see ServletRequestDataBinderFactory */ @Override protected void bindRequestParameters(WebDataBinder binder, NativeWebRequest request) { ServletRequest servletRequest = request.getNativeRequest(ServletRequest.class); ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder; servletBinder.bind(servletRequest); }
@Test public void createBinder() throws Exception { Map<String, String> uriTemplateVars = new HashMap<String, String>(); uriTemplateVars.put("name", "nameValue"); uriTemplateVars.put("age", "25"); request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars); TestBean target = new TestBean(); WebDataBinder binder = new ExtendedServletRequestDataBinder(target, ""); ((ServletRequestDataBinder) binder).bind(request); assertEquals("nameValue", target.getName()); assertEquals(25, target.getAge()); }
@Test public void noUriTemplateVars() throws Exception { TestBean target = new TestBean(); WebDataBinder binder = new ExtendedServletRequestDataBinder(target, ""); ((ServletRequestDataBinder) binder).bind(request); assertEquals(null, target.getName()); assertEquals(0, target.getAge()); }
@Test public void bindTagWithNestedFieldErrors() throws JspException { PageContext pc = createPageContext(); TestBean tb = new TestBean(); tb.setName("name1"); TestBean spouse = new TestBean(); spouse.setName("name2"); tb.setSpouse(spouse); Errors errors = new ServletRequestDataBinder(tb, "tb").getBindingResult(); errors.rejectValue("spouse.name", "code1", "message1"); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors); BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.spouse.name"); assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); assertTrue("Has status variable", status != null); assertTrue("Correct expression", "spouse.name".equals(status.getExpression())); assertTrue("Correct value", "name2".equals(status.getValue())); assertTrue("Correct displayValue", "name2".equals(status.getDisplayValue())); assertTrue("Correct isError", status.isError()); assertTrue("Correct errorCodes", status.getErrorCodes().length == 1); assertTrue("Correct errorMessages", status.getErrorMessages().length == 1); assertTrue("Correct errorCode", "code1".equals(status.getErrorCode())); assertTrue("Correct errorMessage", "message1".equals(status.getErrorMessage())); assertTrue("Correct errorMessagesAsString", "message1".equals(status.getErrorMessagesAsString(" - "))); }
@Test public void bindTagWithIndexedPropertiesAndCustomEditor() throws JspException { PageContext pc = createPageContext(); IndexedTestBean tb = new IndexedTestBean(); DataBinder binder = new ServletRequestDataBinder(tb, "tb"); binder.registerCustomEditor(TestBean.class, null, new PropertyEditorSupport() { @Override public String getAsText() { return "something"; } }); Errors errors = binder.getBindingResult(); errors.rejectValue("array[0]", "code1", "message1"); errors.rejectValue("array[0]", "code2", "message2"); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors); BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.array[0]"); assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); assertTrue("Has status variable", status != null); assertTrue("Correct expression", "array[0]".equals(status.getExpression())); // because of the custom editor getValue() should return a String assertTrue("Value is TestBean", status.getValue() instanceof String); assertTrue("Correct value", "something".equals(status.getValue())); }
@Test public void bindErrorsTagWithoutErrors() throws JspException { PageContext pc = createPageContext(); Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult(); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors); BindErrorsTag tag = new BindErrorsTag(); tag.setPageContext(pc); tag.setName("tb"); assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.SKIP_BODY); assertTrue("Doesn't have errors variable", pc.getAttribute(BindErrorsTag.ERRORS_VARIABLE_NAME) == null); }
@Test public void bindErrorsTagWithErrors() throws JspException { PageContext pc = createPageContext(); Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult(); errors.reject("test", null, "test"); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors); BindErrorsTag tag = new BindErrorsTag(); tag.setPageContext(pc); tag.setName("tb"); assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); assertTrue("Has errors variable", pc.getAttribute(BindErrorsTag.ERRORS_VARIABLE_NAME, PageContext.REQUEST_SCOPE) == errors); }
@Test public void transformTagWithHtmlEscape() throws JspException { // first set up the PageContext and the bean PageContext pc = createPageContext(); TestBean tb = new TestBean(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); ServletRequestDataBinder binder = new ServletRequestDataBinder(tb, "tb"); CustomDateEditor l = new CustomDateEditor(df, true); binder.registerCustomEditor(Date.class, l); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", binder.getBindingResult()); // try another time, this time using Strings BindTag bind = new BindTag(); bind.setPageContext(pc); bind.setPath("tb.name"); bind.doStartTag(); TransformTag transform = new TransformTag(); transform.setPageContext(pc); transform.setValue("na<me"); transform.setParent(bind); transform.setVar("theString"); transform.setHtmlEscape(true); transform.doStartTag(); assertNotNull(pc.getAttribute("theString")); assertEquals("na<me", pc.getAttribute("theString")); }
@Override public void convertFields(HttpServletRequest request, ServletRequestDataBinder binder) { super.convertFields( request, binder); binder.registerCustomEditor(List.class,"lbAuthList", new ManyToManyListEditor(MscAuthInfo.class)); binder.registerCustomEditor(List.class,"lbPersonList", new ManyToManyListEditor(MscUsersInfo.class)); }
@Override public void convertFields(HttpServletRequest request, ServletRequestDataBinder binder) { super.convertFields( request, binder); binder.registerCustomEditor(List.class,"lbPersonList", new ManyToManyListEditor(MscUsersInfo.class)); binder.registerCustomEditor(List.class,"lbAllPersonList", new ManyToManyListEditor(MscUsersInfo.class)); }
/** * 表单中其他格式传入前先解析 * 如时间类型 * @param request * @param binder * @throws Exception */ @InitBinder protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { //对于需要转换为Date类型的属性,使用DateEditor进行处理 binder.registerCustomEditor(Date.class, new DateEditor()); //获取实体类,然后初始化去获取其特定的转换方式 IBaseDomain baseDomain=(IBaseDomain)getServiceImp().getBaseDao().getDomainClass().newInstance(); baseDomain.convertFields( request, binder); }
protected void initBinder(HttpServletRequest arg0, ServletRequestDataBinder binder) throws Exception { // SimpleDateFormat df = (SimpleDateFormat) // DateFormat.getDateInstance(); // df.applyPattern("yyyy-mm-dd"); binder .registerCustomEditor(java.sql.Date.class, null, new DateEditor()); arg0.setCharacterEncoding("gbk"); System.out.println("init End"); }
protected void bindRequestParameters(WebDataBinder binder, NativeWebRequest request,MethodParameter parameter) { Namespace annot = parameter.getParameterAnnotation(Namespace.class); String attrName= (annot != null) ? annot.value() : null; if(StringUtils.hasText(attrName)){ binder.setFieldDefaultPrefix(attrName+":"); } ServletRequest servletRequest = request.getNativeRequest(ServletRequest.class); ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder; servletBinder.bind(servletRequest); }