controller的使用
一、
1.对于控制器层,如果只使用@controller注解,会报500,即controller必须配合一个模板来使用:
使用spring官方的一个模板:
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-thymeleaf</artifactid> </dependency>
在resources下面的templates文件夹下建立:
<h1>hello spring boot!</h1>
hellocontroller:
@controller @responsebody public class hellocontroller { @autowired private girlproperties girlproperties; @requestmapping(value = "/hello",method = requestmethod.get) public string say(){ // return girlproperties.getcupsize(); return "index"; } }
@restcontroller相当于@controller和@responsebody组合使用
如果程序需要通过hello和hi都能访问到,只需在@requestmapping的value中添加如下:
@restcontroller public class hellocontroller { @autowired private girlproperties girlproperties; @requestmapping(value = {"/hello", "/hi"},method = requestmethod.get) public string say(){ return girlproperties.getcupsize(); } }
二、
@pathvariable:
方式一:
@restcontroller @requestmapping("/hello") public class hellocontroller { @autowired private girlproperties girlproperties; @requestmapping(value = {"/say/{id}"},method = requestmethod.get) public string say(@pathvariable("id") integer id){ return "id:"+id; // return girlproperties.getcupsize(); } }
结果:
方式二:也可以把id写在前面:
@restcontroller @requestmapping("/hello") public class hellocontroller { @autowired private girlproperties girlproperties; @requestmapping(value = {"/{id}/say"},method = requestmethod.get) public string say(@pathvariable("id") integer id){ return "id:"+id; // return girlproperties.getcupsize(); } }
结果:
方式三:使用传统方式访问:
@restcontroller @requestmapping("/hello") public class hellocontroller { @autowired private girlproperties girlproperties; @requestmapping(value = "/say",method = requestmethod.get) public string say(@requestparam("id") integer myid){ return "id:"+myid; //方法参数中的integer id这个id不需要与前面对应 // return girlproperties.getcupsize(); } }
结果:
注解简写:@requestmapping(value = "/say",method = requestmethod.get)等价于:@getmapping(value = "/say")
@restcontroller @requestmapping("/hello") public class hellocontroller { @autowired private girlproperties girlproperties; // @requestmapping(value = "/say",method = requestmethod.get) //@getmapping(value = "/say")//等价于上面的 @postmapping(value = "/say") public string say(@requestparam("id") integer myid){ return "id:"+myid; //方法参数中的integer id这个id不需要与前面对应 // return girlproperties.getcupsize(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
android用Popup弹出窗(PopupWindow的使用方式)
ionic3 打包 Could not get resource ‘https://jcenter.bintray.com/com/google/zxing/core/3.2.1/core-3.2.1
NullPointerException: Attempt to invoke virtual method ‘android.content.res.XmlResourceParser androi
网友评论