【JavaEE】简单前后端分离小项目-表白墙

plus版表白墙!✿✿ヽ(°▽°)ノ✿

在这里插入图片描述

JavaEE & 简单前后端分离小项目 - 表白墙

在前面的学习中,我们已经制作了表白墙的页面,并且学习了HTTP、Tomcat、Servlet的知识,而这些知识,就相当于一句英语句子的单词或者字母,通过这些,就可以开始做一些小项目了!

  1. JavaEE & Servlet的API详解_s:103的博客-CSDN博客
  2. JavaScript实战训练小项目 & WebAPI_s:103的博客-CSDN博客

而我对表白墙的优化就是,服务器不关闭,刷新也不会把之前填的都删除

1. body格式约定 - 应用层协议

  • 这里,body我采取的格式是json
    • 应用层协议没有什么必须不必须的,只是json流行,整齐,有api(解析和包装和包装得好),程序员爱好等等…

在这里插入图片描述

通过前端代码,并且根据实际上所实现的功能,得出json应该有的键值对:
在这里插入图片描述

以此构造后端对象:

class Love {
    public String from;
    public String to;
    public String love;

    @Override
    public String toString() {
        return "Love{" +
            "from='" + from + '\'' +
            ", to='" + to + '\'' +
            ", love='" + love + '\'' +
            '}';
    }
}

2. 后端处理请求

2.1 模板

  • 与json对应的对象Love
class Love {
    public String from;
    public String to;
    public String love;

    @Override
    public String toString() {
        return "Love{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", love='" + love + '\'' +
                '}';
    }
}
  • Servlet程序(/love),继承HttpServlet
    • doGet方法 => 浏览器访问前端页面,后端应该响应已有的“甜言蜜语”集合,即Love集合(list)
    • doPost方法 => 浏览器前端页面发送“甜言蜜语”,后端应该将这段“甜言蜜语”放进Love集合
  • ObjectMapper则是,json转换器
@WebServlet("/love")
public class ShowLove extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    private List<Love> list = new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
    }
}

注意:

  • 要引入一些依赖(刷新触发加载)

在这里插入图片描述

其他设置跟之前一样,不做讲解

2.2 doGet方法

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //如果有输入操作互动的操作,在这里refresh是不合理的,因为写着写着就刷新了,体验不好
    // 所以在这里设置refresh没用!

    //转换为json字符串!
    String result = objectMapper.writeValueAsString(list);
    resp.setContentType("application/json; charset=utf8");
    resp.getWriter().write(result);

}
  1. 将Love集合list,通过ObjectMapper调用writeValueAsString方法去转化为json字符串
  2. 设置响应的格式为json,字符集为utf8
  3. 获取响应的输出流,将后端代码的json字符串输出出去,投喂给请求发起者的前端代码

在这里插入图片描述

2.3 doPost方法

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Love love = objectMapper.readValue(req.getInputStream(), Love.class);
    list.add(love);
    //默认返回的就是200 ok的空body报文
}
  1. 获取请求body的输入流(输入,即前端制作的请求投喂给后端代码),并且连同Love.class类对象传入ObjectMapper的readValue方法
  2. 在Love集合中添加这一条“甜言蜜语”

在这里插入图片描述

后端代码就这么多了

  • 是不是很简单 ^ v ^

3. 前端制作请求并解析响应

3.1 原前端页面的代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="pursue.css" />
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <title>表白墙</title>
  </head>
  <body>
    <div class="container">
      <div class="container-left">
        <div class="card">
          <form action="#">
            <h1>表白</h1>
            <div class="row">
              谁:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input
                type="text"
                id="c1"
              />
            </div>
            <div class="row">想对谁:<input type="text" id="c2" /></div>
            <div class="row">
              说:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input
                type="text"
                id="c3"
              />
            </div>
            <div class="print">
              <div class="s">
                <input type="button" value="发送" id="go" onclick="send()" />
              </div>
            </div>
          </form>
        </div>
      </div>
      <div class="container-right">
        <div class="article" id="a">
          <h1 style="font-size: 50px"></h1>
        </div>
      </div>
    </div>
    <script>
      function send() {
        var text1 = jQuery("#c1");
        var text2 = jQuery("#c2");
        var text3 = jQuery("#c3");

        if (text1.val().trim() == "") {
          alert("请输入是谁!");
          text1.focus();
          return;
        }
        if (text2.val().trim() == "") {
          alert("请输入想对谁说!");
          text2.focus();
          return;
        }
        if (text3.val().trim() == "") {
          alert("请输入想说什么!");
          text3.focus();
          return;
        }
        var loveWords =
          "<br><h2>" +
          text1.val() +
          " 想对 " +
          text2.val() +
          " 说 “" +
          text3.val() +
          "”!</h2>";
        jQuery("#a").append(loveWords);
        text1.val("");
        text2.val("");
        text3.val("");
    </script>
  </body>
</html>

css代码:

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}
html {
  height: 100%;
}
body {
  background-image: url(海.jpg);
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
  height: 100%;
}
.container {
  /* 固定宽度 */
  width: 1000px;
  margin: 0 auto;
  height: 100%;

  display: flex;
  justify-content: space-between;
}

/* 增加可读性 */
.container .container-left {
  height: 100%;
  width: 25%;
}

.container .container-right {
  height: 100%;
  width: 74%;
}
.card {
  margin-top: 10px;
  height: 245px;
  width: 100%;
  background-color: rgba(255, 255, 255, 0.8);

  border-radius: 25px;
}
.article {
  margin-top: 10px;
  height: calc(100% - 10px);
  width: 100%;
  background-color: rgba(255, 255, 255, 0.8);

  border-radius: 15px;
  padding: 5px 20px;
  overflow: auto;
  /* 内容溢出,滚动条放入这里 */
}
.article h2 {
    color: rgba(251, 114, 153, 0.8);
}

.card h1 {
  font-size: 50px;
  text-align: center;
  margin-top: 15px;
  margin-bottom: 15px;
}
.row {
  height: 30px;
  width: 100%;
  display: flex;
  justify-content: space-around; /*设置flex的原因就是要用这个*/
  align-items: center;
  font-size: 15px;
  margin: 5px;
  font-weight: 900;
}
#c1 {
  width: 120px;
  height: 19px;
  font-size: 12px;
  text-indent: 4px;
  border-radius: 4px;
  font-weight: 900;
  color: rgba(251, 114, 153, 0.7);
}
#c2 {
  width: 120px;
  height: 19px;
  font-size: 12px;
  text-indent: 4px;
  border-radius: 4px;
  font-weight: 900;
  color: rgba(251, 114, 153, 0.7);
}
#c3 {
  width: 120px;
  height: 19px;
  font-size: 12px;
  text-indent: 4px;
  font-weight: 900;
  border-radius: 4px;
  font-weight: 900;
  color: rgba(251, 114, 153, 0.7);
}
.print {
  display: flex;
  justify-content: center;
  align-items: center;
}
.s #go {
  width: 150px;
  height: 25px;
  background-color: rgba(0, 0, 0, 0.4);
  color: white;
  font-weight: 900;
  line-height: 25px;
  text-align: center;
  border-radius: 10px;
  border: none;
  margin-top: 10px;
  transition: all 0.618s;
}
#go:hover {
  background-color: rgba(251, 114, 153, 0.7);
}

背景图:

在这里插入图片描述

呈现:

在这里插入图片描述

html文件正确位置:
在这里插入图片描述

目的:

  • 与服务器拥有同样的域名,避免出现ajax的跨域问题!!!

3.2 刷新时发送GET请求

  • 前端代码对json的处理,就在jquery里~(已包含)

在js标签中的一开始,加入这一段:

用ajax去构造请求:

  1. type对应Method(GET)
  2. url对应注解名
    • 由于html在webapp下,所以用相对路径,写context path即可,也就是程序的注解名

回调函数success的步骤:

  • 浏览器收到响应自动解析body为body这个对象数组(Love[ ])
  • 通过for of或者其他去遍历它
  • jQuery的api,把“甜言蜜语”追加在右侧墙上!
function getLoves() {
    jQuery.ajax({
        type: "GET",
        url: "love",
        success: function (body) {
            //body就是数组
            for (var word of body) {
                var result =
                    "<br><h2>" +
                    word.from +
                    " 想对 " +
                    word.to +
                    " 说 “" +
                    word.love +
                    "”!</h2>";
                jQuery("#a").append(result);
            }
        },
    });
}
getLoves();

在这里插入图片描述

3.3 点击发送时构造Post请求

  • 这个方法是点击发送时触发的
function send() {
    var text1 = jQuery("#c1");
    var text2 = jQuery("#c2");
    var text3 = jQuery("#c3");
    if (text1.val().trim() == "") {
        alert("请输入是谁!");
        text1.focus();
        return;
    }
    if (text2.val().trim() == "") {
        alert("请输入想对谁说!");
        text2.focus();
        return;
    }
    if (text3.val().trim() == "") {
        alert("请输入想说什么!");
        text3.focus();
        return;
    }
    var loveWords =
        "<br><h2>" +
        text1.val() +
        " 想对 " +
        text2.val() +
        " 说 “" +
        text3.val() +
        "”!</h2>";
    jQuery("#a").append(loveWords);

    var body = {
        from: text1.val(),
        to: text2.val(),
        love: text3.val(),
    };
    jQuery.ajax({
        type: "POST",
        url: "love",
        contentType: "application/json; charset=utf8",
        data: JSON.stringify(body),
        //json的一些方法就在jquery里了
    });

    text1.val("");
    text2.val("");
    text3.val("");
}

修改之处:

  • 通过用户输入的三个字符串,构造json对应的对象body

  • ajax中:

    • type对应Method(POST)
    • url对应注解名
    • contentType对应body的格式
    • 调用JSON.stringfy方法,解析这个对象为字符串,并赋值个data成员(此成员对应post请求的body)

在这里插入图片描述
在这里插入图片描述

3.4 再优化

  • 这个html虽然还没放到云服务器上,别的网络是访问不了的,但是连着服务器所在机器的热点的设备,是可以访问的,这里我以手机为例
  • 我们希望不通过刷新就能获取到对方设备的“甜言蜜语”
    • js的异步来处理之后再讲
    • 想法:每次成功发送的时候,就刷新一次右侧墙

修改1:

右侧墙对应的html元素:

在这里插入图片描述
修改2:

  • 由于更改了html源码,因此对应的css代码也要更改

在这里插入图片描述

  • 理论上这一点可以不加,但是规范点还是要给div加个限制空间
    • 这样就可以将滚动条放到这个div中,不会把“墙”字滚没!

按住ctrl + f5强制刷新,避免浏览器缓存导致css改变没有被识别

修改3:

  • 提交时更新一次墙
  • 修改send方法

在这里插入图片描述

4. 测试

  1. 启动服务器
  2. 浏览器打开html

注意:

打开html不能在文件管理器双击打开,因为这样就是在本地打开,就会导致ajax的跨域问题!

  • 正确的应该是通过这个路径访问:

在这里插入图片描述

在这里插入图片描述

输入测试:

在这里插入图片描述

用连着机器的热点的手机表白:

在这里插入图片描述

在浏览器重新输入:

在这里插入图片描述

滚动条测试:

在这里插入图片描述


文章到此结束!谢谢观看
可以叫我 小马,我可能写的不好或者有错误,但是一起加油鸭🦆

本文源码:showLove · 游离态/马拉圈2023年6月 - 码云 - 开源中国 (gitee.com)


评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

s:103

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值