构建Spring Restful API请求参数解析

       编写Spring restful api接口是一个非常常用的手段来接受http请求服务,那么接收参数的方法以及使用Mock进行测试可以值得探究一下。


Spring Restfule API请求类型

1 无请求参数

没有请求参数,指定请求路径来接收相应的请求,举个简单的例子:

@RequestMapping("/c/manage/qcs/client")
@Controller
public class QcsClientManageController  {

    @RequestMapping(value="/list",method=RequestMethod.GET)
    public ModelAndView listConfigure() {
        ModelAndView mv = new ModelAndView();
        ...
        return mv;
    }
}
请求示例:{base}/c/manager/qcs/client/list

@RequestMapping:设置了请求的路由路径和方法。其是处理请求地址映射的注解,可用用类或者方法上。在类之上时,表示类中所有的方法对应的请求都是以该映射作为父地址。

@Controller:控制器,也就是Spring MVC里面的"C",也就是Controller。
value:方法对应的请求路径

method:请求对应的方法。有GET,PUT,POST,DELETE,HEAD。

GET:获取URI对应信息

POST:创建相应值

PUT:创建/更新

DELETE:删除

HEAD:获取文件是否存在

说明一下POSTPUT的区别: POST 永远是创建新的。PUT 可以表示创建,但是如果指定的URI存在,则含义为更新。换句话说,一个PUT请求,重复执行,结果应该是一样的。


2 请求路径带有参数

方法一:

@RequestMapping("/r/qcs")
@Controller
public class QcsController extends BasicController {
	@RequestMapping(value="/whitelistlogically",method = RequestMethod.GET)
	@ResponseBody
	public List<String> getWhitelistLogically(
		@RequestParam(value="entry",required = true) String entry,
		@RequestParam(value="volume",required = true) String volume) {
		return qcsService.getWhitelistLogically(entry,volume);
	}
}
请求路径: {base}/r/qcs/whitelistlogically?entry={a}&volume={b}

@ResponseBody:将内容或对象作为HTTP响应正文返回,使用@ResponseBody会表过视图处理部分,调用适合HttpMessageConverter,将返回值写入输出流。

@RequestParam:请求参数注解,代表方法参数应该与web请求参数绑定。

required:参数是否必须,如果为true则为必须;为false为不必须。


方法二

@RequestMapping("/r/qcs")
@Controller
public class QcsController extends BasicController {
	@RequestMapping(value="/whitelistlogically",method = RequestMethod.GET)
	@ResponseBody
	public List<String> getWhitelistLogically(HttpServletRequest request) {
		String entry = RequestUtils.getParam(request, "name", null);
		String volume = RequestUtils.getParam(request, "volume", null);
		return qcsService.getWhitelistLogically(entry,volume);
	}
	
	/**
     * 获取浏览器提交的字符串参数
     * 
     * @param req
     *            HttpServletRequest
     * @param param
     *            参数名
     * @param defaultValue
     *            默认值
     * @return String
     */
    public static String getParam(HttpServletRequest req, String param, String defaultValue) {
        String value = req.getParameter(param);
        return (StringUtils.isEmpty(value)) ? defaultValue : value.trim();
    }
}
请求路径: {base}/r/qcs/whitelistlogically?entry={a}&volume={b}
通过解析HttpServletRequest来获取请求参数。


3 通过对象实例来接受Json参数

一般是对于POST请求,通过Json带入需要传入的参数比较多的情况下的数据。

@RequestMapping("/r/qcs")
@Controller
public class QcsController extends BasicController {
    @RequestMapping(value = "/v1/add", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> addClientToWhiteList(@RequestBody QcsClientEntity qcsClientRequest,
    								 HttpServletResponse response) throws Exception{	
    	String location = qcsClientRequest.getLocation();
    	String production = qcsClientRequest.getProduction();
    	String type = qcsClientRequest.getType();
    	String rolename = qcsClientRequest.getRolename();
    	String[] clients = qcsClientRequest.getClientips();
    	String callbackURI = qcsClientRequest.getCallbackuri();
    	String token = qcsClientRequest.getToken();
		...
	}
}

public class QcsClientEntity {
	String location;
	String production;
	String type;
	String rolename;
	String[] clientips;
	String callbackuri;
	String token;
	
	public String getToken() { return token; }
	public void setToken(String token) { this.token = token; }
	public String getLocation() { return location; }
	public void setLocation(String location) { this.location = location; }
	public String getProduction() { return production; }
	public void setProduction(String production) { this.production = production; }
	public String getType() { return type; }
	public void setType(String type) { this.type = type; }
	public String getRolename() { return rolename; }
	public void setRolename(String rolename) { this.rolename = rolename; }
	public String[] getClientips() { return clientips; }
	public void setClientips(String[] clientips) { this.clientips = clientips; }
	public String getCallbackuri() { return callbackuri; }
	public void setCallbackuri(String callbackuri) { this.callbackuri = callbackuri;}

}
通过一个对象实体来接受请求,然后解析请求对象,然后或许相应的参数。就行解析。

4 路径参数

@RequestMapping("/r/qcs")
@Controller
public class QcsController extends BasicController {
	@RequestMapping(value="/whitelistlogically/{entry}/{volume}",method = RequestMethod.GET)
	@ResponseBody
	public List<String> getWhitelistLogically(
		@PathVariable String entry,
		@PathVariable String volume) {
		return qcsService.getWhitelistLogically(entry,volume);
	}
}
对应的路径:{base}/r/qcs/whitelistlogically?entry={entry}&volume={volume}

@PathVariable:注解绑定请求传来的值到方法的参数上。

@RequestMapping(value="/whitelistlogically/{entry}/{volume}",method = RequestMethod.GET) 与 @PathVariable String entry,@PathVariable String volume 一一对应,按名字匹配,为restful风格。如果映射名称不一致,那就使用另外一种方式:

@RequestMapping("/r/qcs")
@Controller
public class QcsController extends BasicController {
	@RequestMapping(value="/whitelistlogically/{entry}/{volume}",method = RequestMethod.GET)
	@ResponseBody
	public List<String> getWhitelistLogically( @PathVariable("entry") String paramEntry,
						   @PathVariable("volume") String paramVolume) {
		return qcsService.getWhitelistLogically(entry,volume);
	}
}

以上是主要一些spring restful api获取参数的方法,作为以备后续翻阅。


参考资料:

>http://liuyanwei.jumppo.com/2015/05/28/spring-2.html

>http://stackoverflow.com/questions/11291933/requestbody-and-responsebody-spring


Author:忆之独秀

Email:leaguenew@qq.com

注明出处:http://blog.csdn.net/lavorange/article/details/50696936


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值