1. 后端数据准备
主要是准备商品名称和数量信息
package com.dyq.bean;
public class Commodity {
private String name;
private Integer num;
private Double price;
public Commodity() {
}
public Commodity(String name, Integer num, Double price) {
this.name = name;
this.num = num;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return "Commodity{" +
"name='" + name + '\'' +
", num=" + num +
", price=" + price +
'}';
}
}
package com.dyq.bean;
import java.util.HashMap;
import java.util.Map;
public class Shop {
private static Map<String, Object> commodities;
static {
commodities = new HashMap<>();
commodities.put("可乐", 0);
commodities.put("薯条", 0);
commodities.put("面包", 0);
commodities.put("矿泉水", 0);
}
public static Integer getCommodity(String name) {
return (Integer) commodities.get(name);
}
public static void setCommodity(String name, Integer num) {
commodities.put(name, num);
}
public static Map<String, Object> getCommodities() {
return commodities;
}
}
2. 后端接口准备(servlet)
package com.dyq.servlet;
import com.alibaba.fastjson.JSONObject;
import com.dyq.bean.Shop;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
@WebServlet("/shop")
public class shop extends HttpServlet {
//由于get/post只是请求实现的不同方式,所以可以相互调用,业务逻辑都一样
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
JSONObject json = new JSONObject(Shop.getCommodities());
resp.getWriter().write(json.toJSONString());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
- 注意@WebServlet(“”)的作用
- @WebServlet(“/shop”)
- 导入fastjson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
- fastjson的使用
- Map转 json
- json转 String
- resp.getWriter().write()的作用
3. 前端页面准备
<script>
$(function(){
init();
});
/** init 函数用来初始化商品 数目 */
function init() {
$.ajax({
type:'get',
url:'/dyq/shop'
}).then(function (result) {
let res = JSON.parse(result);
$("#table").append("<tr><td>商品名称</td><td>商品数量</td></tr>")
for (let key in res) {
$("#table").append("<tr><td>"+key+"</td><td>"+res[key]+"</td></tr>")
}
})
}
function edit() {
$.ajax({
type:'get',
url:'dyq/edit',
data:{
shopName:document.getElementById("shopName").value,
number:$("#number").val()
}
}).then(function (res) {
console.log(res)
})
}
</script>