SpringMVC最主要的一个功能就是设计接口,并提供给其他应用程序访问,如前端客户端等。RESTful接口是一种接口设计风格,也是一种设计规范,目前在项目开发中已经越来越流行。比如RESTful建议请求需要区分GET、POST、PUT等;返回的数据建议是JSON;网络协议使用https;请求url包含版本号等等。在本篇博客中,我们将会基于SpringMVC框架来设计第一个RESTful接口。本文案例代码上传至:https://github.com/chenyufeng1991/StartSpringMVC.git 。
(1)首先为了项目构架,建议创建一个controller报名,把所有的controller都放入到这个路径下。这里会大量使用到Spring注解。创建一个控制器如下:
1 2 3 4 | @Controller public class BasketballController { } |
使用@Controller表示这是一个Spring中的控制器。
(2)创建一个Student类,需要创建setter、getter方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public class Student { String name; String age; public Student(String name, String age) { this .name = name; this .age = age; } public String getName() { return name; } public void setName(String name) { this .name = name; } public String getAge() { return age; } public void setAge(String age) { this .age = age; } } |
(3)在Controller中编写接口,这里供设计了三个接口,分别返回字符串,JSON对象,JSON数组:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | @Controller @RequestMapping ( "basketball" ) //请求的路径 public class BasketballController { /** * 直接返回字符串 * @param teamname * @param request * @return */ //请求的路径,方式 @RequestMapping (value = "v1.0/new/{teamname}" , method = RequestMethod.GET) @ResponseBody public String foo4( @PathVariable String teamname, HttpServletRequest request) { //可以使用teamname获取url路径分隔 //获取请求的参数 String name = request.getParameter( "name" ); String age = request.getParameter( "age" ); Student student = new Student(name, age); return "123456" ; } /** * 直接返回对象,自动转化为JSON格式 * @param teamname * @param request * @return */ @RequestMapping (value = "v2.0/new/{teamname}" , method = RequestMethod.GET) @ResponseBody public Student foo5( @PathVariable String teamname, HttpServletRequest request) { //可以使用teamname获取url路径分隔 //获取请求的参数 String name = request.getParameter( "name" ); String age = request.getParameter( "age" ); Student student = new Student(name, age); return student; } /** * 直接返回List,自动转化为JSON格式 * @param teamname * @param request * @return */ @RequestMapping (value = "v3.0/new/{teamname}" , method = RequestMethod.GET) @ResponseBody public List<Student> foo6( @PathVariable String teamname, HttpServletRequest request) { //可以使用teamname获取url路径分隔 //获取请求的参数 String name = request.getParameter( "name" ); String age = request.getParameter( "age" ); Student student = new Student(name, age); Student student1 = new Student(name + name, age + age); List<Student> list = new ArrayList<Student>(); list.add(student); list.add(student1); return list; } } |
(4)运行程序,别忘了配置Tomcat,使用Postman进行接口测试,分别对上面的三个接口请求:
经过测试,请求结果符合预期,我们已经完成了接口的编写、部署和测试。其他复杂的业务逻辑都可以在上面的基础上进行开发。感兴趣的同学可以更深入的去了解RESTful,编写出更加良好的接口。