spring boot官方文档案例及@GetMapping

该文章为了记录自己看官方文档做出官方demo(示例),以及记录@GetMapping注释引用hello方法的稍微改动。

本人的实验环境:Windows10----IDEA----java8

首先,官方要求我们去:官方的配置打包网站

进行打包并且下载好文档,下图是我的配置选择,这里进行的是一个spring boot基本项目,需要的依赖是spring web

然后点击最下方的菜单栏里面的这个:

等待它下载完成,并解压它,然后用IDEA导入:

最后点击确认就可以导入进IDEA了,导入之后长这样子:

代码:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);

	}

	@GetMapping("/hello")
	public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
		return String.format("Hello %s!", name);
	}
}

在这里插入一下各个注释的意思:@SpringBootApplication是启动spring boot的关键,一般在主类的上方(这里主类是DemoApplication)、@RestController这个是标记DemoApplication作为一个控制器、@GetMapping("/hello")则是获取http的映射,起到路由的作用,让浏览器可以在/hello这个路由里返回hello方法的值。

到这里的话就已经完成了,点击绿色箭头运行:

运行成功:

在浏览器输入:http://localhost:8080/hello 就可以看到:

如果你在 http://localhost:8080/hello 后面加上 ?name=zhangsan 你会发现:

World 变成了zhangsan

以上就是官网的例子

然后我想着把hello方法给弄出来在IDEA里面直接赋值给name参数,我就这样做了:

添加了一点代码,并且改变了@GetMapping注释的位置:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);

	}


	public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
		return String.format("Hello %s!", name);
	}

	@GetMapping("/hello")
	public String print(){
		String a ;
		a = hello("张三");
		return a;
	}

}

结果就可以在print方法里面用hello方法在IDEA里面直接赋值了

浏览器运行截图:

本人刚刚接触spring boot,如有不当之处敬请指出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值