Java速通:36-网页简易加法器

项目目录:

 说明:1.boot下可以额外新建package,但是要保证 启动器StartTheServer和控制                                      器 AddController在同一级

            2.static下可以额外新建package,但是localhost:8080/默认进入的是static,也就是说,要              写成localhost:8080/xxx/xxx的形式进入下一级包

代码说明

文件1:启动器

package boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class StartTheServer {

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

}

文件2:html网页

<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<input type="text" name="a" id="a" value="0"> +
<input type="text" name="b" id="b" value="0">
<input type="button" value = "=" id = evaluate>
<span id = "c"></span>
<script type="text/javascript">
    document.querySelector("#evaluate").onclick = function(){
        var a = document.querySelector("#a").value;
        var b = document.querySelector("#b").value;
        //fetch("http://localhost:8080/add?a=" + a + "&b=" + b) //生成网页路径
        fetch(`http://localhost:8080/add?a=&{a}&b=${b}`)    //可读性更强的写法
            .then(resp=>resp.text())
            .then(text=>document.querySelector("#c").innerText = text)
    }
</script>

</body>
<html>

文件3:控制器

package boot;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AddController {
    @RequestMapping("/add") //js中 fetch()里面规划好的路径
    @ResponseBody
    int add(int a, int b) { //与js中的变量名一致
        return a + b;
    }
}

对控制器中传参的说明:

        1.@RequestMapping("/add")是static下html网页的路径

        2.int add(int a, int b) 中的a b 严格对应html文件中fetch生成url中的传参:

          fetch(`http://localhost:8080/add?a=&{a}&b=${b}`) 即?后的a b

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值