假設我有一個具有基於Hibernate的持久層的Spring 4 Web應用程序。我想創建一個支持我的模型的基本CRUD操作的RestController
。創建讀取記錄的方法可以毫無困難地工作:將JSON映射到Spring REST控制器中的Hibernate模型
@RequestMapping(value = "/stuff/list", method = RequestMethod.GET)
public List<Stuff> getStuff(){
return stuffService.findAll();
}
Jackson處理對象序列化,沒問題。但是如果我想添加一個通過POST請求創建新記錄的方法呢?有沒有簡單的方法來支持這種簡單的方法?
@RequestMapping(value = "/stuff/new", method = RequestMethod.POST)
public Integer getStuff(@RequestParam("stuff") Stuff stuff){
return stuffService.save(stuff);
}
是這樣的可能嗎?或者我需要手動將發佈的表單數據映射到新對象?
SOLUTION
這是我如何解決我的問題,有一對夫婦的步驟。首先,我的最終控制方法:
@RequestMapping(value = "/stuff/new", method = RequestMethod.POST)
public Integer getStuff(@RequestBody Stuff stuff){
return stuffService.save(stuff);
}
我已經有適用於所有應用程序的請求API過濾器,允許跨源資源共享,但需要修改,這允許請求指定內容類型:
public class SimpleCORSFilter implements Filter{
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override public void init(FilterConfig filterConfig) throws ServletException { }
@Override public void destroy() { }
}
被註冊在我的web.xml
文件:當我提出一個要求,如下面的一個
<filter>
<filter-name>cors</filter-name>
<filter-class>com.company.app.util.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/api/*</url-pattern>
</filter-mapping>
現在,它將正確映射我提交了JSON到我的模型並堅持一個新的實例:
var stuff = {
name: "Some stuff",
description: "This is some stuff."
}
$.ajax({
url: url,
method: "post",
dataType: "json",
data: JSON.stringify(stuff),
contentType: "application/json"
}).done(function(data){
console.log(data);
}).fail(function(x, status, e){
console.log(e);
});
內容是HTML表單POST還是JSON? – Affe 2014-08-28 17:28:53
@Affe:JSON,通過瀏覽器AJAX請求或Spring'RestTemplate'發送。 – woemler 2014-08-28 17:30:33