SpringMVC结合Ajax使用Restful风格实现前后端分离
程序员文章站
2024-03-21 21:17:52
...
传输数据类型为Json格式:
1.在web.xml中开启put,和delete的支持:
<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>
2.导入jackson的jar包:
<!-- jackson begin -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.3</version>
</dependency>
<!-- jackson end -->
3.Controller配置:由于从前端页面接收的字符串格式为Json格式,所以在后台Controller中使用对象接收时要在参数前使用@RequestBody,否则会报415错误。关于@RequestBody的用法请见 点击打开链接 @RestController
@RequestMapping(value="user")
public class LoginController {
@RequestMapping(value="/manage", method=RequestMethod.POST)
public String add(@RequestBody User user) {
System.out.println("post: username----" + user.getUsername());
System.out.println("post: password----" + user.getPassword());
if(StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
return "failed";
}
return "success";
}
@RequestMapping(value="/manage", method=RequestMethod.PUT)
public String update(@RequestBody User user) {
System.out.println("put: username-------" + user.getUsername());
System.out.println("put: password-------" + user.getPassword());
if(StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
return "failed";
}
return "success";
}
@RequestMapping(value="/manage", method=RequestMethod.DELETE)
public String delete(@RequestBody User user) {
System.out.println("delete: username-------" + user.getUsername());
System.out.println("delete: password-------" + user.getPassword());
if(StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
return "failed";
}
return "success";
}
}
4.前端页面,在发送一个put/delete请求的时候,我们需求添加一个隐藏域: <form id="login_form">
<input type="hidden" name="_method" value="put"/>
<input name="username" id="username"/>
<input id="submit" type="button">
</form>
<form id="login_form">
<input type="hidden" name="_method" value="delete"/>
<input name="username" id="username"/>
<input id="submit" type="button">
</form>
5.ajax中的写法: $.ajax({
type: "post",
url: "xxx",
contentType: "application/json",
data: JSON.stringify({username: $('#username').val()}),
success: function(result){
//此处省略
},
error: function(result){
//此处省略
}
});