Spring Boot 建立简单的Web项目
新建工程分四步进行
- 在官方提供的网站下生成模板
- 工程文件在 IDEA 中打开
- 编写测试代码
- 测试
1.网站
start.spring.io
添加Web组件,再点击 generate 生成工程模板。
2.使用IDEA打开工程文件
3.测试代码
在主类里面添加测试代码
GetMapping 的作用是把URI请求和映射到当前指定方法。
RequestParam 的作用是把参数和URI传递的参数进行绑定
代码:
package com.example.demo;
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);
}
}
4.测试
右键,点击运行。
或者,在控制台直接运行
windows系统则:mvnw spring-boot:run
MacOS/Linux 系统则:./mvnw spring-boot:run
运行成功提示
接着,在浏览器访问 http://localhost:8080/hello
可以发现, ?name=zanxin 变量name是因为 RequestParam 的绑定而可以传递到hello方法里面的。
小结
- GetMapping 把 URI 映射到方法。
- RequestParam 绑定前端和后端的变量。