controller的使用
一、
- @controller:處理http請求
- @restcontroller:spring4之后新加的注解,原來返回json需要@responsebody配合@controller
- @requestmapping:配置url映射
1.對于控制器層,如果只使用@controller注解,會報500,即controller必須配合一個模板來使用:
使用spring官方的一個模板:
1
2
3
4
|
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-thymeleaf</artifactid> </dependency> |
在resources下面的templates文件夾下建立index.html:
1
|
<h1>hello spring boot!</h1> |
hellocontroller:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@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中添加如下:
1
2
3
4
5
6
7
8
9
10
11
|
@restcontroller public class hellocontroller { @autowired private girlproperties girlproperties; @requestmapping (value = { "/hello" , "/hi" },method = requestmethod.get) public string say(){ return girlproperties.getcupsize(); } } |
二、
- @pathvariable:獲取url中的數據
- @requestparam:獲取請求參數的值
- @getmapping:組合注解
@pathvariable:
方式一:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@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寫在前面:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@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(); } } |
結果:
方式三:使用傳統方式訪問:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@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")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@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(); } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.jianshu.com/p/84cf975068d2?utm_source=tuicool&utm_medium=referral