Java学习Day2——Spring Boot

112 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第6天,点击查看活动详情

1.C/S架构

形式:多个Client端与一个Server端进行交互

功能:支持多个Client访问Server端

image.png

若Client端为浏览器,就称为B/S架构

2.Server——Spring Boot

image.png

*端口号:

Tomcat:8080
MySql:3306

3.IDEA社区版——构建Spring Boot骨架

社区版需要使用网页版向导

国外地址:start.spring.io/

国内网址:start.aliyun.com/

(使用国内地址需要更改配置文件-pom.xml)

image.png

image.png

4.修改Maven的jar包下载地址

image.png

<mirror>
  <id>central</id>
  <mirrorOf>central</mirrorOf>
  <url>https://maven.aliyun.com/repository/public</url>
</mirror>

5.骨架代码加入到项目中

将解压后的文件夹复制到project下

image.png

image.png

image.png

导入成功

image.png

5.简单案例

实例代码:

@Controller
public class HelloController {
    @RequestMapping("/Hello")
    @ResponseBody
    String Hi(){
        return "Hello,World";
    }
}

@Controller:标识当前类为控制器类

@RequestMapping("/Hello"):使得url与Hi方法建立对应联系

@ResponseBody:方法的返回结果作为响应内容

此时运行出现错误

image.png

解决方法:blog.csdn.net/weixin_4378…

运行后在浏览器输入相应的url,运行成功:

image.png

6.输入处理

网页Demo:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--文本框-->
<input type="text" name="name" id="n">
<!--按钮-->
<input type="button" value="say hello" id="b"/>
<h4></h4>
<script type="text/javascript">
    // 按钮的点击事件
    document.querySelector("#b").onclick = function(){
        // 获取用户在文本框输入的值
        var n = document.querySelector("#n").value;
        // 发送请求
        fetch("http://localhost:8080/Hello?name=" + n)
            .then(resp=>resp.text())
            .then(text=>{
                document.querySelector("h4").innerText = text;
            })
    }
</script>
</body>
</html>

Hi方法接收查询参数

image.png

最简单方法:Hi方法传入name参数

image.png

重新运行

image.png

练习

网页Demo:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--数字框-->
<input type="number" name="a" id="a" value="0"> +
<input type="number" name="b" id="b" value="0">
<!--=号按钮-->
<input type="button" value="=" id="evaluate">
<span id="c"></span>
<script>
    document.querySelector("#evaluate").onclick = function() {
        // 获取两个数字框的值
        var a = document.querySelector("#a").value;
        var b = document.querySelector("#b").value;
        // http://localhost:8080/add?a=100&b=200
        // 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>

AddController:

@Controller
public class AddController {
    @RequestMapping("/add")
    @ResponseBody
    int add(int a,int b){
        int c= a+b;
        return  c;
    }
}

实现效果:

image.png 7.Sproing Boot打包

右侧导航栏选择Maven image.png

双击package

image.png 打包完成

image.png

运行测试jar包

image.png

出现Spring Boot的logo,运行成功

image.png