您的位置:首页 > 编程语言 > Java开发

三、Spring Boot构建RESTful API

2017-04-11 22:04 441 查看

定义实体类

package com.lf.entity;

/**
* Created by LF on 2017/4/11.
*/
public class User {
private Long id;
private String name;
private Integer age;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}
}


RestfulController

package com.lf.web;

import com.lf.entity.User;
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.RestController;

/**
* Created by LF on 2017/4/11.
*/
@RestController
public class RestfulController {

@RequestMapping(value = "/user/{code}", method = RequestMethod.GET)
public User getUser(@PathVariable String code) {
//根据code查询
return new User();

}

@RequestMapping(value = "/user", method = RequestMethod.POST)
public void createUser(User user) {
//数据库添加
}

@RequestMapping(value = "/user/{code}", method = RequestMethod.PUT)
public void updateUser(@PathVariable String code, User user) {
//根据code更新用户
}

@RequestMapping(value = "/user/{code}", method = RequestMethod.DELETE)
public void deletUser(@PathVariable String code) {
//根据code删除一个用户
}

}


package com.lf;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}


@RestController

Spring4之后加入的注解,原来在@Controller中返回json需要@ResponseBody来配合,如果直接用@RestController替代.

至此,我们通过引入web模块(没有做其他的任何配置),就可以轻松利用Spring MVC的功能,以非常简洁的代码完成了对User对象的RESTful API的创建以及单元测试的编写。其中同时介绍了Spring MVC中最为常用的几个核心注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring RestContr