简介: handler method 参数绑定常用的注解,我们根据他们处理的request的不同内容部分分为四类:(主要讲解常用类型)
a、处理requet uri 部分(这里指uri template中variable,不含querystring部分)的注解: @pathvariable;
b、处理request header部分的注解: @requestheader, @cookievalue;
c、处理request body部分的注解:@requestparam, @requestbody;
d、处理attribute类型是注解: @sessionattributes, @modelattribute;
1、 @pathvariable当使用@requestmapping uri template 样式映射时, 即 someurl/{paramid}, 这时的paramid可通过 @pathvariable注解绑定它传过来的值到方法的参数上。
示例代码:
@controller
@requestmapping("/owners/{ownerid}")
publicclass relativepathuritemplatecontroller
{
@requestmapping("/pets/{petid}")
publicvoid findpet(@pathvariable string
ownerid, @pathvariable string petid,
model model) {
// implementation
omitted
}
}
@controller
@requestmapping("/owners/{ownerid}")
public class relativepathuritemplatecontroller {
@requestmapping("/pets/{petid}")
public void findpet(@pathvariable string ownerid, @pathvariable string petid, model model) {
// implementation omitted
}
}
上面代码把uri template 中变量 ownerid的值和petid的值,绑定到方法的参数上。若方法参数名称和需要绑定的uri template中变量名称不一致,需要在@pathvariable("name")指定uri template中的名称。
2、 @requestheader、@cookievalue@requestheader 注解,可以把request请求header部分的值绑定到方法的参数上。
示例代码:
这是一个request 的header部分:
host localhost:8080
accept text/html,application/xhtml+xml,application/xml;q=0.9
accept-language fr,en-gb;q=0.7,en;q=0.3
accept-encoding gzip,deflate
accept-charset iso-8859-1,utf-8;q=0.7,*;q=0.7
keep-alive 300
host localhost:8080
accept text/html,application/xhtml+xml,application/xml;q=0.9
accept-language fr,en-gb;q=0.7,en;q=0.3
accept-encoding gzip,deflate
accept-charset iso-8859-1,utf-8;q=0.7,*;q=0.7
keep-alive 300
@requestmapping("/displayheaderinfo.do")
publicvoid displayheaderinfo(@requestheader("accept-encoding")
string encoding,
@requestheader("keep-alive") long keepalive)
{
//...
}
@requestmapping("/displayheaderinfo.do")
public void displayheaderinfo(@requestheader("accept-encoding") string encoding,
@requestheader("keep-alive") long keepalive) {
//...
}
上面的代码,把request header部分的 accept-encoding的值,绑定到参数encoding上了, keep-alive header的值绑定到参数keepalive上。
@cookievalue 可以把request header中关于cookie的值绑定到方法的参数上。
例如有如下cookie值:
jsessionid=415a4ac178c59dace0b2c9ca727cdd84
jsessionid=415a4ac178c59dace0b2c9ca727cdd84
参数绑定的代码:
@requestmapping("/displayheaderinfo.do")
publicvoid displayheaderinfo(@cookievalue("jsessionid")
string cookie) {
//...
}
@requestmapping("/displayheaderinfo.do")
public void displayheaderinfo(@cookievalue("jsessionid") string cookie) {
//...
}
即把jsessionid的值绑定到参数cookie上。
3、@requestparam, @requestbody@requestparam
a) 常用来处理简单类型的绑定,通过request.getparameter() 获取的string可直接转换为简单类型的情况( string--> 简单类型的转换操作由conversionservice配置的转换器来完成);因为使用request.getparameter()方式获取参数,所以可以处理get 方式中querystring的值,也可以处理post方式中 body data的值;
b)用来处理content-type: 为 application/x-www-form-urlencoded编码的内容,提交方式get、post;
c) 该注解有两个属性: value、required; value用来指定要传入值的id名称,required用来指示参数是否必须绑定;
示例代码:
@controller
@requestmapping("/pets")
@sessionattributes("pet")
publicclass editpetform
{
// ...
@requestmapping(method
= requestmethod.get)
public string
setupform(@requestparam("petid") int petid,
modelmap model) {
pet pet = this.clinic.loadpet(petid);
model.addattribute("pet",
pet);
return"petform";
}
// ...
@controller
@requestmapping("/pets")
@sessionattributes("pet")
public class editpetform {
// ...
@requestmapping(method = requestmethod.get)
public string setupform(@requestparam("petid") int petid, modelmap model) {
pet pet = this.clinic.loadpet(petid);
model.addattribute("pet", pet);
return "petform";
}
// ...
@requestbody
该注解常用来处理content-type: 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;
它是通过使用handleradapter 配置的httpmessageconverters来解析post data body,然后绑定到相应的bean上的。
因为配置有formhttpmessageconverter,所以也可以用来处理 application/x-www-form-urlencoded的内容,处理完的结果放在一个multivaluemap<string, string>里,这种情况在某些特殊需求下使用,详情查看formhttpmessageconverter api;
示例代码:
@requestmapping(value
= "/something", method = requestmethod.put)
publicvoid handle(@requestbody string
body, writer writer) throws ioexception
{
writer.write(body);
}
@requestmapping(value = "/something", method = requestmethod.put)
public void handle(@requestbody string body, writer writer) throws ioexception {
writer.write(body);
}
4、@sessionattributes, @modelattribute@sessionattributes:
该注解用来绑定httpsession中的attribute对象的值,便于在方法中的参数里使用。
该注解有value、types两个属性,可以通过名字和类型指定要使用的attribute 对象;
示例代码:
@controller
@requestmapping("/editpet.do")
@sessionattributes("pet")
publicclass editpetform
{
// ...
}
@controller
@requestmapping("/editpet.do")
@sessionattributes("pet")
public class editpetform {
// ...
}
@modelattribute
该注解有两个用法,一个是用于方法上,一个是用于参数上;
用于方法上时: 通常用来在处理@requestmapping之前,为请求绑定需要从后台查询的model;
用于参数上时: 用来通过名称对应,把相应名称的值绑定到注解的参数bean上;要绑定的值来源于:
a) @sessionattributes 启用的attribute 对象上;
b) @modelattribute 用于方法上时指定的model对象;
c) 上述两种情况都没有时,new一个需要绑定的bean对象,然后把request中按名称对应的方式把值绑定到bean中。
用到方法上@modelattribute的示例代码:
// add one attribute
// the return value
of the method is added to the model under the name "account"
// you can customize
the name via @modelattribute("myaccount")
@modelattribute
public account
addaccount(@requestparam string number)
{
return accountmanager.findaccount(number);
}
// add one attribute
// the return value of the method is added to the model under the name "account"
// you can customize the name via @modelattribute("myaccount")
@modelattribute
public account addaccount(@requestparam string number) {
return accountmanager.findaccount(number);
}
这种方式实际的效果就是在调用@requestmapping的方法之前,为request对象的model里put(“account”, account);
用在参数上的@modelattribute示例代码:
@requestmapping(value="/owners/{ownerid}/pets/{petid}/edit",
method = requestmethod.post)
public string
processsubmit(@modelattribute pet pet)
{
}
@requestmapping(value="/owners/{ownerid}/pets/{petid}/edit", method = requestmethod.post)
public string processsubmit(@modelattribute pet pet) {
}
首先查询 @sessionattributes有无绑定的pet对象,若没有则查询@modelattribute方法层面上是否绑定了pet对象,若没有则将uri template中的值按对应的名称绑定到pet对象的各属性上。
补充讲解:问题: 在不给定注解的情况下,参数是怎样绑定的?通过分析annotationmethodhandleradapter和requestmappinghandleradapter的源代码发现,方法的参数在不给定参数的情况下:
若要绑定的对象时简单类型: 调用@requestparam来处理的。
若要绑定的对象时复杂类型: 调用@modelattribute来处理的。
这里的简单类型指java的原始类型(boolean, int 等)、原始类型对象(boolean, int等)、string、date等conversionservice里可以直接string转换成目标对象的类型;
下面贴出annotationmethodhandleradapter中绑定参数的部分源代码:
private object[]
resolvehandlerarguments(method handlermethod, object handler,
nativewebrequest webrequest, extendedmodelmap implicitmodel) throws exception
{
class[] paramtypes = handlermethod.getparametertypes();
object[] args = new object[paramtypes.length];
for (int i
= 0; i < args.length; i++) {
methodparameter methodparam = new methodparameter(handlermethod,
i);
methodparam.initparameternamediscovery(this.parameternamediscoverer);
generictyperesolver.resolveparametertype(methodparam, handler.getclass());
string paramname = null;
string headername = null;
boolean requestbodyfound
= false;
string cookiename = null;
string pathvarname = null;
string attrname = null;
boolean required
= false;
string defaultvalue = null;
boolean validate
= false;
object[] validationhints = null;
int annotationsfound
= 0;
annotation[] paramanns = methodparam.getparameterannotations();
for (annotation
paramann : paramanns) {
if (requestparam.class.isinstance(paramann))
{
requestparam requestparam = (requestparam) paramann;
paramname = requestparam.value();
required = requestparam.required();
defaultvalue = parsedefaultvalueattribute(requestparam.defaultvalue());
annotationsfound++;
}
elseif (requestheader.class.isinstance(paramann))
{
requestheader requestheader = (requestheader) paramann;
headername = requestheader.value();
required = requestheader.required();
defaultvalue = parsedefaultvalueattribute(requestheader.defaultvalue());
annotationsfound++;
}
elseif (requestbody.class.isinstance(paramann))
{
requestbodyfound = true;
annotationsfound++;
}
elseif (cookievalue.class.isinstance(paramann))
{
cookievalue cookievalue = (cookievalue) paramann;
cookiename = cookievalue.value();
required = cookievalue.required();
defaultvalue = parsedefaultvalueattribute(cookievalue.defaultvalue());
annotationsfound++;
}
elseif (pathvariable.class.isinstance(paramann))
{
pathvariable pathvar = (pathvariable) paramann;
pathvarname = pathvar.value();
annotationsfound++;
}
elseif (modelattribute.class.isinstance(paramann))
{
modelattribute attr = (modelattribute) paramann;
attrname = attr.value();
annotationsfound++;
}
elseif (value.class.isinstance(paramann))
{
defaultvalue = ((value) paramann).value();
}
elseif (paramann.annotationtype().getsimplename().startswith("valid"))
{
validate = true;
object value = annotationutils.getvalue(paramann);
validationhints = (value instanceof object[]
? (object[]) value : new object[]
{value});
}
}
if (annotationsfound
> 1) {
thrownew illegalstateexception("handler
parameter annotations are exclusive choices - " +
"do
not specify more than one such annotation on the same parameter: " + handlermethod);
}
if (annotationsfound
== 0) {//
若没有发现注解
object argvalue = resolvecommonargument(methodparam, webrequest); //判断webrquest是否可赋值给参数
if (argvalue
!= webargumentresolver.unresolved) {
args[i] = argvalue;
}
elseif (defaultvalue
!= null)
{
args[i] = resolvedefaultvalue(defaultvalue);
}
else {
class<?> paramtype = methodparam.getparametertype();
if (model.class.isassignablefrom(paramtype)
|| map.class.isassignablefrom(paramtype))
{
if (!paramtype.isassignablefrom(implicitmodel.getclass()))
{
thrownew illegalstateexception("argument
[" + paramtype.getsimplename() + "]
is of type " +
"model
or map but is not assignable from the actual model. you may need to switch " +
"newer
mvc infrastructure classes to use this argument.");
}
args[i] = implicitmodel;
}
elseif (sessionstatus.class.isassignablefrom(paramtype))
{
args[i] = this.sessionstatus;
}
elseif (httpentity.class.isassignablefrom(paramtype))
{
args[i] = resolvehttpentityrequest(methodparam, webrequest);
}
elseif (errors.class.isassignablefrom(paramtype))
{
thrownew illegalstateexception("errors/bindingresult
argument declared " +
"without
preceding model attribute. check your handler method signature!");
}
elseif (beanutils.issimpleproperty(paramtype))
{// 判断是否参数类型是否是简单类型,若是在使用@requestparam方式来处理,否则使用@modelattribute方式处理
paramname = "";
}
else {
attrname = "";
}
}
}
if (paramname
!= null)
{
args[i] = resolverequestparam(paramname, required, defaultvalue, methodparam, webrequest, handler);
}
elseif (headername
!= null)
{
args[i] = resolverequestheader(headername, required, defaultvalue, methodparam, webrequest, handler);
}
elseif (requestbodyfound)
{
args[i] = resolverequestbody(methodparam, webrequest, handler);
}
elseif (cookiename
!= null)
{
args[i] = resolvecookievalue(cookiename, required, defaultvalue, methodparam, webrequest, handler);
}
elseif (pathvarname
!= null)
{
args[i] = resolvepathvariable(pathvarname, methodparam, webrequest, handler);
}
elseif (attrname
!= null)
{
webdatabinder binder =
resolvemodelattribute(attrname, methodparam, implicitmodel, webrequest, handler);
boolean assignbindingresult
= (args.length > i + 1 && errors.class.isassignablefrom(paramtypes[i
+ 1]));
if (binder.gettarget()
!= null)
{
dobind(binder, webrequest, validate, validationhints, !assignbindingresult);
}
args[i] = binder.gettarget();
if (assignbindingresult)
{
args[i + 1]
= binder.getbindingresult();
i++;
}
implicitmodel.putall(binder.getbindingresult().getmodel());
}
}
return args;
}
private object[] resolvehandlerarguments(method handlermethod, object handler,
nativewebrequest webrequest, extendedmodelmap implicitmodel) throws exception {
class[] paramtypes = handlermethod.getparametertypes();
object[] args = new object[paramtypes.length];
for (int i = 0; i < args.length; i++) {
methodparameter methodparam = new methodparameter(handlermethod, i);
methodparam.initparameternamediscovery(this.parameternamediscoverer);
generictyperesolver.resolveparametertype(methodparam, handler.getclass());
string paramname = null;
string headername = null;
boolean requestbodyfound = false;
string cookiename = null;
string pathvarname = null;
string attrname = null;
boolean required = false;
string defaultvalue = null;
boolean validate = false;
object[] validationhints = null;
int annotationsfound = 0;
annotation[] paramanns = methodparam.getparameterannotations();
for (annotation paramann : paramanns) {
if (requestparam.class.isinstance(paramann)) {
requestparam requestparam = (requestparam) paramann;
paramname = requestparam.value();
required = requestparam.required();
defaultvalue = parsedefaultvalueattribute(requestparam.defaultvalue());
annotationsfound++;
}
else if (requestheader.class.isinstance(paramann)) {
requestheader requestheader = (requestheader) paramann;
headername = requestheader.value();
required = requestheader.required();
defaultvalue = parsedefaultvalueattribute(requestheader.defaultvalue());
annotationsfound++;
}
else if (requestbody.class.isinstance(paramann)) {
requestbodyfound = true;
annotationsfound++;
}
else if (cookievalue.class.isinstance(paramann)) {
cookievalue cookievalue = (cookievalue) paramann;
cookiename = cookievalue.value();
required = cookievalue.required();
defaultvalue = parsedefaultvalueattribute(cookievalue.defaultvalue());
annotationsfound++;
}
else if (pathvariable.class.isinstance(paramann)) {
pathvariable pathvar = (pathvariable) paramann;
pathvarname = pathvar.value();
annotationsfound++;
}
else if (modelattribute.class.isinstance(paramann)) {
modelattribute attr = (modelattribute) paramann;
attrname = attr.value();
annotationsfound++;
}
else if (value.class.isinstance(paramann)) {
defaultvalue = ((value) paramann).value();
}
else if (paramann.annotationtype().getsimplename().startswith("valid")) {
validate = true;
object value = annotationutils.getvalue(paramann);
validationhints = (value instanceof object[] ? (object[]) value : new object[] {value});
}
}
if (annotationsfound > 1) {
throw new illegalstateexception("handler parameter annotations are exclusive choices - " +
"do not specify more than one such annotation on the same parameter: " + handlermethod);
}
if (annotationsfound == 0) {// 若没有发现注解
object argvalue = resolvecommonargument(methodparam, webrequest); //判断webrquest是否可赋值给参数
if (argvalue != webargumentresolver.unresolved) {
args[i] = argvalue;
}
else if (defaultvalue != null) {
args[i] = resolvedefaultvalue(defaultvalue);
}
else {
class<?> paramtype = methodparam.getparametertype();
if (model.class.isassignablefrom(paramtype) || map.class.isassignablefrom(paramtype)) {
if (!paramtype.isassignablefrom(implicitmodel.getclass())) {
throw new illegalstateexception("argument [" + paramtype.getsimplename() + "] is of type " +
"model or map but is not assignable from the actual model. you may need to switch " +
"newer mvc infrastructure classes to use this argument.");
}
args[i] = implicitmodel;
}
else if (sessionstatus.class.isassignablefrom(paramtype)) {
args[i] = this.sessionstatus;
}
else if (httpentity.class.isassignablefrom(paramtype)) {
args[i] = resolvehttpentityrequest(methodparam, webrequest);
}
else if (errors.class.isassignablefrom(paramtype)) {
throw new illegalstateexception("errors/bindingresult argument declared " +
"without preceding model attribute. check your handler method signature!");
}
else if (beanutils.issimpleproperty(paramtype)) {// 判断是否参数类型是否是简单类型,若是在使用@requestparam方式来处理,否则使用@modelattribute方式处理
paramname = "";
}
else {
attrname = "";
}
}
}
if (paramname != null) {
args[i] = resolverequestparam(paramname, required, defaultvalue, methodparam, webrequest, handler);
}
else if (headername != null) {
args[i] = resolverequestheader(headername, required, defaultvalue, methodparam, webrequest, handler);
}
else if (requestbodyfound) {
args[i] = resolverequestbody(methodparam, webrequest, handler);
}
else if (cookiename != null) {
args[i] = resolvecookievalue(cookiename, required, defaultvalue, methodparam, webrequest, handler);
}
else if (pathvarname != null) {
args[i] = resolvepathvariable(pathvarname, methodparam, webrequest, handler);
}
else if (attrname != null) {
webdatabinder binder =
resolvemodelattribute(attrname, methodparam, implicitmodel, webrequest, handler);
boolean assignbindingresult = (args.length > i + 1 && errors.class.isassignablefrom(paramtypes[i + 1]));
if (binder.gettarget() != null) {
dobind(binder, webrequest, validate, validationhints, !assignbindingresult);
}
args[i] = binder.gettarget();
if (assignbindingresult) {
args[i + 1] = binder.getbindingresult();
i++;
}
implicitmodel.putall(binder.getbindingresult().getmodel());
}
}
return args;
}
requestmappinghandleradapter中使用的参数绑定,代码稍微有些不同,有兴趣的同仁可以分析下,最后处理的结果都是一样的。
示例:
@requestmapping ({"/", "/home"})
public string
showhomepage(string key){
logger.debug("key="+key);
return"home";
}
@requestmapping ({"/", "/home"})
public string showhomepage(string key){
logger.debug("key="+key);
return "home";
}
这种情况下,就调用默认的@requestparam来处理。
@requestmapping (method
= requestmethod.post)
public string
doregister(user user){
if(logger.isdebugenabled()){
logger.debug("process
url[/user], method[post] in "+getclass());
logger.debug(user);
}
return"user";
}
@requestmapping (method = requestmethod.post)
public string doregister(user user){
if(logger.isdebugenabled()){
logger.debug("process url[/user], method[post] in "+getclass());
logger.debug(user);
}
return "user";
}
这种情况下,就调用@modelattribute来处理。
以上就是@requestparam @requestbody @pathvariable 等参数绑定注解详解的内容。