使用 SpringMVC 标签库在 JSP 中创建了一个在线表单。我的表单的控制器是一个 RESTful Web 服务。
RESTful Web 服务有两个调用:
(1) http://localhost:8080/myapp/applications/new
这会在浏览器中打开在线表单(这可行)。
(2) http://localhost:8080/myapp/applications/create
这会将表单数据保存到数据库(处理提交)。这就是它破裂的地方。
遵循 Spring Framework 附带的示例演示 petclinic 应用程序中的约定。
在线表格:
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<body>
<form:form modelAttribute="application" method="POST" action="create">
<table>
<tr>
<td>Name:</td>
<td><form:input path="name" size="30" maxlength="80"/></td>
</tr>
<tr>
<td>Description:</td>
<td><form:input path="description" size="30" maxlength="80"/></td>
</tr>
<tr>
<td>Image URL:</td>
<td><form:input path="imgUrl" size="30" maxlength="80"/></td>
</tr>
</table>
<input type="submit" value="Save" />
</form:form>
</body>
</html>
用作表单控制器的 RESTful Web 服务:
@Controller
@Path(ApplicationsResource.APPLICATION_URL)
public class ApplicationsResource
{
private final Logger log =
LoggerFactory.getLogger(ApplicationsResource.class);
public static final String APPLICATION_URL = "/applications";
@Autowired
private ApplicationManager applicationManager;
@Autowired
private ProfileManager profileManager;
@POST
@Path("create")
@Produces(MediaType.TEXT_HTML)
public Model getNewApplication(@Context HttpServletRequest request,
@RequestAttribute Model model)
{
Application app = new Application();
model.addAttribute("application", app);
try
{
if ("POST".equalsIgnoreCase(request.getMethod()))
{
if (app != null)
{
applicationManager.save(app);
log.info("Added application: " + app.getName());
}
else
{
log.info("Application not added");
}
}
}
catch (Exception e)
{
log.info("Exception: ", e);
throw new
WebApplicationException(Response.status(
RestError.SERVER_ERROR_HTTP_RESP).
type("application/json;charset=utf-8").
entity(new ErrorOutput(RestError.SERVER_ERROR_CODE, RestError.SERVER_ERROR_MSG, e.toString())).build());
}
return model;
}
@InitBinder
public void setAllowedFields(WebDataBinder dataBinder)
{
dataBinder.setDisallowedFields(new String[] {"id"});
}
@GET
@Path("new")
@Produces( { MediaType.TEXT_HTML })
public ModelAndView getNewApplicationForm()
{
log.info("ApplicationsResource - Inside getNewApplicationForm");
ModelAndView mv = new ModelAndView("/applications/applications_new");
mv.addObject("application", new Application());
return mv;
}
}
单击提交时抛出异常:
执行 POST /applications/create org.jboss.resteasy.spi.BadRequestException 失败:
找不到以下类型的消息正文阅读器:
interface org.springframework.ui.Model of content type: application/x-www-form-urlencoded at
org.jboss.resteasy.core.MessageBodyParameterInjector$1 createReaderNotFound(MessageBodyParameterInjector.java:73)
有谁知道我为什么会得到这个例外?
如果有人可以帮助我解决这个问题,我将不胜感激......
编程愉快,感谢您抽出宝贵时间阅读本文。