@pathvariable的作用
获取url动态变量,例如
@requestmapping("/users/{userid}")
@responsebody
public string getuser(@pathvariable string userid){
return "userid=" + userid;
}
@pathvariable的包引用
spring自从3.0版本就引入了org.springframework.web.bind.annotation.pathvariable,
这是restful一个具有里程碑的方式,将springmvc的精华推向了高潮,那个时代,跟微信公众号结合的开发如火如荼,很多东西都会用到url参数带值的功能。
@pathvariable的pathvariable官方doc解释
- annotation which indicates that a method parameter should be bound to a uri template variable. supported for requestmapping annotated handler methods in servlet environments.
- if the method parameter is map<string, string> or multivaluemap<string, string> then the map is populated with all path variable names and values.
翻译过来就是:
- 在springmvc中可以使用@pathvariable注解,来支持绑定url模板参数(占位符参数/参数带值)
- 另外如果controller的参数是map(string, string)或者multivaluemap(string, string),也会顺带把@pathvariable的参数也接收进去
@pathvariable的restful示范
前面讲作用的时候已经有一个,现在再提供多一个,别人访问的时候可以http://localhost:8080/call/窗口号-检查编号-1
/**
* 叫号
*/
@putmapping("/call/{checkwicket}-{checknum}-{status}")
public apireturnobject call(@pathvariable("checkwicket") string checkwicket,@pathvariable("checknum") string checknum,
@pathvariable("status") string status) {
if(stringutils.isblank(checkwicket) || stringutils.isblank(checknum)) {
return apireturnutil.error("叫号失败,窗口号,检查者编号不能为空");
}else {
if(stringutils.isblank(status)) status ="1";
try {
lineservice.updatecall(checkwicket,checknum,status);
return apireturnutil.success("叫号成功");
} catch (exception e) {
return apireturnutil.error(e.getmessage());
}
}
}
补充:解决@pathvariable接收参数带点号时只截取点号前的数据的问题
问题:
@requestmapping(value = "preview/{filename}", method = requestmethod.get)
public void previewfile(@pathvariable("filename") string filename, httpservletrequest req, httpservletresponse res) {
officeonlinepreviewservice.previewfile(filename, req, res);
}
本来filename参数传的是:userinfo.docx,
但结果接收到的是:userinfo
这显然不是我想要的。
解决方法:
@requestmapping(value = "preview/{filename:.+}", method = requestmethod.get)
public void previewfile(@pathvariable("filename") string filename, httpservletrequest req, httpservletresponse res) {
officeonlinepreviewservice.previewfile(filename, req, res);
}
参数filename这样写,表示任何点(包括最后一个点)都将被视为参数的一部分:
{filename:.+}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。
我只想好好睡一觉