【发布时间】:2015-09-22 12:42:55
【问题描述】:
我正在使用弹簧靴和弹簧 MVC。我正在创建一个简单的表单(CRUD) 这是代码:
@Document
public class User
{
@Id
private ObjectId id;
@Indexed(unique=true)
@NotNull
@Size(min=2, max=30)
private String username;
@NotNull
@Size(min=2, max=30)
private String password;
private List<String> roles;
...
控制器:
@Controller
@RequestMapping("/admin")
public class AdminController {
...
/**
* NEW USER (POST)
*/
@RequestMapping(value = "new", method = RequestMethod.POST)
public ModelAndView newUser(@Valid User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return new ModelAndView("/admin/new");
}
user.setRoles(Arrays.asList(Constants.ROLE_ADMIN));
ur.save(user);
return new ModelAndView("redirect:/admin");
}
/**
* NEW USER (VIEW)
*/
@RequestMapping(value = "new", method = RequestMethod.GET)
public ModelAndView newUser(User user) {
ModelAndView mv = new ModelAndView("admin/new");
return mv;
}
...
}
和视图:
<form name="new" th:action="@{/admin/new}" th:object="${user}" method="post">
<table>
<tr th:if="${error != null}">
<td colspan="4">
<span th:text="${error}"></span>
</td>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="username" autocomplete="off"/></td>
<td width="10"/>
<td th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" autocomplete="off"/></td>
<td width="10"/>
<td th:if="${#fields.hasErrors('password')}" th:errors="*{password}"></td>
</tr>
<tr>
<td><button type="submit">Create</button></td>
</tr>
</table>
</form>
如果我输入的用户名大于 30 个字符,它就可以工作。
但是如果我从存储库中获得异常,例如: 来自 mongodb 存储库的 DuplicateKey 无效。
所以我试着把这段代码放在控制器中:
@ExceptionHandler(Exception.class)
public ModelAndView handleCustomException(Exception ex) {
ModelAndView model = new ModelAndView("admin/new");
model.addObject("error", ex.getMessage());
return model;
}
它处理所有异常,但此时我没有“用户”或“绑定结果”,当它尝试渲染时出现此错误:
2015-09-22 13:36:55.498 ERROR 6208 --- [nio-8080-exec-8] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#fields.hasErrors('username')" (admin/new:21)] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'user' available as request attribute
我做错了什么? 我应该如何处理这种异常? 有没有办法将 USER 发送到 ExceptionHandler?
谢谢。
【问题讨论】:
标签: spring mongodb spring-mvc exception thymeleaf