String留言板
1.概念
2.接口约定
3.后端代码
package com.bite.springmvc;
import lombok.Data;
@Data
public class MessageInfo {private String from;private String to;private String msg;
}
package com.bite.springmvc;import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;import java.util.ArrayList;
import java.util.List;@RequestMapping("/message")
@RestController
public class MessageController {//存储留言信息private List<MessageInfo> messageInfoList = new ArrayList<>();@RequestMapping(value = "/publish", method = RequestMethod.POST)public boolean publish(@RequestBody MessageInfo messageInfo){messageInfoList.add(messageInfo);return true;}@RequestMapping("/getList")public List<MessageInfo> getList(){return messageInfoList;}
}
4.测试
5.前端代码
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>留言板</title><style>.container {width: 350px;height: 300px;margin: 0 auto;/* border: 1px black solid; */text-align: center;}.grey {color: grey;}.container .row {width: 350px;height: 40px;display: flex;justify-content: space-between;align-items: center;}.container .row input {width: 260px;height: 30px;}#submit {width: 350px;height: 40px;background-color: orange;color: white;border: none;margin: 10px;border-radius: 5px;font-size: 20px;}</style>
</head><body><div class="container"><h1>留言板</h1><p class="grey">输入后点击提交, 会将信息显示下方空白处</p><div class="row"><span>谁:</span> <input type="text" name="" id="from"></div><div class="row"><span>对谁:</span> <input type="text" name="" id="to"></div><div class="row"><span>说什么:</span> <input type="text" name="" id="say"></div><input type="button" value="提交" id="submit" onclick="submit()"><!-- <div>A 对 B 说: hello</div> --></div><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script><script>$.ajax({type:"get",url:"/message/getList",success:function(messages){if(messages!=null){for(var message of messages){var divE = "<div>"+message.from+"对"+message.to+"说"+message.msg+"</div>";$(".container").append(divE)}}}})</script>
</body></html>
apend把这个for循环添加到container这个div下面