Spring MVC Controler层获取errors验证信息 同时返回

时间:2023-01-25 10:06:12
	/**
	 * spring 获取错误信息
	 * @param bindingResult
	 * @param request
	 * @return
	 */
	public static String[] getFiledMessage(BindingResult bindingResult,HttpServletRequest request) {
		
		WebApplicationContext webApplicationContext = RequestContextUtils.getWebApplicationContext(request, request.getSession().getServletContext());
		LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
		LocaleContext localeContext = ((LocaleContextResolver) localeResolver).resolveLocaleContext(request);
		Locale locale = localeContext.getLocale();
		
		String[] errorMessages = new String[bindingResult.getFieldErrors().size()];
		for (int i = 0; i < bindingResult.getFieldErrors().size(); i++) {
			ObjectError error = bindingResult.getFieldErrors().get(i);
			//获取字段列
//			String obj = ApplicationContextUtil.getMessage(error.getArguments()[0].toString());
			errorMessages[i] = webApplicationContext.getMessage(error, locale);
			//替换国际化
//			errorMessages[i].replace(error.getArguments()[0].toString(), obj);
		}
		return errorMessages;
	}


//将错误信息放入errors里边
validateEmpty("datastrunm", errors, "Datastru.datastrunm");

    /**
     * 非空验证
     * 
     * @param fieldName
     *            属性名称
     * @param errors
     * @param messageKey
     *            国际化属性名称
     */
    public void validateEmpty(String fieldName, Errors errors, String messageKey) {
        ValidationUtils.rejectIfEmpty(errors, fieldName, "common.constraints.empty.message",
                new Object[] { ApplicationContextUtil.getMessage(messageKey) }, fieldName);
    }