springboot-controller的使用详解
程序员文章站
2024-02-24 19:50:10
controller的使用
一、
@controller:处理http请求
@restcontroller:spring4之后新加的注解,原来返回json...
controller的使用
一、
- @controller:处理http请求
- @restcontroller:spring4之后新加的注解,原来返回json需要@responsebody配合@controller
- @requestmapping:配置url映射
1.对于控制器层,如果只使用@controller注解,会报500,即controller必须配合一个模板来使用:
使用spring官方的一个模板:
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-thymeleaf</artifactid> </dependency>
在resources下面的templates文件夹下建立index.html:
<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:获取url中的数据
- @requestparam:获取请求参数的值
- @getmapping:组合注解
@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(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。