Here are the examples of the java api org.springframework.validation.Errors taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1109 Examples
19
View Source File : SamplePropertiesValidator.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Override
public void validate(Object o, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "host", "host.empty");
ValidationUtils.rejectIfEmpty(errors, "port", "port.empty");
SampleProperties properties = (SampleProperties) o;
if (properties.getHost() != null && !this.pattern.matcher(properties.getHost()).matches()) {
errors.rejectValue("host", "Invalid host");
}
}
19
View Source File : ValidatorAdapter.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Override
public void validate(Object target, Errors errors, Object... validationHints) {
this.target.validate(target, errors, validationHints);
}
19
View Source File : ValidatorAdapter.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Override
public void validate(Object target, Errors errors) {
this.target.validate(target, errors);
}
19
View Source File : ConfigurationPropertiesJsr303Validator.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Override
public void validate(Object target, Errors errors) {
this.delegate.validate(target, errors);
}
19
View Source File : InvalidRequestException.java
License : MIT License
Project Creator : wx-chevalier
License : MIT License
Project Creator : wx-chevalier
@SuppressWarnings("serial")
public clreplaced InvalidRequestException extends RuntimeException {
private final Errors errors;
public InvalidRequestException(Errors errors) {
super("");
this.errors = errors;
}
public Errors getErrors() {
return errors;
}
}
19
View Source File : ProfileUpdateFormValidator.java
License : Apache License 2.0
Project Creator : webauthn4j
License : Apache License 2.0
Project Creator : webauthn4j
@Override
public void validate(Object target, Errors errors) {
ProfileUpdateForm form = (ProfileUpdateForm) target;
if (form.getAuthenticators() == null || form.getAuthenticators().isEmpty()) {
if (form.isSingleFactorAuthenticationAllowed() != true) {
errors.rejectValue("authenticators", "e.ProfileUpdateFormValidator.noAuthenticator", "To disable preplacedword authentication, at least one authenticator must be registered.");
}
} else {
for (AuthenticatorForm authenticator : form.getAuthenticators()) {
try {
authenticatorFormValidator.validate(request, authenticator, errors);
} catch (ValidationException exception) {
errors.rejectValue("authenticators", "e.ProfileUpdateFormValidator.invalidAuthenticator", "AuthenticatorEnreplacedy is invalid.");
}
}
}
}
19
View Source File : ProfileCreateFormValidator.java
License : Apache License 2.0
Project Creator : webauthn4j
License : Apache License 2.0
Project Creator : webauthn4j
@Override
public void validate(Object target, Errors errors) {
ProfileCreateForm form = (ProfileCreateForm) target;
if (form.getAuthenticators() == null || form.getAuthenticators().isEmpty()) {
if (!form.isSingleFactorAuthenticationAllowed()) {
errors.rejectValue("authenticators", "e.ProfileCreateFormValidator.noAuthenticator", "To disable preplacedword authentication, at least one authenticator must be registered.");
}
} else {
for (AuthenticatorForm authenticator : form.getAuthenticators()) {
try {
authenticatorFormValidator.validate(request, authenticator, errors);
} catch (ValidationException exception) {
errors.rejectValue("authenticators", "e.ProfileCreateFormValidator.invalidAuthenticator", "AuthenticatorEnreplacedy is invalid.");
}
}
}
}
19
View Source File : CiTypeAttrValidator.java
License : Apache License 2.0
Project Creator : WeBankPartners
License : Apache License 2.0
Project Creator : WeBankPartners
private void validateBooleanField(String filedName, Integer val, Errors errors) {
BooleanType type = BooleanType.fromCode(val);
if (BooleanType.None.equals(type)) {
errors.rejectValue(filedName, "Invalid display type value");
}
}
19
View Source File : CiTypeAttrValidator.java
License : Apache License 2.0
Project Creator : WeBankPartners
License : Apache License 2.0
Project Creator : WeBankPartners
@Override
public void validate(Object target, Errors errors) {
CiTypeAttrDto ciTypeAttr = (CiTypeAttrDto) target;
validateInputType(errors, ciTypeAttr);
// validateDisplayType(errors, ciTypeAttr);
// validateBooleanField("editIsEditable",ciTypeAttr.getIsEditable(),errors);
// validateBooleanField("editIsHiden",ciTypeAttr.getIsHidden(),errors);
// validateBooleanField("editIsNull",ciTypeAttr.getIsNull(),errors);
// validateBooleanField("editIsOnly",ciTypeAttr.getIsUnique(),errors);
}
19
View Source File : MessageBrokerBeanDefinitionParserTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
public void validate(@Nullable Object target, Errors errors) {
}
19
View Source File : ErrorsTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void starMatchesAllErrors() throws Exception {
this.tag.setPath("*");
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
errors.reject("some.code", "object error");
errors.rejectValue("name", "some.code", "field error");
exposeBindingResult(errors);
this.tag.doStartTag();
replacedertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
this.tag.doEndTag();
String output = getOutput();
replacedertTrue(output.contains("id=\"testBean.errors\""));
replacedertTrue(output.contains("object error"));
replacedertTrue(output.contains("field error"));
}
19
View Source File : ErrorsTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void asBodyTag() throws Exception {
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
errors.rejectValue("name", "some.code", "Default Message");
errors.rejectValue("name", "too.short", "Too Short");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
replacedertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
replacedertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
String bodyContent = "Foo";
this.tag.setBodyContent(new MockBodyContent(bodyContent, getWriter()));
this.tag.doEndTag();
this.tag.doFinally();
replacedertEquals(bodyContent, getOutput());
replacedertNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
}
19
View Source File : ErrorsTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* https://jira.spring.io/browse/SPR-2788
*/
@Test
public void asBodyTagWithErrorsAndExistingMessagesAttributeInNonPageScopeAreNotClobbered() throws Exception {
String existingAttribute = "something";
getPageContext().setAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, existingAttribute, PageContext.APPLICATION_SCOPE);
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
errors.rejectValue("name", "some.code", "Default Message");
errors.rejectValue("name", "too.short", "Too Short");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
replacedertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
replacedertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
replacedertTrue(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE) instanceof List);
String bodyContent = "Foo";
this.tag.setBodyContent(new MockBodyContent(bodyContent, getWriter()));
this.tag.doEndTag();
this.tag.doFinally();
replacedertEquals(bodyContent, getOutput());
replacedertEquals(existingAttribute, getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, PageContext.APPLICATION_SCOPE));
}
19
View Source File : ErrorsTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void withExplicitNonWhitespaceBodyContent() throws Exception {
String mockContent = "This is some explicit body content";
this.tag.setBodyContent(new MockBodyContent(mockContent, getWriter()));
// construct an errors instance of the tag
TestBean target = new TestBean();
target.setName("Rob Harrop");
Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
errors.rejectValue("name", "some.code", "Default Message");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
replacedertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
replacedertEquals(Tag.EVAL_PAGE, result);
replacedertEquals(mockContent, getOutput());
}
19
View Source File : ErrorsTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void withErrorsAndDynamicAttributes() throws Exception {
String dynamicAttribute1 = "attr1";
String dynamicAttribute2 = "attr2";
this.tag.setDynamicAttribute(null, dynamicAttribute1, dynamicAttribute1);
this.tag.setDynamicAttribute(null, dynamicAttribute2, dynamicAttribute2);
// construct an errors instance of the tag
TestBean target = new TestBean();
target.setName("Rob Harrop");
Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
errors.rejectValue("name", "some.code", "Default Message");
errors.rejectValue("name", "too.short", "Too Short");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
replacedertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
replacedertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
replacedertElementTagOpened(output);
replacedertElementTagClosed(output);
replacedertContainsAttribute(output, "id", "name.errors");
replacedertContainsAttribute(output, dynamicAttribute1, dynamicAttribute1);
replacedertContainsAttribute(output, dynamicAttribute2, dynamicAttribute2);
replacedertBlockTagContains(output, "<br/>");
replacedertBlockTagContains(output, "Default Message");
replacedertBlockTagContains(output, "Too Short");
}
19
View Source File : ErrorsTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* https://jira.spring.io/browse/SPR-4005
*/
@Test
public void omittedPathMatchesObjectErrorsOnly() throws Exception {
this.tag.setPath(null);
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
errors.reject("some.code", "object error");
errors.rejectValue("name", "some.code", "field error");
exposeBindingResult(errors);
this.tag.doStartTag();
replacedertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
this.tag.doEndTag();
String output = getOutput();
replacedertTrue(output.contains("id=\"testBean.errors\""));
replacedertTrue(output.contains("object error"));
replacedertFalse(output.contains("field error"));
}
19
View Source File : ErrorsTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void withNonEscapedErrors() throws Exception {
this.tag.setHtmlEscape(false);
// construct an errors instance of the tag
TestBean target = new TestBean();
target.setName("Rob Harrop");
Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
errors.rejectValue("name", "some.code", "Default <> Message");
errors.rejectValue("name", "too.short", "Too & Short");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
replacedertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
replacedertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
replacedertElementTagOpened(output);
replacedertElementTagClosed(output);
replacedertContainsAttribute(output, "id", "name.errors");
replacedertBlockTagContains(output, "<br/>");
replacedertBlockTagContains(output, "Default <> Message");
replacedertBlockTagContains(output, "Too & Short");
}
19
View Source File : ErrorsTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void withEscapedErrors() throws Exception {
// construct an errors instance of the tag
TestBean target = new TestBean();
target.setName("Rob Harrop");
Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
errors.rejectValue("name", "some.code", "Default <> Message");
errors.rejectValue("name", "too.short", "Too & Short");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
replacedertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
replacedertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
replacedertElementTagOpened(output);
replacedertElementTagClosed(output);
replacedertContainsAttribute(output, "id", "name.errors");
replacedertBlockTagContains(output, "<br/>");
replacedertBlockTagContains(output, "Default <> Message");
replacedertBlockTagContains(output, "Too & Short");
}
19
View Source File : ErrorsTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void withErrorsAndCustomElement() throws Exception {
// construct an errors instance of the tag
TestBean target = new TestBean();
target.setName("Rob Harrop");
Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
errors.rejectValue("name", "some.code", "Default Message");
errors.rejectValue("name", "too.short", "Too Short");
exposeBindingResult(errors);
this.tag.setElement("div");
int result = this.tag.doStartTag();
replacedertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
replacedertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
replacedertElementTagOpened(output);
replacedertElementTagClosed(output);
replacedertContainsAttribute(output, "id", "name.errors");
replacedertBlockTagContains(output, "<br/>");
replacedertBlockTagContains(output, "Default Message");
replacedertBlockTagContains(output, "Too Short");
}
19
View Source File : ErrorsTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void withoutErrors() throws Exception {
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
replacedertEquals(Tag.SKIP_BODY, result);
result = this.tag.doEndTag();
replacedertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
replacedertEquals(0, output.length());
}
19
View Source File : ErrorsTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void withExplicitEmptyWhitespaceBodyContent() throws Exception {
this.tag.setBodyContent(new MockBodyContent("", getWriter()));
// construct an errors instance of the tag
TestBean target = new TestBean();
target.setName("Rob Harrop");
Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
errors.rejectValue("name", "some.code", "Default Message");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
replacedertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
replacedertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
replacedertElementTagOpened(output);
replacedertElementTagClosed(output);
replacedertContainsAttribute(output, "id", "name.errors");
replacedertBlockTagContains(output, "Default Message");
}
19
View Source File : ErrorsTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void asBodyTagWithExistingMessagesAttribute() throws Exception {
String existingAttribute = "something";
getPageContext().setAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, existingAttribute);
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
errors.rejectValue("name", "some.code", "Default Message");
errors.rejectValue("name", "too.short", "Too Short");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
replacedertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
replacedertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
replacedertTrue(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE) instanceof List);
String bodyContent = "Foo";
this.tag.setBodyContent(new MockBodyContent(bodyContent, getWriter()));
this.tag.doEndTag();
this.tag.doFinally();
replacedertEquals(bodyContent, getOutput());
replacedertEquals(existingAttribute, getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
}
19
View Source File : ErrorsTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void withErrors() throws Exception {
// construct an errors instance of the tag
TestBean target = new TestBean();
target.setName("Rob Harrop");
Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
errors.rejectValue("name", "some.code", "Default Message");
errors.rejectValue("name", "too.short", "Too Short");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
replacedertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
replacedertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
replacedertElementTagOpened(output);
replacedertElementTagClosed(output);
replacedertContainsAttribute(output, "id", "name.errors");
replacedertBlockTagContains(output, "<br/>");
replacedertBlockTagContains(output, "Default Message");
replacedertBlockTagContains(output, "Too Short");
}
19
View Source File : ErrorsTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void withExplicitWhitespaceBodyContent() throws Exception {
this.tag.setBodyContent(new MockBodyContent("\t\n ", getWriter()));
// construct an errors instance of the tag
TestBean target = new TestBean();
target.setName("Rob Harrop");
Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
errors.rejectValue("name", "some.code", "Default Message");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
replacedertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
replacedertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
replacedertElementTagOpened(output);
replacedertElementTagClosed(output);
replacedertContainsAttribute(output, "id", "name.errors");
replacedertBlockTagContains(output, "Default Message");
}
19
View Source File : ErrorsTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
private void replacedertWhenNoErrorsExistingMessagesInScopeAreNotClobbered(int scope) throws JspException {
String existingAttribute = "something";
getPageContext().setAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, existingAttribute, scope);
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
replacedertEquals(Tag.SKIP_BODY, result);
result = this.tag.doEndTag();
replacedertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
replacedertEquals(0, output.length());
replacedertEquals(existingAttribute, getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, scope));
}
19
View Source File : ErrorsTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void specificPathMatchesSpecificFieldOnly() throws Exception {
this.tag.setPath("name");
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
errors.reject("some.code", "object error");
errors.rejectValue("name", "some.code", "field error");
exposeBindingResult(errors);
this.tag.doStartTag();
replacedertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
this.tag.doEndTag();
String output = getOutput();
replacedertTrue(output.contains("id=\"name.errors\""));
replacedertFalse(output.contains("object error"));
replacedertTrue(output.contains("field error"));
}
19
View Source File : BindTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@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");
replacedertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.SKIP_BODY);
replacedertTrue("Doesn't have errors variable", pc.getAttribute(BindErrorsTag.ERRORS_VARIABLE_NAME) == null);
}
19
View Source File : BindTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void propertyExposing() throws JspException {
PageContext pc = createPageContext();
TestBean tb = new TestBean();
tb.setName("name1");
Errors errors = new BindException(tb, "tb");
errors.rejectValue("name", "code1", null, "message & 1");
errors.rejectValue("name", "code2", null, "message2");
pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors);
// test global property (should be null)
BindTag tag = new BindTag();
tag.setPageContext(pc);
tag.setPath("tb");
replacedertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
replacedertNull(tag.getProperty());
// test property set (tb.name)
tag.release();
tag.setPageContext(pc);
tag.setPath("tb.name");
replacedertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
replacedertEquals("name", tag.getProperty());
}
19
View Source File : BindTagTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@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");
replacedertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
replacedertTrue("Has errors variable", pc.getAttribute(BindErrorsTag.ERRORS_VARIABLE_NAME, PageContext.REQUEST_SCOPE) == errors);
}
19
View Source File : BindErrorsTag.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* This {@code <hasBindErrors>} tag provides an {@link Errors} instance in case of
* bind errors. The HTML escaping flag participates in a page-wide or
* application-wide setting (i.e. by HtmlEscapeTag or a "defaultHtmlEscape"
* context-param in web.xml).
*
* <table>
* <caption>Attribute Summary</caption>
* <thead>
* <tr>
* <th>Attribute</th>
* <th>Required?</th>
* <th>Runtime Expression?</th>
* <th>Description</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>htmlEscape</td>
* <td>false</td>
* <td>true</td>
* <td>Set HTML escaping for this tag, as boolean value.
* Overrides the default HTML escaping setting for the current page.</td>
* </tr>
* <tr>
* <td>name</td>
* <td>true</td>
* <td>true</td>
* <td>The name of the bean in the request that needs to be inspected for errors.
* If errors are available for this bean, they will be bound under the
* 'errors' key.</td>
* </tr>
* </tbody>
* </table>
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see BindTag
* @see org.springframework.validation.Errors
*/
@SuppressWarnings("serial")
public clreplaced BindErrorsTag extends HtmlEscapingAwareTag {
/**
* Page context attribute containing {@link Errors}.
*/
public static final String ERRORS_VARIABLE_NAME = "errors";
private String name = "";
@Nullable
private Errors errors;
/**
* Set the name of the bean that this tag should check.
*/
public void setName(String name) {
this.name = name;
}
/**
* Return the name of the bean that this tag checks.
*/
public String getName() {
return this.name;
}
@Override
protected final int doStartTagInternal() throws ServletException, JspException {
this.errors = getRequestContext().getErrors(this.name, isHtmlEscape());
if (this.errors != null && this.errors.hasErrors()) {
this.pageContext.setAttribute(ERRORS_VARIABLE_NAME, this.errors, PageContext.REQUEST_SCOPE);
return EVAL_BODY_INCLUDE;
} else {
return SKIP_BODY;
}
}
@Override
public int doEndTag() {
this.pageContext.removeAttribute(ERRORS_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
return EVAL_PAGE;
}
/**
* Retrieve the Errors instance that this tag is currently bound to.
* <p>Intended for cooperating nesting tags.
*/
@Nullable
public final Errors getErrors() {
return this.errors;
}
@Override
public void doFinally() {
super.doFinally();
this.errors = null;
}
}
19
View Source File : RequestContext.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Retrieve the Errors instance for the given bind object.
* @param name name of the bind object
* @param htmlEscape create an Errors instance with automatic HTML escaping?
* @return the Errors instance, or {@code null} if not found
*/
@Nullable
public Errors getErrors(String name, boolean htmlEscape) {
if (this.errorsMap == null) {
this.errorsMap = new HashMap<>();
}
Errors errors = this.errorsMap.get(name);
boolean put = false;
if (errors == null) {
errors = (Errors) getModelObject(BindingResult.MODEL_KEY_PREFIX + name);
// Check old BindException prefix for backwards compatibility.
if (errors instanceof BindException) {
errors = ((BindException) errors).getBindingResult();
}
if (errors == null) {
return null;
}
put = true;
}
if (htmlEscape && !(errors instanceof EscapedErrors)) {
errors = new EscapedErrors(errors);
put = true;
} else if (!htmlEscape && errors instanceof EscapedErrors) {
errors = ((EscapedErrors) errors).getSource();
put = true;
}
if (put) {
this.errorsMap.put(name, errors);
}
return errors;
}
19
View Source File : BindStatus.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Simple adapter to expose the bind status of a field or object.
* Set as a variable both by the JSP bind tag and FreeMarker macros.
*
* <p>Obviously, object status representations (i.e. errors at the object level
* rather than the field level) do not have an expression and a value but only
* error codes and messages. For simplicity's sake and to be able to use the same
* tags and macros, the same status clreplaced is used for both scenarios.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Darren Davison
* @see RequestContext#getBindStatus
* @see org.springframework.web.servlet.tags.BindTag
* @see org.springframework.web.servlet.view.AbstractTemplateView#setExposeSpringMacroHelpers
*/
public clreplaced BindStatus {
private final RequestContext requestContext;
private final String path;
private final boolean htmlEscape;
@Nullable
private final String expression;
@Nullable
private final Errors errors;
private final String[] errorCodes;
@Nullable
private String[] errorMessages;
@Nullable
private List<? extends ObjectError> objectErrors;
@Nullable
private Object value;
@Nullable
private Clreplaced<?> valueType;
@Nullable
private Object actualValue;
@Nullable
private PropertyEditor editor;
@Nullable
private BindingResult bindingResult;
/**
* Create a new BindStatus instance, representing a field or object status.
* @param requestContext the current RequestContext
* @param path the bean and property path for which values and errors
* will be resolved (e.g. "customer.address.street")
* @param htmlEscape whether to HTML-escape error messages and string values
* @throws IllegalStateException if no corresponding Errors object found
*/
public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException {
this.requestContext = requestContext;
this.path = path;
this.htmlEscape = htmlEscape;
// determine name of the object and property
String beanName;
int dotPos = path.indexOf('.');
if (dotPos == -1) {
// property not set, only the object itself
beanName = path;
this.expression = null;
} else {
beanName = path.substring(0, dotPos);
this.expression = path.substring(dotPos + 1);
}
this.errors = requestContext.getErrors(beanName, false);
if (this.errors != null) {
// Usual case: A BindingResult is available as request attribute.
// Can determine error codes and messages for the given expression.
// Can use a custom PropertyEditor, as registered by a form controller.
if (this.expression != null) {
if ("*".equals(this.expression)) {
this.objectErrors = this.errors.getAllErrors();
} else if (this.expression.endsWith("*")) {
this.objectErrors = this.errors.getFieldErrors(this.expression);
} else {
this.objectErrors = this.errors.getFieldErrors(this.expression);
this.value = this.errors.getFieldValue(this.expression);
this.valueType = this.errors.getFieldType(this.expression);
if (this.errors instanceof BindingResult) {
this.bindingResult = (BindingResult) this.errors;
this.actualValue = this.bindingResult.getRawFieldValue(this.expression);
this.editor = this.bindingResult.findEditor(this.expression, null);
} else {
this.actualValue = this.value;
}
}
} else {
this.objectErrors = this.errors.getGlobalErrors();
}
this.errorCodes = initErrorCodes(this.objectErrors);
} else {
// No BindingResult available as request attribute:
// Probably forwarded directly to a form view.
// Let's do the best we can: extract a plain target if appropriate.
Object target = requestContext.getModelObject(beanName);
if (target == null) {
throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute");
}
if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) {
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target);
this.value = bw.getPropertyValue(this.expression);
this.valueType = bw.getPropertyType(this.expression);
this.actualValue = this.value;
}
this.errorCodes = new String[0];
this.errorMessages = new String[0];
}
if (htmlEscape && this.value instanceof String) {
this.value = HtmlUtils.htmlEscape((String) this.value);
}
}
/**
* Extract the error codes from the ObjectError list.
*/
private static String[] initErrorCodes(List<? extends ObjectError> objectErrors) {
String[] errorCodes = new String[objectErrors.size()];
for (int i = 0; i < objectErrors.size(); i++) {
ObjectError error = objectErrors.get(i);
errorCodes[i] = error.getCode();
}
return errorCodes;
}
/**
* Return the bean and property path for which values and errors
* will be resolved (e.g. "customer.address.street").
*/
public String getPath() {
return this.path;
}
/**
* Return a bind expression that can be used in HTML forms as input name
* for the respective field, or {@code null} if not field-specific.
* <p>Returns a bind path appropriate for resubmission, e.g. "address.street".
* Note that the complete bind path as required by the bind tag is
* "customer.address.street", if bound to a "customer" bean.
*/
@Nullable
public String getExpression() {
return this.expression;
}
/**
* Return the current value of the field, i.e. either the property value
* or a rejected update, or {@code null} if not field-specific.
* <p>This value will be an HTML-escaped String if the original value
* already was a String.
*/
@Nullable
public Object getValue() {
return this.value;
}
/**
* Get the '{@code Clreplaced}' type of the field. Favor this instead of
* '{@code getValue().getClreplaced()}' since '{@code getValue()}' may
* return '{@code null}'.
*/
@Nullable
public Clreplaced<?> getValueType() {
return this.valueType;
}
/**
* Return the actual value of the field, i.e. the raw property value,
* or {@code null} if not available.
*/
@Nullable
public Object getActualValue() {
return this.actualValue;
}
/**
* Return a suitable display value for the field, i.e. the stringified
* value if not null, and an empty string in case of a null value.
* <p>This value will be an HTML-escaped String if the original value
* was non-null: the {@code toString} result of the original value
* will get HTML-escaped.
*/
public String getDisplayValue() {
if (this.value instanceof String) {
return (String) this.value;
}
if (this.value != null) {
return (this.htmlEscape ? HtmlUtils.htmlEscape(this.value.toString()) : this.value.toString());
}
return "";
}
/**
* Return if this status represents a field or object error.
*/
public boolean isError() {
return (this.errorCodes.length > 0);
}
/**
* Return the error codes for the field or object, if any.
* Returns an empty array instead of null if none.
*/
public String[] getErrorCodes() {
return this.errorCodes;
}
/**
* Return the first error codes for the field or object, if any.
*/
public String getErrorCode() {
return (this.errorCodes.length > 0 ? this.errorCodes[0] : "");
}
/**
* Return the resolved error messages for the field or object,
* if any. Returns an empty array instead of null if none.
*/
public String[] getErrorMessages() {
return initErrorMessages();
}
/**
* Return the first error message for the field or object, if any.
*/
public String getErrorMessage() {
String[] errorMessages = initErrorMessages();
return (errorMessages.length > 0 ? errorMessages[0] : "");
}
/**
* Return an error message string, concatenating all messages
* separated by the given delimiter.
* @param delimiter separator string, e.g. ", " or "<br>"
* @return the error message string
*/
public String getErrorMessagesreplacedtring(String delimiter) {
return StringUtils.arrayToDelimitedString(initErrorMessages(), delimiter);
}
/**
* Extract the error messages from the ObjectError list.
*/
private String[] initErrorMessages() throws NoSuchMessageException {
if (this.errorMessages == null) {
if (this.objectErrors != null) {
this.errorMessages = new String[this.objectErrors.size()];
for (int i = 0; i < this.objectErrors.size(); i++) {
ObjectError error = this.objectErrors.get(i);
this.errorMessages[i] = this.requestContext.getMessage(error, this.htmlEscape);
}
} else {
this.errorMessages = new String[0];
}
}
return this.errorMessages;
}
/**
* Return the Errors instance (typically a BindingResult) that this
* bind status is currently replacedociated with.
* @return the current Errors instance, or {@code null} if none
* @see org.springframework.validation.BindingResult
*/
@Nullable
public Errors getErrors() {
return this.errors;
}
/**
* Return the PropertyEditor for the property that this bind status
* is currently bound to.
* @return the current PropertyEditor, or {@code null} if none
*/
@Nullable
public PropertyEditor getEditor() {
return this.editor;
}
/**
* Find a PropertyEditor for the given value clreplaced, replacedociated with
* the property that this bound status is currently bound to.
* @param valueClreplaced the value clreplaced that an editor is needed for
* @return the replacedociated PropertyEditor, or {@code null} if none
*/
@Nullable
public PropertyEditor findEditor(Clreplaced<?> valueClreplaced) {
return (this.bindingResult != null ? this.bindingResult.findEditor(this.expression, valueClreplaced) : null);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("BindStatus: ");
sb.append("expression=[").append(this.expression).append("]; ");
sb.append("value=[").append(this.value).append("]");
if (!ObjectUtils.isEmpty(this.errorCodes)) {
sb.append("; errorCodes=").append(Arrays.asList(this.errorCodes));
}
return sb.toString();
}
}
19
View Source File : ErrorsMethodArgumentResolverTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@SuppressWarnings("unused")
void handle(@ModelAttribute Foo foo, Errors errors, @ModelAttribute Mono<Foo> fooMono, BindingResult bindingResult, Mono<Errors> errorsMono, String string) {
}
19
View Source File : RequestContext.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Retrieve the Errors instance for the given bind object.
* @param name name of the bind object
* @param htmlEscape create an Errors instance with automatic HTML escaping?
* @return the Errors instance, or {@code null} if not found
*/
@Nullable
public Errors getErrors(String name, boolean htmlEscape) {
if (this.errorsMap == null) {
this.errorsMap = new HashMap<>();
}
Errors errors = this.errorsMap.get(name);
if (errors == null) {
errors = getModelObject(BindingResult.MODEL_KEY_PREFIX + name);
if (errors == null) {
return null;
}
}
if (errors instanceof BindException) {
errors = ((BindException) errors).getBindingResult();
}
if (htmlEscape && !(errors instanceof EscapedErrors)) {
errors = new EscapedErrors(errors);
} else if (!htmlEscape && errors instanceof EscapedErrors) {
errors = ((EscapedErrors) errors).getSource();
}
this.errorsMap.put(name, errors);
return errors;
}
19
View Source File : BindStatus.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Simple adapter to expose the bind status of a field or object.
* Set as a variable by FreeMarker macros and other tag libraries.
*
* <p>Obviously, object status representations (i.e. errors at the object level
* rather than the field level) do not have an expression and a value but only
* error codes and messages. For simplicity's sake and to be able to use the same
* tags and macros, the same status clreplaced is used for both scenarios.
*
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @since 5.0
* @see RequestContext#getBindStatus
*/
public clreplaced BindStatus {
private final RequestContext requestContext;
private final String path;
private final boolean htmlEscape;
@Nullable
private final String expression;
@Nullable
private final Errors errors;
private final String[] errorCodes;
@Nullable
private String[] errorMessages;
@Nullable
private List<? extends ObjectError> objectErrors;
@Nullable
private Object value;
@Nullable
private Clreplaced<?> valueType;
@Nullable
private Object actualValue;
@Nullable
private PropertyEditor editor;
@Nullable
private BindingResult bindingResult;
/**
* Create a new BindStatus instance, representing a field or object status.
* @param requestContext the current RequestContext
* @param path the bean and property path for which values and errors
* will be resolved (e.g. "customer.address.street")
* @param htmlEscape whether to HTML-escape error messages and string values
* @throws IllegalStateException if no corresponding Errors object found
*/
public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException {
this.requestContext = requestContext;
this.path = path;
this.htmlEscape = htmlEscape;
// determine name of the object and property
String beanName;
int dotPos = path.indexOf('.');
if (dotPos == -1) {
// property not set, only the object itself
beanName = path;
this.expression = null;
} else {
beanName = path.substring(0, dotPos);
this.expression = path.substring(dotPos + 1);
}
this.errors = requestContext.getErrors(beanName, false);
if (this.errors != null) {
// Usual case: A BindingResult is available as request attribute.
// Can determine error codes and messages for the given expression.
// Can use a custom PropertyEditor, as registered by a form controller.
if (this.expression != null) {
if ("*".equals(this.expression)) {
this.objectErrors = this.errors.getAllErrors();
} else if (this.expression.endsWith("*")) {
this.objectErrors = this.errors.getFieldErrors(this.expression);
} else {
this.objectErrors = this.errors.getFieldErrors(this.expression);
this.value = this.errors.getFieldValue(this.expression);
this.valueType = this.errors.getFieldType(this.expression);
if (this.errors instanceof BindingResult) {
this.bindingResult = (BindingResult) this.errors;
this.actualValue = this.bindingResult.getRawFieldValue(this.expression);
this.editor = this.bindingResult.findEditor(this.expression, null);
} else {
this.actualValue = this.value;
}
}
} else {
this.objectErrors = this.errors.getGlobalErrors();
}
this.errorCodes = initErrorCodes(this.objectErrors);
} else {
// No BindingResult available as request attribute:
// Probably forwarded directly to a form view.
// Let's do the best we can: extract a plain target if appropriate.
Object target = requestContext.getModelObject(beanName);
if (target == null) {
throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute");
}
if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) {
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target);
this.value = bw.getPropertyValue(this.expression);
this.valueType = bw.getPropertyType(this.expression);
this.actualValue = this.value;
}
this.errorCodes = new String[0];
this.errorMessages = new String[0];
}
if (htmlEscape && this.value instanceof String) {
this.value = HtmlUtils.htmlEscape((String) this.value);
}
}
/**
* Extract the error codes from the ObjectError list.
*/
private static String[] initErrorCodes(List<? extends ObjectError> objectErrors) {
String[] errorCodes = new String[objectErrors.size()];
for (int i = 0; i < objectErrors.size(); i++) {
ObjectError error = objectErrors.get(i);
errorCodes[i] = error.getCode();
}
return errorCodes;
}
/**
* Return the bean and property path for which values and errors
* will be resolved (e.g. "customer.address.street").
*/
public String getPath() {
return this.path;
}
/**
* Return a bind expression that can be used in HTML forms as input name
* for the respective field, or {@code null} if not field-specific.
* <p>Returns a bind path appropriate for resubmission, e.g. "address.street".
* Note that the complete bind path as required by the bind tag is
* "customer.address.street", if bound to a "customer" bean.
*/
@Nullable
public String getExpression() {
return this.expression;
}
/**
* Return the current value of the field, i.e. either the property value
* or a rejected update, or {@code null} if not field-specific.
* <p>This value will be an HTML-escaped String if the original value
* already was a String.
*/
@Nullable
public Object getValue() {
return this.value;
}
/**
* Get the '{@code Clreplaced}' type of the field. Favor this instead of
* '{@code getValue().getClreplaced()}' since '{@code getValue()}' may
* return '{@code null}'.
*/
@Nullable
public Clreplaced<?> getValueType() {
return this.valueType;
}
/**
* Return the actual value of the field, i.e. the raw property value,
* or {@code null} if not available.
*/
@Nullable
public Object getActualValue() {
return this.actualValue;
}
/**
* Return a suitable display value for the field, i.e. the stringified
* value if not null, and an empty string in case of a null value.
* <p>This value will be an HTML-escaped String if the original value
* was non-null: the {@code toString} result of the original value
* will get HTML-escaped.
*/
public String getDisplayValue() {
if (this.value instanceof String) {
return (String) this.value;
}
if (this.value != null) {
return (this.htmlEscape ? HtmlUtils.htmlEscape(this.value.toString()) : this.value.toString());
}
return "";
}
/**
* Return if this status represents a field or object error.
*/
public boolean isError() {
return (this.errorCodes.length > 0);
}
/**
* Return the error codes for the field or object, if any.
* Returns an empty array instead of null if none.
*/
public String[] getErrorCodes() {
return this.errorCodes;
}
/**
* Return the first error codes for the field or object, if any.
*/
public String getErrorCode() {
return (!ObjectUtils.isEmpty(this.errorCodes) ? this.errorCodes[0] : "");
}
/**
* Return the resolved error messages for the field or object,
* if any. Returns an empty array instead of null if none.
*/
public String[] getErrorMessages() {
return initErrorMessages();
}
/**
* Return the first error message for the field or object, if any.
*/
public String getErrorMessage() {
String[] errorMessages = initErrorMessages();
return (errorMessages.length > 0 ? errorMessages[0] : "");
}
/**
* Return an error message string, concatenating all messages
* separated by the given delimiter.
* @param delimiter separator string, e.g. ", " or "<br>"
* @return the error message string
*/
public String getErrorMessagesreplacedtring(String delimiter) {
return StringUtils.arrayToDelimitedString(initErrorMessages(), delimiter);
}
/**
* Extract the error messages from the ObjectError list.
*/
private String[] initErrorMessages() throws NoSuchMessageException {
if (this.errorMessages == null) {
if (this.objectErrors != null) {
this.errorMessages = new String[this.objectErrors.size()];
for (int i = 0; i < this.objectErrors.size(); i++) {
ObjectError error = this.objectErrors.get(i);
this.errorMessages[i] = this.requestContext.getMessage(error, this.htmlEscape);
}
} else {
this.errorMessages = new String[0];
}
}
return this.errorMessages;
}
/**
* Return the Errors instance (typically a BindingResult) that this
* bind status is currently replacedociated with.
* @return the current Errors instance, or {@code null} if none
* @see org.springframework.validation.BindingResult
*/
@Nullable
public Errors getErrors() {
return this.errors;
}
/**
* Return the PropertyEditor for the property that this bind status
* is currently bound to.
* @return the current PropertyEditor, or {@code null} if none
*/
@Nullable
public PropertyEditor getEditor() {
return this.editor;
}
/**
* Find a PropertyEditor for the given value clreplaced, replacedociated with
* the property that this bound status is currently bound to.
* @param valueClreplaced the value clreplaced that an editor is needed for
* @return the replacedociated PropertyEditor, or {@code null} if none
*/
@Nullable
public PropertyEditor findEditor(Clreplaced<?> valueClreplaced) {
return (this.bindingResult != null ? this.bindingResult.findEditor(this.expression, valueClreplaced) : null);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("BindStatus: ");
sb.append("expression=[").append(this.expression).append("]; ");
sb.append("value=[").append(this.value).append("]");
if (!ObjectUtils.isEmpty(this.errorCodes)) {
sb.append("; errorCodes=").append(Arrays.asList(this.errorCodes));
}
return sb.toString();
}
}
19
View Source File : ErrorsMethodArgumentResolverTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@SuppressWarnings("unused")
private void handle(Errors errors) {
}
19
View Source File : WebExchangeBindException.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
public void addAllErrors(Errors errors) {
this.bindingResult.addAllErrors(errors);
}
19
View Source File : EscapedErrors.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Errors wrapper that adds automatic HTML escaping to the wrapped instance,
* for convenient usage in HTML views. Can be retrieved easily via
* RequestContext's {@code getErrors} method.
*
* <p>Note that BindTag does <i>not</i> use this clreplaced to avoid unnecessary
* creation of ObjectError instances. It just escapes the messages and values
* that get copied into the respective BindStatus instance.
*
* @author Juergen Hoeller
* @since 01.03.2003
* @see org.springframework.web.servlet.support.RequestContext#getErrors
* @see org.springframework.web.servlet.tags.BindTag
*/
public clreplaced EscapedErrors implements Errors {
private final Errors source;
/**
* Create a new EscapedErrors instance for the given source instance.
*/
public EscapedErrors(Errors source) {
replacedert.notNull(source, "Errors source must not be null");
this.source = source;
}
public Errors getSource() {
return this.source;
}
@Override
public String getObjectName() {
return this.source.getObjectName();
}
@Override
public void setNestedPath(String nestedPath) {
this.source.setNestedPath(nestedPath);
}
@Override
public String getNestedPath() {
return this.source.getNestedPath();
}
@Override
public void pushNestedPath(String subPath) {
this.source.pushNestedPath(subPath);
}
@Override
public void popNestedPath() throws IllegalStateException {
this.source.popNestedPath();
}
@Override
public void reject(String errorCode) {
this.source.reject(errorCode);
}
@Override
public void reject(String errorCode, String defaultMessage) {
this.source.reject(errorCode, defaultMessage);
}
@Override
public void reject(String errorCode, @Nullable Object[] errorArgs, @Nullable String defaultMessage) {
this.source.reject(errorCode, errorArgs, defaultMessage);
}
@Override
public void rejectValue(@Nullable String field, String errorCode) {
this.source.rejectValue(field, errorCode);
}
@Override
public void rejectValue(@Nullable String field, String errorCode, String defaultMessage) {
this.source.rejectValue(field, errorCode, defaultMessage);
}
@Override
public void rejectValue(@Nullable String field, String errorCode, @Nullable Object[] errorArgs, @Nullable String defaultMessage) {
this.source.rejectValue(field, errorCode, errorArgs, defaultMessage);
}
@Override
public void addAllErrors(Errors errors) {
this.source.addAllErrors(errors);
}
@Override
public boolean hasErrors() {
return this.source.hasErrors();
}
@Override
public int getErrorCount() {
return this.source.getErrorCount();
}
@Override
public List<ObjectError> getAllErrors() {
return escapeObjectErrors(this.source.getAllErrors());
}
@Override
public boolean hasGlobalErrors() {
return this.source.hasGlobalErrors();
}
@Override
public int getGlobalErrorCount() {
return this.source.getGlobalErrorCount();
}
@Override
public List<ObjectError> getGlobalErrors() {
return escapeObjectErrors(this.source.getGlobalErrors());
}
@Override
@Nullable
public ObjectError getGlobalError() {
return escapeObjectError(this.source.getGlobalError());
}
@Override
public boolean hasFieldErrors() {
return this.source.hasFieldErrors();
}
@Override
public int getFieldErrorCount() {
return this.source.getFieldErrorCount();
}
@Override
public List<FieldError> getFieldErrors() {
return this.source.getFieldErrors();
}
@Override
@Nullable
public FieldError getFieldError() {
return this.source.getFieldError();
}
@Override
public boolean hasFieldErrors(String field) {
return this.source.hasFieldErrors(field);
}
@Override
public int getFieldErrorCount(String field) {
return this.source.getFieldErrorCount(field);
}
@Override
public List<FieldError> getFieldErrors(String field) {
return escapeObjectErrors(this.source.getFieldErrors(field));
}
@Override
@Nullable
public FieldError getFieldError(String field) {
return escapeObjectError(this.source.getFieldError(field));
}
@Override
@Nullable
public Object getFieldValue(String field) {
Object value = this.source.getFieldValue(field);
return (value instanceof String ? HtmlUtils.htmlEscape((String) value) : value);
}
@Override
@Nullable
public Clreplaced<?> getFieldType(String field) {
return this.source.getFieldType(field);
}
@SuppressWarnings("unchecked")
@Nullable
private <T extends ObjectError> T escapeObjectError(@Nullable T source) {
if (source == null) {
return null;
}
String defaultMessage = source.getDefaultMessage();
if (defaultMessage != null) {
defaultMessage = HtmlUtils.htmlEscape(defaultMessage);
}
if (source instanceof FieldError) {
FieldError fieldError = (FieldError) source;
Object value = fieldError.getRejectedValue();
if (value instanceof String) {
value = HtmlUtils.htmlEscape((String) value);
}
return (T) new FieldError(fieldError.getObjectName(), fieldError.getField(), value, fieldError.isBindingFailure(), fieldError.getCodes(), fieldError.getArguments(), defaultMessage);
} else {
return (T) new ObjectError(source.getObjectName(), source.getCodes(), source.getArguments(), defaultMessage);
}
}
private <T extends ObjectError> List<T> escapeObjectErrors(List<T> source) {
List<T> escaped = new ArrayList<>(source.size());
for (T objectError : source) {
escaped.add(escapeObjectError(objectError));
}
return escaped;
}
}
19
View Source File : EscapedErrors.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
public void addAllErrors(Errors errors) {
this.source.addAllErrors(errors);
}
19
View Source File : ModelResultMatchers.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* replacedert the given model attribute(s) have errors.
*/
public ResultMatcher attributeErrorCount(final String name, final int expectedCount) {
return result -> {
ModelAndView mav = getModelAndView(result);
Errors errors = getBindingResult(mav, name);
replacedertEquals("Binding/validation error count for attribute '" + name + "', ", expectedCount, errors.getErrorCount());
};
}
19
View Source File : ValidatorFactoryTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void testValidationWithOptionalField() {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.afterPropertiesSet();
MainBeanWithOptional mainBean = new MainBeanWithOptional();
Errors errors = new BeanPropertyBindingResult(mainBean, "mainBean");
validator.validate(mainBean, errors);
Object rejected = errors.getFieldValue("inner.value");
replacedertNull(rejected);
}
19
View Source File : ValidatorFactoryTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void testInnerBeanValidation() {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.afterPropertiesSet();
MainBean mainBean = new MainBean();
Errors errors = new BeanPropertyBindingResult(mainBean, "mainBean");
validator.validate(mainBean, errors);
Object rejected = errors.getFieldValue("inner.value");
replacedertNull(rejected);
}
19
View Source File : SpringValidatorAdapter.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
public void validate(Object target, Errors errors) {
if (this.targetValidator != null) {
processConstraintViolations(this.targetValidator.validate(target), errors);
}
}
19
View Source File : SpringValidatorAdapter.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
public void validate(Object target, Errors errors, Object... validationHints) {
if (this.targetValidator != null) {
processConstraintViolations(this.targetValidator.validate(target, asValidationGroups(validationHints)), errors);
}
}
19
View Source File : CdmrFeatureQueryBeanValidator.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Unidata
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Unidata
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "req", "req.empty", "must have a req parameter");
ValidationUtils.rejectIfEmpty(errors, "var", "var.empty", "data request must have a var paramater");
CdmrFeatureQueryBean bean = (CdmrFeatureQueryBean) target;
if (bean.getReq() == null)
bean.addError("must have a req parameter");
if (bean.getVar() == null)
bean.addError("data request must have a var parameter");
CdmrFeatureQueryBean.RequestType reqType;
if (bean.getReq().equalsIgnoreCase("data"))
reqType = CdmrFeatureQueryBean.RequestType.data;
else if (bean.getReq().equalsIgnoreCase("header"))
reqType = CdmrFeatureQueryBean.RequestType.header;
else
// default
reqType = CdmrFeatureQueryBean.RequestType.data;
bean.setReqType(reqType);
}
19
View Source File : CdmRemoteQueryBeanValidator.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Unidata
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Unidata
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "req", "req.empty", "must have a req parameter");
ValidationUtils.rejectIfEmpty(errors, "var", "var.empty", "data request must have a var paramater");
CdmRemoteQueryBean bean = (CdmRemoteQueryBean) target;
if (bean.getReq() == null)
bean.addError("must have a req parameter");
if (bean.getVar() == null)
bean.addError("data request must have a var parameter");
CdmRemoteQueryBean.RequestType reqType;
if (bean.getReq().equalsIgnoreCase("capabilities"))
reqType = CdmRemoteQueryBean.RequestType.capabilities;
else if (bean.getReq().equalsIgnoreCase("cdl"))
reqType = CdmRemoteQueryBean.RequestType.cdl;
else if (bean.getReq().equalsIgnoreCase("form"))
reqType = CdmRemoteQueryBean.RequestType.cdl;
else if (bean.getReq().equalsIgnoreCase("data"))
reqType = CdmRemoteQueryBean.RequestType.data;
else if (bean.getReq().equalsIgnoreCase("header"))
reqType = CdmRemoteQueryBean.RequestType.header;
else if (bean.getReq().equalsIgnoreCase("ncml"))
reqType = CdmRemoteQueryBean.RequestType.ncml;
else
// default
reqType = CdmRemoteQueryBean.RequestType.data;
bean.setReqType(reqType);
int deflateLevel = bean.getDeflate();
if (deflateLevel >= 0)
bean.setDeflate(deflateLevel);
}
19
View Source File : RemoteCatalogRequestValidator.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Unidata
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Unidata
public void validate(Object obj, Errors errs) {
RemoteCatalogRequest rcr = (RemoteCatalogRequest) obj;
try {
URI catUri = new URI(rcr.getCatalog());
if (!catUri.isAbsolute())
errs.rejectValue("catalogUri", "catalogUri.notAbsolute", "The catalog parameter must be an absolute URI.");
if (catUri.getScheme() != null && !catUri.getScheme().equalsIgnoreCase("HTTP") && !catUri.getScheme().equalsIgnoreCase("HTTPS"))
errs.rejectValue("catalogUri", "catalogUri.notHttpUri", "The \"catalogUri\" field must be an HTTP|HTTPS URI.");
rcr.setCatalogUri(catUri);
} catch (URISyntaxException e) {
errs.rejectValue("catalog", "catalogUri.notAbsolute", "catalog parameter is not a valid URI");
}
if (rcr.getDataset() != null)
rcr.setCommand(RemoteCatalogRequest.Command.SUBSET);
else if (rcr.getCommand() == null)
rcr.setCommand(RemoteCatalogRequest.Command.SHOW);
}
19
View Source File : DepositController.java
License : Apache License 2.0
Project Creator : tedyoung
License : Apache License 2.0
Project Creator : tedyoung
@PostMapping
public String processDepositCommand(@Valid @ModelAttribute("depositCommand") TransactionCommand depositCommand, Errors errors, @AuthenticationPrincipal UserProfile userProfile) {
if (errors.hasErrors()) {
return "deposit";
}
int depositAmount = depositCommand.amountInCents();
LocalDateTime dateTime = depositCommand.getDateAsLocalDateTime();
account.deposit(dateTime, depositAmount, depositCommand.getDescription(), userProfile);
return "redirect:" + AccountController.ACCOUNT_URL;
}
19
View Source File : StudentValidator.java
License : The Unlicense
Project Creator : suriarasai
License : The Unlicense
Project Creator : suriarasai
@Override
public void validate(Object target, Errors errors) {
// TODO Auto-generated method stub
Student s = (Student) target;
ValidationUtils.rejectIfEmpty(errors, "nric", "NRIC can be empty");
ValidationUtils.rejectIfEmpty(errors, "name", "Name cant be empty");
System.out.println(s.toString());
}
19
View Source File : LecturerValidator.java
License : The Unlicense
Project Creator : suriarasai
License : The Unlicense
Project Creator : suriarasai
@Override
public void validate(Object target, Errors errors) {
// TODO Auto-generated method stub
}
See More Examples