小编最近的项目是好几个团队的一块合作,由于项目大,功能多,各个团队负责的东西不同,我的团队除了自己的开发前端和后端外,还负责给别的团队提供后端支持,在这里就用上了restful接口.
小编刚开始都是本本分分的做着自己的dubbo接口,后来被分了几个restful接口,之前没有写过restful接口,别人给讲了讲以后开始写dobbo接口的旅程.
为什么用restful接口?
怎么用呢?
restful接口常用的两种方式是get和post.下面简单介绍一下这两种方式的使用.
由于调用restful接口是通过url的方式来访问后端的代码.新建CustRegisterApi类以后,除了基本的注入外,还需要配置url的地址.以后的demo就在这个类里面写了.
<strong><span style="font-size:18px;">@RestController @RequestMapping(value = "/customer/register", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE }) @CrossOrigin(origins = "*") public class CustRegisterApi { @Autowired private HttpServletRequest request; @Autowired private HttpServletResponse response; }</span></strong>1:get方式,url地址会在地址栏显示出参数.
<strong><span style="font-size:18px;">/** * 检查邮箱是否已经绑定 * @param email 邮箱 * @return */ @RequestMapping(value = "/checkEmail", method = { RequestMethod.GET }) @ApiOperation(value = "检查邮箱是否已经绑定") public RestResponse<Boolean> checkEmail(@RequestParam(value = "email") String email) { RestResponse<Boolean> restResponse = null; try { boolean checkIsMailBinding = custService.checkIsMailBinding(email); // restResponse = new RestResponse<Boolean>(RestRespCode.OK, MessageUtil.getMessage(RestRespCode.OK), // checkIsMailBinding); if (checkIsMailBinding == false) { restResponse = new RestResponse<Boolean>(RestRespCode.REGISTER_USERNAME_EXISTED, MessageUtil.getMessage(RestRespCode.REGISTER_USERNAME_EXISTED), null); } else { restResponse = new RestResponse<Boolean>(RestRespCode.OK, MessageUtil.getMessage(RestRespCode.OK), null); } } catch (Exception e) { e.printStackTrace(); restResponse = new RestResponse<Boolean>(RestRespCode.INTERNAL_ERROR, MessageUtil.getMessage(RestRespCode.INTERNAL_ERROR), null); } return restResponse; }</span></strong>访问方式:http://localhost:8080(端口号)/模块名称/register/checkEmail?email=****
2:post方式,url地址会在地址栏不会显示出参数.
<strong><span style="font-size:18px;">/** * 修改密码 * @param memberId 用户编号 * @param oldPassword 旧密码 * @param newPassword 新密码 * @return * @throws Exception */ @RequestMapping(value = "/modifyPassword", method = RequestMethod.POST, consumes = "application/json") @ApiOperation(value = "修改支付密码") public RestResponse<Boolean> changePassword(@RequestBody CaptchaVO captchaVO) throws Exception { // 验证旧密码是否正确 Boolean findPassword = registerService.findPassword(captchaVO.getMemberId(), captchaVO.getOldPassword()); if (findPassword == false) { return new RestResponse<Boolean>(RestRespCode.PASSWORD_WRONG, MessageUtil.getMessage(RestRespCode.PASSWORD_WRONG), null); } return new RestResponse<Boolean>(RestRespCode.OK, MessageUtil.getMessage(RestRespCode.OK), null); }</span></strong>
post方式
是通过application/json;charset=utf-8来访问一级custom的方式来访问,一般是用于修改密码或者是不让别人看到参数的情况下用的post方式.
在测试的时候我是用火狐浏览器上的resteasy插件来进行测试的.