SpringBoot之Controller的使用详解

2025-05-29 0 18

本文介绍了 springboot之controller的使用,分享给大家,具体如下:

1.@controller:处理http请求

2.@restcontroller:spring4之后新加的注解,原来返回json需要@responsebody配合@controller

3.@requestmapping 配置url映射

1.现在有一个需求(即可以使用localhost:8080/hello和localhost:8080/hi都可以访问):

?

1
2

3

4

5

6

7
@restcontroller

public class hellocontroller {

@requestmapping(value={"/hello","hi"},method = requestmethod.get)//使用集合设置

public string say(){

return "hello spring boot";

}

}

springboot获取请求参数

1.@pathvariable–>获取url中的数据

2.@reqeustparam–>获取请求参数的值,可以设置默认值以及是否必传

3.@getmapping–>组合注解(相当于@requestmapping同时限定请求方法为get 方式)

1.第一种方式:

假如http://localhost:8080/hello为请求,springboot为需要传递的参数:http://localhost:8080/hello/spingboot,获取此种请求的参数的方式,使用@pathvariable注解

?

1
2

3

4

5

6

7
@restcontroller

public class hellocontroller {

@requestmapping("/hello/{params}")//获取请求为http://localhost:8080/hello/xxx 类型的参数

public string hello(@pathvariable("params") string paramsstr) {//声明一个变量接收请求中的参数

return "parameter is "+paramsstr;

}

}

运行程序,输入http://localhost:8080/hello/spingboot进行测试:

SpringBoot之Controller的使用详解

2.第二种方式:

获取请求为http://localhost:8080/hello?params=spingboot类型的参数,使用@requesparam注解,使用方法为@requesparam("请求中的参数名params")

?

1
2

3

4

5

6

7

8
@restcontroller

public class hellocontroller {

//获取请求为http://localhost:8080/hello?xxx=xxx类型的参数

@requestmapping("/hello")

public string hello(@requestparam("params") string paramsstr) {//requestparam中的参数名称与请求中参数名称要一致

return "parameter is "+paramsstr;

}

}

如:@requestparam(value="item_id",required=true) string id

@requestparam中的其他属性:

–required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报错

–defaultvalue:默认值,表示如果请求中没有同名参数时的默认值

启动程序,输入http://localhost:8080/hello?params=spingboot:

SpringBoot之Controller的使用详解

对于@requestmapping(value="/hello",method = requestmethod.get)可以使用:@getmapping(value="/hello"),如果是post的话就是用@postmapping

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:http://blog.csdn.net/qq_35508033/article/details/71893371?utm_source=gold_browser_extension

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 SpringBoot之Controller的使用详解 https://www.kuaiidc.com/115304.html

相关文章

发表评论
暂无评论