在映射到 Dto 類之前,我需要轉換兩個特定欄位。我從表格中獲得的資料:
userName: test
password: 123
active: N
enabled: N
external: N
id: -1
Dto類:
@Getter @Setter
public class UserDto {
protected Integer id;
protected String userName;
protected String password;
protected boolean active = false;
protected boolean enabled = true;
protected String external;
}
欄位active和enabled是布爾型別,但從表單中我得到“Y”或“N”字串值。原因,我有一個錯誤Failed to convert property value of type 'java.lang.String' to required type 'boolean' for property 'active'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [N]
我已經閱讀了關于 Сonverter<T,V> 和 PropertyEditors 的資訊,但我不確定它們是否對我有用,以及如何僅將其應用于 2 個特定欄位。
控制器:
@RequestMapping(value = "/user/save",method = RequestMethod.POST)
public ResponseEntity<String> saveUser(@ModelAttribute UserDto userDto, BindingResult bindingResultM, HttpServletRequest req) {
List<FieldError> errors = bindingResultM.getFieldErrors();
for (FieldError error : errors) {
log.error("bindingResultM: " error.getObjectName() " - " error.getDefaultMessage());
}
try {
userService.saveUserDto(userDto);
return new ResponseEntity<>("OK", HttpStatus.OK);
} catch (Exception e){
throw new ResponseException(e.getMessage(), HttpStatus.METHOD_FAILURE);
}
}
uj5u.com熱心網友回復:
因為您說您需要從表單中獲取資料以填充 UserDTO 物件,這是將String 型別轉換為其他型別的程序。
因此,您需要使用“org.springframework.core.convert.converter.Converter ”、“java.beans.PropertyEditor ”或“org.springframework.format.Formatter ”。這三個都可以完成將 String 型別轉換為其他型別或將其他型別轉換為 String 型別的作業。
但是PropertyEditor太復雜了,所以通常我們總是使用 Converter 或 Formatter,而這兩者可以在“ WebMvcConfigurer ”介面的“ default void addFormatters (FormatterRegistry registry){}”方法中設定。
但這是針對整個應用程式的,您只希望對UserDTO的“活動”和“啟用”欄位進行翻譯。
然后需要使用“org.springframework.web.bind.annotation.InitBinder ”,具體方法引數可以在Controller內部定義。“ @InitBinder ”的“ userDTO ”表示資料系結器僅用于此Controller內部的“ userDTO ”方法引數。(這個名字是區分大小寫的,所以如果你在方法中“userDto”,你需要在@InitBinder注解中將它改為userDto。)在這個方法中,你可以只為“ active ”和“ enabled ”指定Formatter欄位,通過使用此方法:
public void addCustomFormatter(Formatter<?> formatter, String... fields){}
當然你可以為這兩個欄位指定Converter ,但是在“WebDataBinder”類中并沒有直接的方法。因此,使用Formatter更容易。
@InitBinder("userDTO")
public void forUserDto(WebDataBinder binder) {
binder.addCustomFormatter(new BooleanFormatter(), "active", "enabled");
}
這是 BooleanFormatter 類:
public class BooleanFormatter implements Formatter<Boolean>{
@Override
public String print(Boolean object, Locale locale) {
if (object) {
return "Y";
}
return "N";
}
@Override
public Boolean parse(String text, Locale locale) throws ParseException {
if (text.equals("Y")) {
return true;
}
return false;
}
}
uj5u.com熱心網友回復:
在您的 DTO 上,您可以使用以下命令注釋布爾欄位:
@JsonDeserialize(
using = BooleanDeserializer.class
)
protected boolean enabled;
并創建反序列化器:
public class BooleanDeserializer extends JsonDeserializer<Boolean> {
public Boolean deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
String booleanValue = StringUtils.trimToEmpty(jsonParser.getText().trim());
return BooleanUtils.toBoolean(booleanValue, "Y", "N");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425487.html
