26.SpringBoot构建Restful service完成Get和Post请求

本文介绍了如何使用SpringBoot构建RESTful服务,处理GET和POST请求。通过示例展示了GET请求中URL参数和路径参数的使用,以及POST请求中提交JSON和表单数据的方法。

SpringBoot构建Restful service完成Get和Post请求

       一个基本的RESTfule service最经常向外提供的请求Method就是GetPost

Get中,常用的都会在请求上带上参数,或者是路径参数。响应Json

Post中,常用的会提交form data或者json data作为参数,响应Json

1.    Get请求,url传参,返回json

准备一个请求后,响应的对象。

packagecom.example.demo;

publicclassEcho{

  privatefinallongid;

  privatefinalStringcontent;

  publicEcho(longid,String content) {

    this.id= id;

    this.content= content;

  }

  publiclonggetId(){

    returnthis.id;

  }

  publicStringgetContent() {

    returnthis.content;

  }

}

准备一个用来接收请求的EchoController(名字可以根据实际情况写),为它增加@RestController注解,表示这是一个处理RESTful请求的响处理类。

增加@RequestMapping,为本Controller提供一个根url,当然可以不写,写这个是为了更好的将同一种处理的url归在一类,本Controller其他的处理方法对应的url中就不需要重复写。

@RestController

@RequestMapping("/echo")

publicclassEchoController{

  privatestaticfinalStringechoTemplate1 = "received %s!";

  privatestaticfinalStringechoTemplate2 = "%s speak to %s \'%s\'";

  privatefinalAtomicLongcounter = newAtomicLong();

  @RequestMapping(value="/getter/pattern1",method=RequestMethod.GET)

  publicEchogetterPattern1(String content) {

    returnnewEcho(counter.incrementAndGet(),String.format(echoTemplate1, content));

  }

  @RequestMapping(value="/getter/pattern2",method=RequestMethod.GET)

  publicEchogetterPattern2(@RequestParam(value="content", required=false) Stringalias) {

    returnnewEcho(counter.incrementAndGet(),String.format(echoTemplate1, alias));

  }

}

getterPattern1的上面增加了@RequestMapping注解,将指定的url和处理的方法进行映射,对应这个url的请求就由该方法来处理,method可以省略,省略后就是对应所有的Http MethogtterPatten1方法的参数默认就和url中的content参数进行映射。

getterPattern2,跟上面的方法效果一致,他们的区别就在于参数定义用了@RequestParam注解将url参数和方法参数进行了映射说明@RequesteParamvalue的值就是url中实际的参数,required说明该参数是否必须,如果是true,而实际上url中并没有带上该参数,那么会报异常,为防止异常可以增加defaultValue指定参数的默认值即可。我们会发现这里的方法参数是alias,这里当然是可以和url的参数名不同,只要RequestParam注解映射了他们的关系就没问题。

运行后,可以在浏览器中访问对应的url来看看结果,我这里是用curl来访问。

curl http://localhost:8080/echo/getter/pattern1?content=hello
curl http://localhost:8080/echo/getter/pattern2?content=hello

 上面两个url的访问得到的结果除了id会自增外,其他是一致的:

{"id":6,"content":"receivedhello!"}

 2. Get请求,传递url路径参数,返回json

EchoController中增加一个响应方法。

@RequestMapping(value="/getter/pattern3/{content}",method=RequestMethod.GET)

publicEchogetterPattern3(@PathVariableString content) {

  returnnewEcho(counter.incrementAndGet(),String.format(echoTemplate1, content));

}可以看到,在@RequestMappingurl定义中的末尾有“{content}”,表明这里是一个路径参数,在getterPattern3的参数content增加了@PathVariable注解,将方法参数与路径参数进行了映射。

运行后,访问url

curl http://localhost:8080/echo/getter/pattern3/123456

结果:

{"id":8,"content":"received123456!"}

3.Post请求,参数以Http body的途径提交Json数据。

先定义一个提交的Json对应的对象,这里把它定义为Message

packagecom.example.demo;

publicclassMessage{

  privateStringfrom;

  privateStringto;

  privateStringcontent;

  publicMessage(){}

  publicStringgetFrom() {

    returnthis.from;

  }

  publicStringgetTo() {

    returnthis.to;

  }

  publicStringgetContent() {

    returnthis.content;

  }

  publicvoidsetFrom(Stringvalue) {

    this.from =value;

  }

  publicvoidsetTo(Stringvalue) {

    this.to = value;

  }

  publicvoidsetContent(Stringvalue) {

    this.content =value;

  }

}

EchoController增加响应的方法,并完成映射。

@RequestMapping(value="/setter/message1",method=RequestMethod.POST)

publicEchosetterMessage1(@RequestBody Message message) {

  returnnewEcho(counter.incrementAndGet(),String.format(echoTemplate2, message.getFrom(), message.getTo(),message.getContent()));

}

setterMessage1方法的参数中用@RequestBody将请求的Http Body和参数messge进行了映射。

运行后,使用curl向服务端提交json数据。提交的请求头部要带上"Content-Type:application/json",表明请求体Json

curl-i -H "Content-Type:application/json"-d"{\"from\":\"Tom\",\"to\":\"Sandy\",\"content\":\"hellobuddy\"}"http://localhost:8080/echo/setter/message1

结果:

{"id":9,"content":"Tom speak toSandy 'hello buddy'"}

4.Post请求,参数以Http body的途径提交表单数据。

EchoController增加响应的方法,并完成映射。

@RequestMapping(value="/setter/message2",method=RequestMethod.POST)

public Echo setterMessage2(@ModelAttribute Message message) {

  return newEcho(counter.incrementAndGet(), String.format(echoTemplate2, message.getFrom(),message.getTo(), message.getContent()));

} 

setterMessage2方法的参数中用@ModelAttribute将请求的Http Body中的表单数据和参数messge进行了映射。

运行后,使用curl向服务端提交表单数据。提交的请求头部要带上"Content-Type:application/x-www-form-urlencoded",表明请求体是表单数据,格式是"key1=value1&key2=value2&key3=value

curl -i -H"Content-Type:application/x-www-form-urlencoded"-d"from=sandy&to=aissen&content=go to"http://localhost:8080/echo/setter/message2

 结果:

{"id":11,"content":"sandyspeak to aissen 'go to'"}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值