准备一: web.xml
这里只需要增加一个REST的支持
准备二: rest-servlet.xml
启用注解扫描,以及扫描controller
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
default-lazy-init="true">
<!-- 通过mvc:resources设置静态资源,这样servlet就会处理这些静态资源,而不通过控制器 -->
<!-- 设置不过滤内容,比如:css,jquery,img 等资源文件 -->
<mvc:resources location="/*.html" mapping="/**.html" />
<mvc:resources location="/css/*" mapping="/css/**" />
<mvc:resources location="/js/*" mapping="/js/**" />
<mvc:resources location="/images/*" mapping="/images/**" />
<!-- 添加注解驱动 -->
<mvc:annotation-driven />
<!-- 默认扫描的包路径 -->
<context:component-scan base-package="rest.controller" />
<!-- mvc:view-controller可以在不需要Controller处理request的情况,转向到设置的View -->
<!-- 像下面这样设置,如果请求为/,则不通过controller,而直接解析为/index.jsp -->
<mvc:view-controller path="/" view-name="index" />
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<!-- 配置jsp路径前缀 -->
<property name="prefix" value="/"></property>
<!-- 配置URl后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
准备三: controller
package rest.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import net.sf.json.JSONObject;
@Controller
@RequestMapping("/restcontroller")
public class RestController {
@RequestMapping(value = "/usersid/{id}", method = RequestMethod.GET
, produces = "application/json;charset=UTF-8")
public @ResponseBody String selectById(@PathVariable("id") Integer id) {
System.out.println("查找id为: " + id);
UserModel userModel = new UserModel();
userModel.setId(1);
userModel.setName("zhangxu");
userModel.setCipher("man");
JSONObject jsonObject = new JSONObject();
jsonObject.put("data", userModel);
System.out.println(jsonObject);
return jsonObject.toString();
}
@RequestMapping(value = "/usersname/{name}", method = RequestMethod.POST
, produces = "application/text;charset=UTF-8")
public @ResponseBody String selectByName(@PathVariable("name") String name) {
System.out.println("查找name为: " + name);
return "查找" + name + ",这是返回结果String";
}
@RequestMapping(value = "/userspage", method = RequestMethod.POST
, produces = "application/json;charset=UTF-8")
public @ResponseBody String getDataFromPage(UserModel userModel) {
JSONObject fromObject = JSONObject.fromObject(userModel);
System.out.println("获取json数据"+fromObject.toString());
return fromObject.toString();
}
}
这里有几个地方需要注意:
- 界面中使用的请求方法要与controller对应
- 占位符表示此处为参数, 有多少个参数应该使用多少个/{}去接收, @PathVariable("")指明后面的传递参数接收的是哪个占位符对应的值.
- 视图传递json数据可以使用对应的实体类去接收
- 以上第二个是rest的一个特点
还需要增加一个实体类
package rest.controller;
public class UserModel {
private Integer id;
private String name;
private String cipher;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public String getCipher() {
return cipher;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setCipher(String cipher) {
this.cipher = cipher;
}
}
最后: 写个ajax请求
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="http://unpkg.com/jquery@3.3.1/dist/jquery.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>欢迎</title>
</head>
<body>
<h1>Hello RESTful!</h1>
<hr>
<h2>按照id查找,返回json格式: </h2>
<span id="span1" style="background-color: yellow;"></span>
<hr>
<h2>按照name查找,返回String格式: </h2>
<span id="span2" style="background-color: yellow;"></span>
<hr>
<h2>发送JSON, 返回JSON格式: </h2>
<span id="span3" style="background-color: yellow;"></span>
</body>
<script type="text/javascript">
$.ajax({
url:'/SpringDemo/restcontroller/usersid/1'
, type: 'get'
, dataType: 'json'
, async: true
, success: function(data){
$("#span1").text(JSON.stringify(data))
}
})
$.ajax({
url:'/SpringDemo/restcontroller/usersname/zhangxu'
, type: 'post'
, dataType: 'text'
, async: true
, success: function(data){
$("#span2").text(data)
}
})
var data = {id: 2, name:'sunhongluan', cipher: 'female'}
$.ajax({
url:'/SpringDemo/restcontroller/userspage/'
, type: 'post'
, data: data
, dataType: 'json'
, async: true
, success: function(data){
$("#span3").text(JSON.stringify(data))
}
})
</script>
</html>
验证
刷新一下页面,可以看到,页面出现的信息
参考
如何给老婆解释什么是RESTful:
https://zhuanlan.zhihu.com/p/30396391?group_id=937244108725641216(推荐)
REST,以及RESTful的讲解:
https://blog.csdn.net/qq_21383435/article/details/80032375(这篇文章的参考值得一看)