本文介绍了 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进行测试:
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:
对于@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
相关文章
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
-
2025-05-25 80
-
2025-05-29 62
-
2025-05-29 67
-
2025-05-25 99
-
2025-05-29 33



