使用springboot开发一个最简单的restful风格的接口,加入依赖:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
定义Controller:
package com.zhihao.miao.controller;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
/**
* @GetMapping、@PostMapping 是spring4.3中的新特性
*
*/
@Controller
public class UserController {
private Logger logger = LoggerFactory.getLogger(getClass());
@RequestMapping(value="/user/home",method=RequestMethod.GET)
@ResponseBody
public String home(){
return "user home";
}
@GetMapping("/user/show")
@ResponseBody
public String show(){
return "user show";
}
//直接接收HttpServletRequest原生的Reuqest
@GetMapping("/user/edit")
@ResponseBody
public String edit(HttpServletRequest req){
return "user edit "+req.getRemoteHost();
}
/**
* 获取url的参数 /user/1, /user/2
*/
@GetMapping("/user/{id}")
@ResponseBody
public String display(@PathVariable("id")String id){
return "user display, id ="+id;
}
/**
* @RequestParam 注解默认是参数必须提供值
* defaultValue 设置默认值
*/
@PostMapping("/user/create")
@ResponseBody
public String create(@RequestParam(value="username",defaultValue="admin")String username,@RequestParam(value="password",required=false)String password){
return "user create,username="+username+",password="+password;
}
@DeleteMapping("/user/deleteUserById/{id}")
public String deleteUserById(@PathVariable("id") String id){
return "删除id为:"+id+"的用户";
}
@PutMapping("/puttingById/{id}")
public String puttingById(@PathVariable("id") String id){
logger.info("id====="+id);
return id;
}
}
spring4.3版本出现了@GetMapping,@PostMapping,@DeleteMapping,@PutMapping等注解,可以更加细粒度的反应请求的方式(代替@RequestMapping)。
启动类启动:
package com.zhihao.miao;
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);
}
}
打印结果,项目中的请求url打印出来,默认项目启动端口是8080.
响应的get,post,delete,put请求就不测试了,太简单了。
@RestController注解
从上面的demo可以看出,我们每个方法都要加上@ResponseBody,spring4.0提供 了一个新的注解,@RestController注解(是@Controller和@ResponseBody二个注解的结合),列子如下,定义RoleController:
@RestController
public class RoleController {
@GetMapping("/role/show")
public String show(){
return "role show";
}
}
启动项目进行测试,这里也不测试了。