首页 > 解决方案 > 简单的弹簧靴+反应组件

问题描述

我有一个带有 react 的 webapp,以及一个带有 spring boot 的后端 webapp。

我在 APP.js 上使用它

constructor(props) {
      super(props);

      this.state = {
        greeting: "This is a false greeting" 
      }
    } 

    componentDidMount() {
        fetch("/test2").then(function(response) {
               return response.text();
            }).then((text) => {
                  this.setState({greeting: text})
               });
     }

这在控制器上:

@RestController
public class HelloController {

    @RequestMapping("/test")
    public String test() {
        int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
        return "This is a greeting from spring";
    }

它有效,与

{this.state.greeting}

我可以看到“这是春天的问候”

我想从 app.js 发送一个值(一个用按钮选择的数字)到弹簧侧控制器,控制器会采用这个值,选择一个随机值,比较两个值,然后发送响应。

我被困在“将值从 app.js 发送到弹簧侧控制器”

有人能帮我吗 ?

标签: reactjsspring-boot

解决方案


在您的 UI 上将查询参数附加到 GET 请求中的 URL。

constructor(props) {
  super(props);

  this.state = {
    greeting: "This is a false greeting",
    selectedNumber: 0 //update this state variable on button click
  }

} 

componentDidMount() {
    fetch("/test2?selectedNumber=" + this.state.selectedNumber).then(function(response) {
           return response.text();
        }).then((response) => {
              console.log(response);
           });
 }

在 Spring-boot API 控制器上,添加 RequestParam 以便 API 能够从请求中读取查询参数。

@RestController
public class HelloController {

@RequestMapping("/test2")
public String test2(@RequestParam("selectedNumber") int selectedNumber) {
    System.out.println(selectedNumber);
    int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
    return "This is a greeting from spring";
}

推荐阅读