服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|

服务器之家 - 编程语言 - JAVA教程 - SpringBoot之Controller的使用详解

SpringBoot之Controller的使用详解

2020-12-16 13:27ren-zhe JAVA教程

本篇文章主要介绍了SpringBoot之Controller的使用详解,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。

本文介绍了 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

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

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

延伸 · 阅读

精彩推荐