SpringBoot中的获得与职位请求怎么利用rest式服务实现?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
<强> 1。得到请求、url传参,返回json。强>
先准备一个请求后,响应的对象。
包com.example.demo; 公共类回波{ 私人最终长id; 私人最终字符串内容; 公共回波(长id字符串内容){ 这一点。id=id; 这一点。内容=内容; } 公共长getId () { 返回this.id; } 公共字符串getContent () { 返回this.content; } }
准备一个用来接收请求的EchoController(名字可以根据实际情况写),为它增加@RestController注解,表示这是一个处理RESTful请求的响处理类。
增加@RequestMapping,为本控制器提供一个根url,当然可以不写,写这个是为了更好的将同一种处理的url归在一类,本控制器其他的处理方法对应的url中就不需要重复写。
包com.example.demo; 进口java.util.concurrent.atomic.AtomicLong; 进口org.springframework.web.bind.annotation.RequestMapping; 进口org.springframework.web.bind.annotation.RequestParam; 进口org.springframework.web.bind.annotation.RestController; 进口org.springframework.web.bind.annotation.RequestBody; 进口org.springframework.web.bind.annotation.RequestMethod; 进口org.springframework.web.bind.annotation.PathVariable; 进口org.springframework.web.bind.annotation.ModelAttribute; @RestController @RequestMapping (“/echo") 公开课EchoController { 私有静态最终字符串echoTemplate1=笆盏? s !“; 私有静态最终字符串echoTemplate2=? s % s说话\ & # 39;% s \ & # 39;“; 私人最终AtomicLong counter=新AtomicLong (); @RequestMapping (value=https://www.yisu.com/zixun/癵etter/pattern1”方法=RequestMethod.GET) 公共回声getterPattern1(字符串内容){ 返回新的回波(counter.incrementAndGet(),字符串。格式(echoTemplate1、内容)); } @RequestMapping (value="/getter/pattern2”、方法=RequestMethod.GET) 公共回声getterPattern2 (@RequestParam (value=澳谌荨?要求=false)字符串别名){ 返回新的回波(counter.incrementAndGet(),字符串。格式(echoTemplate1、别名)); } }
getterPattern1的上面增加了@RequestMapping注解,将指定的url和处理的方法进行映射,对应这个url的请求就由该方法来处理,方法可以省略,省略后就是对应所有的Http卫理公会教徒,gtterPatten1方法的参数默认就和url中的内容参数进行映射。
再看getterPattern2,跟上面的方法效果一致,他们的区别就在于参数定义用了@RequestParam注解将url参数和方法参数进行了映射说明,@RequesteParam中值的值就是url中实际的参数,需要说明该参数是否必须,如果是真的,而实际上url中并没有带上该参数,那么会报异常,为防止异常可以增加defaultValue指定参数的默认值即可。我们会发现这里的方法参数是别名,这里当然是可以和url的参数名不同,只要RequestParam注解映射了他们的关系就没问题。
运行后,可以在浏览器中访问对应的url来看看结果,我这里是用curl来访问。
curl http://localhost: 8080/echo/getter/pattern1& # 63;内容=你好
curl http://localhost: 8080/echo/getter/pattern2& # 63;内容=
你好,上面两个url的访问得到的结果除了id会自增外,其他是一致的:
{“id": 6“content":“收到你好!“}
在EchoController中增加一个响应方法。
@RequestMapping(值=https://www.yisu.com/zixun/?getter/pattern3/{内容}”,方法=RequestMethod.GET) 公共回声getterPattern3 (@PathVariable字符串内容){ 返回新的回波(counter.incrementAndGet(),字符串。格式(echoTemplate1、内容)); }
可以看的到,在@RequestMapping的url定义中的末尾有“{内容}”,表明这里是一个路径参数,在getterPattern3的参数内容增加了@PathVariable注解,将方法参数与路径参数进行了映射。
运行后,访问url。
curl http://localhost: 8080/echo getter/pattern3/123456
结果:
{“id": 8“content":“收到123456 !“}
先定义一个提交的Json对应的对象,这里把它定义为消息。
包com.example.demo; 公开课信息{ 私人的字符串; 私人字符串; 私人字符串内容; 公共消息(){} 公共字符串getFrom () { 返回this.from; } 公共字符串文字(){ 返回this.to; } 公共字符串getContent () { 返回this.content; } 公共空间setFrom(字符串值){ this.from=价值; } 公共空间太空站(字符串值){ 这一点。=价值; } 公共空间setContent(字符串值){ 这一点。内容=价值; } }SpringBoot中的获得与职位请求怎么利用rest式服务实现