项目目录:
说明: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