Запрос, отправленный клиентом, был синтаксически некорректным, возникает ошибка при попытке связать данные и отправить в контроллер
Я пытаюсь связать данные из формы JSP и отправить его на контроллер, чтобы сохранить.
форма:
<form:form method="post" modelAttribute="user" action="adduser">
<div class="form-group">
<label for="role-name" class="col-form-label">User Name</label>
<form:input type="text" required="required" class="form-control" id="role-name" path="username" />
</div>
<div class="form-group">
<label for="role-name" class="col-form-label">Name</label>
<form:input type="text" required="required" class="form-control" id="name" path="name" />
</div>
<div class="form-group">
<label for="role">Role</label>
<form:select class="form-control"
required="required" path="role" id="role">
<c:forEach items="${roles}" var="role">
<form:option value="${role}" label="${role.roleName}" />
</c:forEach>
</form:select>
</div>
<div class="form-group">
<label for="state">Status</label>
<form:select class="form-control" id="state"
required="required" path="state" >
<form:option value="ACTIVE" label="ACTIVE" />
<form:option value="INACTIVE" label="INACTIVE" />
</form:select>
</div>
<div class="form-group">
<label for="role-name" class="col-form-label">Password</label>
<form:input type="password" required="required" class="form-control" id="password" path="password" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form:form>
контроллер:
@RequestMapping(value = "adduser", method = RequestMethod.POST)
public ModelAndView saveUser(@ModelAttribute("user") SystemUser user, ModelMap model) {
userService.saveSystemUser(user);
model.addAttribute("user", new SystemUser());
return new ModelAndView("users");
}
модель:
@Entity(name = "system_user")
public class SystemUser implements Serializable {
public enum State {ACTIVE, INACTIVE}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@Column(name = "username", nullable = false)
private String username;
@Column(name = "name")
private String name;
@Enumerated(EnumType.STRING)
@Column(name = "state")
private State state;
@Column(name = "password", nullable = false)
private String password;
@JoinColumn(name = "role_id", nullable = false)
@ManyToOne(fetch = FetchType.EAGER)
private SystemRole role;
}
но я продолжаю получать сообщение об ошибке "Запрос, отправленный клиентом, был синтаксически неправильным" в браузере и nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'SystemRole' for property 'role': no matching editors or conversion strategy found]
в журнале. Здесь я также отправляю весь объект роли. но я продолжаю получать эти две ошибки, когда я пытаюсь сделать это. что могло пойти не так?
1 ответ
Из журналов ошибок ясно, что Spring не может преобразовать объект объекта Role.
Определите центральный класс для всех разговоров и конвертеров, как показано ниже.
@Configurable
/**
* A central place to register application converters and formatters.
*/
public class ApplicationConversionServiceFactoryBean extends FormattingConversionServiceFactoryBean {
@Autowired
RoleService roleService;
@SuppressWarnings("deprecation")
@Override
protected void installFormatters(FormatterRegistry registry) {
super.installFormatters(registry);
}
public Converter<Role, String> getRoleToStringConverter() {
return new Converter<com.package.Role, String>() {
@Override
public String convert(Role role) {
return new StringBuilder().append(role.getRoleName()).toString();
}
};
}
public Converter<Long, Role> getIdToRoleConverter() {
return new Converter<Long, com.package.Role>() {
@Override
public com.package.Role convert(Long id) {
return roleService.read(id);
}
};
}
public Converter<String, Role> getStringToRoleConverter() {
return new Converter<String, com.package.Role>() {
@Override
public com.package.Role convert(String id) {
return getObject().convert(getObject().convert(id, Long.class), Role.class);
}
};
}
public void installLabelConverters(FormatterRegistry registry) {
registry.addConverter(getRoleToStringConverter());
registry.addConverter(getIdToRoleConverter());
registry.addConverter(getStringToRoleConverter());
}
@Override
public void afterPropertiesSet() {
super.afterPropertiesSet();
installLabelConverters(getObject());
}
}
Но для того, чтобы Spring узнал об этом классе, вам нужно вставить приведенный ниже компонент в конфигурацию applicationContext.xml.
<bean class="com.package.ApplicationConversionServiceFactoryBean" id="applicationConversionService"/>
и зарегистрируйте класс обслуживания в конфигурации applicationContext.xml, как показано ниже.
<mvc:annotation-driven conversion-service="applicationConversionService"/>