SpringMVC使用转换器从path变量加载对象,但需要返回404以查找未找到的对象
TL;DR-是否有方法在MVC数据绑定阶段从注册的类型转换器抛出错误,从而返回带有特定HTTP状态代码的响应?也就是说,如果我的转换器无法从转换源中找到对象,我可以返回404吗 我有一个POJO:SpringMVC使用转换器从path变量加载对象,但需要返回404以查找未找到的对象,spring,spring-mvc,spring-mvc-initbinders,Spring,Spring Mvc,Spring Mvc Initbinders,TL;DR-是否有方法在MVC数据绑定阶段从注册的类型转换器抛出错误,从而返回带有特定HTTP状态代码的响应?也就是说,如果我的转换器无法从转换源中找到对象,我可以返回404吗 我有一个POJO: public class Goofball { private String id = "new"; // others public String getName () { ... } public void setName (String name) { ... }
public class Goofball {
private String id = "new";
// others
public String getName () { ... }
public void setName (String name) { ... }
}
当“new”.equals(id)
时,我使用StringToFofBallConverter创建一个空对象,或者尝试从数据库加载一个Goofball(如果存在):
public Goofball convert(String idOrNew) {
Goofball result = null;
log.debug("Trying to convert " + idOrNew + " to Goofball");
if ("new".equalsIgnoreCase(idOrNew))
{
result = new Goofball ();
result.setId("new");
}
else
{
try
{
result = this.repository.findOne(idOrNew);
}
catch (Throwable ex)
{
log.error (ex);
}
if (result == null)
{
throw new GoofballNotFoundException(idOrNew);
}
}
return result;
}
当请求与此端点匹配时,spring将使用该转换器:
@RequestMapping(value = "/admin/goofballs/{goofball}", method=RequestMethod.POST)
public String createOrEditGoofball (@ModelAttribute("goofball") @Valid Goofball object, BindingResult result, Model model) {
// ... handle the post and save the goofball if there were no binding errors, then return the template string name
}
这一切都非常有效,因为对于创建新对象和编辑现有对象,获取对/admin/goobballs/new
和/admin/goobballs/1234
的请求在控制器中都能顺利工作。问题是,如果我发出一个带有假id的请求,这个id不是新的,也不存在于数据库中,我想返回404。当前转换器正在引发自定义异常:
@ResponseStatus(value= HttpStatus.NOT_FOUND, reason="Goofball Not Found") //404
public class GoofballNotFoundException extends RuntimeException {
private static final long serialVersionUID = 422445187706673678L;
public GoofballNotFoundException(String id){
super("GoofballNotFoundException with id=" + id);
}
}
但我从一个简单的IllegalArgumentException开始。无论哪种情况,结果都是Spring返回HTTP状态为400的响应
这让我觉得我误用了转换器接口,但这种方法
那么,问题又来了:有没有办法在数据绑定阶段从注册的类型转换器抛出一个错误,这样它将返回一个带有特定HTTP状态码的响应?回答我自己的问题: 将
stringTogofBallConverter
更改为仅为未找到的实体返回null
,而不是引发IllegalArgumentException
或自定义异常。然后将为@Controller
方法提供一个Goofball
对象,该对象具有null
id(例如,id既不是“新的”,也不是路径元素值)。此时,我可以在控制器方法中抛出一个GoofballNotFoundException
或任何其他@ResponseStatus
异常,以影响响应状态代码