本文整理汇总了Java中org.springframework.validation.MapBindingResult类的典型用法代码示例。如果您正苦于以下问题:Java MapBindingResult类的具体用法?Java MapBindingResult怎么用?Java MapBindingResult使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
MapBindingResult类属于org.springframework.validation包,在下文中一共展示了MapBindingResult类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: shouldFailIfLoginFormIsNotValid
import org.springframework.validation.MapBindingResult; //导入依赖的package包/类
@Test
public void shouldFailIfLoginFormIsNotValid() {
//given
RedirectAttributesModelMap map = new RedirectAttributesModelMap();
MapBindingResult bindingResult = new MapBindingResult(new HashMap<String, Object>(), "loginForm");
bindingResult.addError(new FieldError("test", "test", "test"));
LoginForm loginForm = new LoginForm();
loginForm.setLoginFormUrl("url");
//when
String path = controller.login(loginForm, bindingResult, map, new MockHttpServletRequest(), new MockHttpServletResponse());
//then
assertEquals(bindingResult.getAllErrors(), map.getFlashAttributes().get("errors"));
assertEquals("redirect:url", path);
}
示例2: shouldFailRequestIfCannotLogin
import org.springframework.validation.MapBindingResult; //导入依赖的package包/类
@Test
public void shouldFailRequestIfCannotLogin() {
//given
RedirectAttributesModelMap map = new RedirectAttributesModelMap();
MapBindingResult bindingResult = new MapBindingResult(new HashMap<String, Object>(), "loginForm");
LoginForm loginForm = new LoginForm();
when(securityProvider.validate(any(LoginForm.class), any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(false);
//when
controller.login(loginForm, bindingResult, map, new MockHttpServletRequest(), new MockHttpServletResponse());
//then
assertTrue(map.getFlashAttributes().containsKey("errors"));
List<ObjectError> errors = (List<ObjectError>) map.getFlashAttributes().get("errors");
assertEquals("login.failed", errors.get(0).getCode());
assertTrue(errors.size() == 1);
}
示例3: testHasBindingErrorsModelAndViewElement
import org.springframework.validation.MapBindingResult; //导入依赖的package包/类
@Test
public void testHasBindingErrorsModelAndViewElement() {
MockHttpServletRequest request = new MockHttpServletRequest(RequestMethod.GET.name(), "/");
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext);
request.setAttribute(DispatcherServlet.INPUT_FLASH_MAP_ATTRIBUTE, new LinkedHashMap<String, Object>());
// Set servlet attributes in request context holder...
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
// Set BindingResult
BindingResult bindingResult = new MapBindingResult(new HashMap<String, Object>(), "form");
bindingResult.reject(null, "My Error");
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject(BindingResult.MODEL_KEY_PREFIX, bindingResult);
ModelAndViewElement modelAndViewElement = new ModelAndViewElement();
modelAndViewElement.setContent(modelAndView);
// Set variables
Map<String, Object> variables = new LinkedHashMap<>();
variables.put("content", modelAndViewElement);
// Build block
List<RenderedElement> elements = new LinkedList<>();
statusMessageBlock.build(elements, new HashMap<>(), variables);
assertTrue(!elements.isEmpty());
}
示例4: testHasBindingErrorsModelAndView
import org.springframework.validation.MapBindingResult; //导入依赖的package包/类
@Test
public void testHasBindingErrorsModelAndView() {
MockHttpServletRequest request = new MockHttpServletRequest(RequestMethod.GET.name(), "/");
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext);
request.setAttribute(DispatcherServlet.INPUT_FLASH_MAP_ATTRIBUTE, new LinkedHashMap<String, Object>());
// Set servlet attributes in request context holder...
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
// Set BindingResult
BindingResult bindingResult = new MapBindingResult(new HashMap<String, Object>(), "form");
bindingResult.reject(null, "My Error");
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject(BindingResult.MODEL_KEY_PREFIX, bindingResult);
// Set variables
Map<String, Object> variables = new LinkedHashMap<>();
variables.put("content", modelAndView);
// Build block
List<RenderedElement> elements = new LinkedList<>();
statusMessageBlock.build(elements, new HashMap<>(), variables);
assertTrue(!elements.isEmpty());
}
示例5: createRelationship
import org.springframework.validation.MapBindingResult; //导入依赖的package包/类
public String[] createRelationship(Integer personAId, Integer personBId, Integer relationshipTypeId, String startDateStr)
throws Exception {
PersonService ps = Context.getPersonService();
Person personA = ps.getPerson(personAId);
Person personB = ps.getPerson(personBId);
RelationshipType relType = Context.getPersonService().getRelationshipType(relationshipTypeId);
Relationship rel = new Relationship();
rel.setPersonA(personA);
rel.setPersonB(personB);
rel.setRelationshipType(relType);
if (StringUtils.isNotBlank(startDateStr)) {
rel.setStartDate(Context.getDateFormat().parse(startDateStr));
}
Map<String, String> map = new HashMap<String, String>();
MapBindingResult errors = new MapBindingResult(map, Relationship.class.getName());
new RelationshipValidator().validate(rel, errors);
String errmsgs[];
if (!errors.hasErrors()) {
ps.saveRelationship(rel);
errmsgs = null;
return errmsgs;
}
errmsgs = errors.getGlobalError().getCodes();
return errmsgs;
}
示例6: changeRelationshipDates
import org.springframework.validation.MapBindingResult; //导入依赖的package包/类
public boolean changeRelationshipDates(Integer relationshipId, String startDateStr, String endDateStr) throws Exception {
Relationship r = Context.getPersonService().getRelationship(relationshipId);
Date startDate = null;
if (StringUtils.isNotBlank(startDateStr)) {
startDate = Context.getDateFormat().parse(startDateStr);
}
Date endDate = null;
if (StringUtils.isNotBlank(endDateStr)) {
endDate = Context.getDateFormat().parse(endDateStr);
}
r.setStartDate(startDate);
r.setEndDate(endDate);
Map<String, String> map = new HashMap<String, String>();
MapBindingResult errors = new MapBindingResult(map, Relationship.class.getName());
new RelationshipValidator().validate(r, errors);
if (errors.hasErrors()) {
return false;
} else {
Context.getPersonService().saveRelationship(r);
return true;
}
}
示例7: testCsrWithInvalidRdnStructureOrder
import org.springframework.validation.MapBindingResult; //导入依赖的package包/类
@Test
public void testCsrWithInvalidRdnStructureOrder() throws Exception {
// Create the validator
CsrRequestValidationConfigParams params = new CsrRequestValidationConfigParams("UK", "eScience");
params.setRalistDao(this.createMockJdbcRalistDao("DL", "CLRC"));
PKCS10SubjectDNValidator validator = new PKCS10SubjectDNValidator(params);
Errors errors = new MapBindingResult(new HashMap<String, String>(), "csrPemStr");
// CSR DN has following order (this is invalid for our DB):
// CN=some valid body,L=DL,OU=CLRC,O=eScience,C=UK
String csrPemStr = this.getCsrRegularDnStructureOrder();
PKCS10_RequestWrapper.Builder builder = new PKCS10_RequestWrapper.Builder(CSR_Flags.Csr_Types.NEW, CSR_Flags.Profile.UKPERSON, csrPemStr, "[email protected]");
PKCS10_RequestWrapper csrWrapper = builder.build();
validator.validate(csrWrapper, errors);
assertTrue(errors.hasErrors());
//System.out.println("D: " + errors.getAllErrors().get(0).getDefaultMessage());
}
示例8: testInvalidRFC2253_RDN_Order
import org.springframework.validation.MapBindingResult; //导入依赖的package包/类
@Test
public void testInvalidRFC2253_RDN_Order()throws Exception {
CsrRequestValidationConfigParams params = new CsrRequestValidationConfigParams("UK", "eScience");
params.setRalistDao(this.createMockJdbcRalistDao("DL", "CLRC"));
PKCS10SubjectDNValidator validator = new PKCS10SubjectDNValidator(params);
Errors errors = new MapBindingResult(new HashMap<String, String>(), "csrPemStr");
// CSR DN has an invalid RFC2253 order:
// CN=some body,C=UK,L=DL,O=eScience,OU=CLRC
// Needs to be: (CN=val,L=val,OU=val,O=val,C=val)
String csrPemStr = this.getCsrIrregularOrderDN();
PKCS10_RequestWrapper.Builder builder = new PKCS10_RequestWrapper.Builder(CSR_Flags.Csr_Types.NEW, CSR_Flags.Profile.UKPERSON, csrPemStr, "[email protected]");
PKCS10_RequestWrapper csrWrapper = builder.build();
validator.validate(csrWrapper, errors);
assertTrue(errors.hasErrors());
//System.out.println("" + errors.getAllErrors().get(0).getDefaultMessage());
}
示例9: testPKCS10Validator
import org.springframework.validation.MapBindingResult; //导入依赖的package包/类
@Test
public void testPKCS10Validator() throws Exception {
String csrPemStr = this.getCsrIrregularOrderDN();
CsrRequestValidationConfigParams params = new CsrRequestValidationConfigParams("UK", "eScienceDev");
PKCS10Validator validator = new PKCS10Validator(params);
assertTrue(validator.supports(csrPemStr.getClass()));
Errors errors = new MapBindingResult(new HashMap<String, String>(), "csrPemStr");
validator.validate(csrPemStr, errors);
assertTrue(errors.hasErrors() == false);
validator.validate("invalid csr string", errors);
assertTrue(errors.hasErrors());
//System.out.println(errors.getAllErrors().get(0));
}
示例10: testConstructFromSpringErrors
import org.springframework.validation.MapBindingResult; //导入依赖的package包/类
@Test
public void testConstructFromSpringErrors() {
MessageCodesResolver mockMessageCodesResolver = mock(MessageCodesResolver.class);
when(mockMessageCodesResolver.resolveMessageCodes("default.blank.message", "foo", "bar", null)).thenReturn(new String[] {"Property [bar] cannot be blank"});
when(mockMessageCodesResolver.resolveMessageCodes("default.blank.message", "foo", "baz", null)).thenReturn(new String[] {"Property [baz] cannot be blank"});
MapBindingResult errors = new MapBindingResult(new HashMap(), "foo");
errors.setMessageCodesResolver(mockMessageCodesResolver);
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "bar", "default.blank.message");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "baz", "default.blank.message");
JsonCError jsonc = new JsonCError(errors);
assertThat(jsonc.getCode(), is("Property [bar] cannot be blank"));
assertThat(jsonc.getMessage(), is("Field error in object 'foo' on field 'bar': rejected value [null]; codes [Property [bar] cannot be blank]; arguments []; default message [null]"));
List<Map<String,Object>> errorList = jsonc.getErrors();
assertThat((String) errorList.get(0).get("code"), is("Property [bar] cannot be blank"));
assertThat((String) errorList.get(0).get("message"), is("Field error in object 'foo' on field 'bar': rejected value [null]; codes [Property [bar] cannot be blank]; arguments []; default message [null]"));
assertThat((String) errorList.get(1).get("code"), is("Property [baz] cannot be blank"));
assertThat((String) errorList.get(1).get("message"), is("Field error in object 'foo' on field 'baz': rejected value [null]; codes [Property [baz] cannot be blank]; arguments []; default message [null]"));
}
示例11: doValidate
import org.springframework.validation.MapBindingResult; //导入依赖的package包/类
@Override
protected void doValidate(Errors errors, Record target) {
super.doValidate(errors, target);
if (!errors.hasErrors()) {
// Получаем существующие МЕТА-поля справочника
Collection<MetaField> metaFields = metaFieldService.findAllByRelativeId(target.getDictionaryId(), null, true);
// Проверяем значение первичного ключа
doValidateMetaFields(errors, target, metaFields);
// Если нет ошибок, то проверяем значение полей
if (!errors.hasErrors()) {
Errors fieldErrors = new MapBindingResult(target.getFields(), retrieveTargetClass().getSimpleName());
doValidateFields(fieldErrors, target, metaFields);
errors.addAllErrors(fieldErrors);
}
}
}
示例12: succesfull_captcha_check
import org.springframework.validation.MapBindingResult; //导入依赖的package包/类
@Test
public void succesfull_captcha_check() {
mockRestServer.expect(requestTo(URL))
.andRespond(withSuccess("{\n" +
" \"success\": true,\n" +
" \"challenge_ts\": \"2016-01-01'T'12:12:1200\",\n" +
" \"hostname\": \"some\",\n" +
" \"error-codes\": []\n" +
"}",
MediaType.APPLICATION_JSON));
MapBindingResult bindingResult = bindingResult();
recaptchaVerifier.verify("response", bindingResult);
assertThat(bindingResult.hasErrors(), is(false));
}
示例13: failing_captcha_check
import org.springframework.validation.MapBindingResult; //导入依赖的package包/类
@Test
public void failing_captcha_check() {
mockRestServer.expect(requestTo(URL))
.andRespond(withSuccess("{\n" +
" \"success\": false,\n" +
" \"challenge_ts\": \"2016-01-01'T'12:12:1200\",\n" +
" \"hostname\": \"some\",\n" +
" \"error-codes\": [\"some\"]\n" +
"}",
MediaType.APPLICATION_JSON));
MapBindingResult bindingResult = bindingResult();
recaptchaVerifier.verify("response", bindingResult);
assertThat(bindingResult.getAllErrors(), hasSize(1));
FieldError fieldError = (FieldError) bindingResult.getAllErrors().get(0);
assertThat(fieldError.getObjectName(), is("followInitiative"));
assertThat(fieldError.getField(), is("recaptcha"));
assertThat(fieldError.getCode(), is("recaptcha.invalid"));
assertThat(bindingResult.hasErrors(), is(true));
}
示例14: testSubmitWithValidUser
import org.springframework.validation.MapBindingResult; //导入依赖的package包/类
@Test
public void testSubmitWithValidUser() {
MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
MockHttpServletResponse response = new MockHttpServletResponse();
Model uiModel = new ExtendedModelMap();
MockUser user = (MockUser) getApplicationContext().getBean("user");
user.setUserId(TEST_USER);
user.setPassword(TEST_PASSWORD);
MockHttpSession session = new MockHttpSession();
session.setAttribute(Constants.KME_MOCK_USER_KEY, user);
request.setSession(session);
BindingResult result = new MapBindingResult(new HashMap<String, String>(), new String());
String viewName;
try {
viewName = getController().submit(request, response, uiModel, user, result);
} catch (NullPointerException npe) {
LOG.error(npe.getLocalizedMessage(), npe);
viewName = null;
}
assertTrue("View name is incorrect.", REDIRECT_VIEW.equals(viewName));
}
示例15: testSubmitWithInvalidPassword
import org.springframework.validation.MapBindingResult; //导入依赖的package包/类
@Test
public void testSubmitWithInvalidPassword() {
MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
MockHttpServletResponse response = new MockHttpServletResponse();
Model uiModel = new ExtendedModelMap();
MockUser user = (MockUser) getApplicationContext().getBean("user");
user.setUserId(TEST_USER);
user.setPassword(INVALID);
MockHttpSession session = new MockHttpSession();
session.setAttribute(Constants.KME_MOCK_USER_KEY, user);
request.setSession(session);
BindingResult result = new MapBindingResult(new HashMap<String, String>(), new String());
String viewName;
try {
viewName = getController().submit(request, response, uiModel, user, result);
} catch (NullPointerException npe) {
LOG.error(npe.getLocalizedMessage(), npe);
viewName = null;
}
assertTrue("View name is incorrect.", LOGIN_VIEW.equals(viewName));
}