springmvc的PUT請求和DELETE請求
阿新 • • 發佈:2018-12-18
springmvc 支援rest風格 一般我們傳送請求 都是get請求或post請求 而rest風格告訴我們
- 通過GET請求獲取資源
- 通過POST請求 新增資源
- 通過PUT請求修改資源
- 通過DELETE請求刪除資源
那麼 普通的springmvc搭建好之後 我們應該如何支援restful呢 web.xml中配置:
<!--4.使用Rest風格的URI,將頁面普通的post請求轉為指定的delete或put請求-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name >
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
< filter>
<filter-name>HttpPutFormContentFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HttpPutFormContentFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
get和post程式碼就不貼了 因為我們平常玩的就是get和post請求 PUT請求 ajax:
function pauseJob(jobName,jobGroup) {
$.ajax({
url:url+"/quartz/pauseJob",
data:{jobName:jobName,jobGroup:jobGroup},
dataType:'json',
type:"PUT",
success:function (data) {
if (data.status=='success') {
window.location.reload();
}
}
});
}
後臺程式碼
@RequestMapping(value = "pauseJob", method = RequestMethod.PUT)
@ResponseBody
public String pauseJob(@RequestParam("jobName") String jobName, @RequestParam("jobGroup") String jobGroup) {
JSONObject jsonObject = new JSONObject();
if (StringUtils.isEmpty(jobName) || StringUtils.isEmpty(jobGroup)) {
jsonObject.put("status", "error");
} else {
quartzService1.pauseJob(jobName, jobGroup);
jsonObject.put("status", "success");
}
return jsonObject.toJSONString();
}
在傳送DELETE請求時 請求引數有多個 在用RequestParma接收的時候接收不到 因此我們用RequestBody接收請求 1.引入jackson-databind包 不引入會報Http415錯誤
<[email protected]支援-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
2.DELETE請求
function deleteJob(jobName,jobGroupName,triggerName,triggerGroupName) {
var jsonstr = {jobName:jobName,jobGroupName:jobGroupName,triggerName:triggerName,triggerGroupName:triggerGroupName};
$.ajax({
url:url+"/quartz/deleteJob",
data:JSON.stringify(jsonstr),
contentType:"application/json",
dataType:'json',
type:"DELETE",
success:function (data) {
if (data.status=='success') {
window.location.reload();
}
}
});
}
3.後臺:
@RequestMapping(value = "deleteJob", method = RequestMethod.DELETE)
@ResponseBody
public String deleteJob(@RequestBody TriggerEntity triggerEntity) {
JSONObject jsonObject = new JSONObject();
if (StringUtils.isEmpty(triggerEntity.getJobName()) || StringUtils.isEmpty(triggerEntity.getJobGroupName())
|| StringUtils.isEmpty(triggerEntity.getTriggerName()) || StringUtils.isEmpty(triggerEntity.getTriggerGroupName())) {
jsonObject.put("status", "error");
} else {
quartzService1.deleteJob(triggerEntity);
jsonObject.put("status", "success");
}
return jsonObject.toJSONString();
}