SpringMVC(二):基于注解的SpringMVC入门

阅读:402 2019-03-19 14:40:05 来源:开源中国

对包进行扫描,实现注释驱动bean定义,同时将bean自动注入容器中使用。即解决了@controller标识的类的bean的注入和使用。

会自动注册defaultannotationhandlermapping与annotationmethodhandleradapter两个bean。

如果没有,那么所有的controller可能就没有解析,没有相应的controller就会被defaultservlet处理。

启用自动检测

标识一个控制器,@controller注解定义在org.springframework.steretype包中。使用方式:@controller或者@controller("")。

org.springframework.steretype包中还包含@component@service@respository三个注解。@component是通用标注,@controller标注web控制器,@service标注servicec层的服务,@respository标注dao层的数据访问。

在类级别上则表示相对路径

在方法级别上则表示访问路径

请求:(网站域名+web应用名)web应用根目录+类定义处@requestmapping+方法定义处@requestmapping

映射到

物理视图:webapp根目录+springmvc.xml配置的prefix+控制器方法的返回值+springmvc.xml配置的sufix

这里的话是

请求:http://localhost:8080/myspringmvc/roger/test

映射到

物理视图webapp/test.jsp就通过控制器上的

注:当方法返回值类型为void时,controller方法还是返回一个string类型的值作为视图名(默认为请求名)

例如:http://localhost:8080/myspringmvc/roger/test访问showtest()

@controller@requestmapping("/roger")publicclasstestcontroller{@requestmapping("/")publicstringshowindex(){return"index";}@requestmapping(value="/test")publicstringshowtest(){return"test";}@requestmapping(value="/get")publicvoidshowtest(){//dosomething..}(默认返回一个string类型的值作为视图名(默认为请求名))

@requestmapping的value值前后是否有“/”对请求的路径没有影响,即value="test"、"/test"、"/test/"其效果是一样的。

在一些场景中,请求的url可能是符合一定模式的多个值,这时候需要使用ant风格通配符来进行限定。

ant风格资源地址支持3种匹配符:

?:匹配文件名中的一个字符

*:匹配文件名中的任意字符

**:**匹配多层路径

@requestmapping支持ant风格的url:

–/user/*/createuser:匹配

/user/aaa/createuser、/user/bbb/createuser等url

–/user/**/createuser:匹配

/user/createuser、/user/aaa/bbb/createuser等url

–/user/createuser??:匹配

/user/createuseraa、/user/createuserbb等url

选择范围更小,更加具体的进行映射

?>*>**

仅仅是位置关系有差别,映射是随机的

@requestmapping(params="action=del"),请求参数包含“action=del",如http://localhost:8080/myspringmvc/roger/test?action=del

复杂点,例如:

所传参数中必须包含username,age=20,以及不能包含名为pwd的参数

@requestmapping(value="testparam2",params={"username","age=20","!pwd"})publicstringtestparam2(){return"test";}

使用@requestparam("xx")注解获取get请求或post请求提交的参数,替代request.getparameter("xx")

例如:

访问链接:http://localhost:8080/myspringmvc/roger/testparam?username=roger

@requestmapping(value="/testparam",method=requestmethod.get)publicstringtestparam(httpservletrequestrequest,@requestparam("username")stringusername){system.out.println("httpservletrequest,username:"+request.getparameter("username"));system.out.println("@requestparam(),username:"+username);return"test";}

@requestparam()来映射请求参数

value值即请求参数名

required该参数是否必需。默认为true

defaultvalue请求参数的默认值

处理函数的参数类型必须是对象类型,否则基本数据类型如int等无法设为空。

required属性标注这个参数是否是必需的,默认是true,如果想让它可以不存在,那么就设置为false。但是请注意,required设置成false的参数对应的处理函数的参数类型必须是对象类型,否则回报错500!

packagecom.happybks.springmvc.handlers;importorg.springframework.stereotype.controller;importorg.springframework.web.bind.annotation.requestmapping;importorg.springframework.web.bind.annotation.requestparam;@requestmapping("class")@controllerpublicclassrptesthandler{stringpage="successrm";@requestmapping("student")publicstringhandle(@requestparam(value="username")stringun,@requestparam(value="age",required=false)intage){system.out.println("astudent'srequesthascome.username:"+un+",age:"+age);returnpage;}}

结果会报错,因为age虽然设置了required为false,请求参数可以不包含age,但是在处理函数中对应的参数类型是int,int是基本数据类型,无法为空,所以报错。解决办法是将int改为integer。

如果我们仍然想用基本类型作为参数类型,那么可以用到@requestparam注解的defaultvalue属性来指定默认值。

@controllerpublicclassrptesthandler{stringpage="successrm";@requestmapping("student")publicstringhandle(@requestparam(value="username")stringun,@requestparam(value="age",required=false,defaultvalue="0")intage){system.out.println("astudent'srequesthascome.username:"+un+",age:"+age);returnpage;}}

使用@pathvariable注解提取路径中的变量值,映射请求url中的占位符到控制器方法参数。

例如:

@requestmapping(value="/testpathvariable/{username}",method=requestmethod.get)publicstringtestpathvariable(@pathvariablestringusername){system.out.println("username:"+username);return"test";}

访问路径可以是:http://localhost:8080/myspringmvc/roger/testpathvariable/roger_fang

但是/testpathvariable/{username},路径中username部分不能有'/'。

@autowired,注释类型属于org.springframework.beans.factory.annotation包,注解到字段或方法。

@service,注释类型属于org.springframework.stereotype包,注解到类上,用于指示类是一个服务,在配置文件中还需要添加一个元素来扫描依赖基本包。

例如:

controller类

publicclassproductcontroller{@autowiredprivteproductserviceproductservice;//handlemethod}

productservice接口

publicinterfaceproductservice{//product处理方法}

productserviceimpl类

@servicepublicclassproductserviceimplimplementsproductservice{//product处理方法}

本例中,@autowired注解会使一个productservice实例被注入到productcontroller实例中,同时,为了使productserviceimpl类能被spring扫描到,必须为其标注@service。

a、注释方法的参数

用于将输入或创建的对象添加到model对象中(若方法中没有显示添加)。

@requestmapping("/saveproduct")publicstringsaveproduct(@modelattributeproductproduct,modelmodel){...}

@modelattribute如果未定义键值名则自动将类的首字母改为小写如"product"作为键值名添加到model对象中。也可以自定义@modelattribute("xxx")。

从form表单或url参数中获取(实际上,不做此注释也能拿到product对象)。

b、标注一个非请求的处理方法

被@modelattribute注解的方法会在每次调用该控制器类的请求处理方法时被调用。带@modelattribute注解的方法可以返回一个对象或一个void类型,如果返回一个对象免则返回的对象会自动添加到model中。

以下两种方式:

@modelatrributepublicvoidpopulatemodel(modelmodel){model.addattribute(newproduct())}@modelattributepublicproductaddproduct(){returnnewproduct();}

使用@responsebody将会跳过视图处理部分,而是调用适合httpmessageconverter,将返回值写入输出流

相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>
推荐商标

{{ v.name }}

{{ v.cls }}类

立即购买 联系客服