当前位置: 移动技术网 > IT编程>开发语言>Java > SpringBoot之Controller的使用详解

SpringBoot之Controller的使用详解

2019年07月19日  | 移动技术网IT编程  | 我要评论

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

1.@controller:处理http请求

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

3.@requestmapping 配置url映射

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

@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://www.lhsxpumps.com/_localhost:8080/hello为请求,springboot为需要传递的参数:http://localhost:8080/hello/spingboot,获取此种请求的参数的方式,使用@pathvariable注解

@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://www.lhsxpumps.com/_localhost:8080/hello?params=spingboot类型的参数,使用@requesparam注解,使用方法为@requesparam("请求中的参数名params")

@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

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网