一、判断用户名是否存在
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<%--1、导入JQuery库--%>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(function () {
$(":input[name='username']").change(function () {
var val=$(this).val();
val=$.trim(val);
if (val!="") {
var url="${pageContext.request.contextPath}/valiateUserName";
var args={"userName": val,"time":new Date()};
$.post(url,args,function (data) {
$("#message").html(data);
})
}
})
})
</script>
</head>
<body>
<form action="" method="post">
UserName: <input type="text" name="username">
<br>
<div id="message"></div>
<br>
<input type="submit" value="Submit">
<br>
</form>
</body>
</html>
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.util.Arrays;
import java.util.List;
@WebServlet(name ="valiateUserNameServlet",urlPatterns = "/valiateUserName",asyncSupported = true)
public class valiateUserNameServlet extends HttpServlet {
private static final long serialVersionUID=1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<String> userNames= Arrays.asList("AAA","BBB","CCC");
String userName=req.getParameter("userName");
String result=null;
if (userNames.contains(userName)) {
result="<font color='red'>该用户名已经被使用</font>";
} else {
result="<font color='green'>该用户名可以被使用</font>";
}
resp.setContentType("text/html;charset=utf-8");
resp.setCharacterEncoding("utf-8");
resp.getWriter().print(result);
}
}
二、加入购物车(jackson)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<%--1、导入JQuery库--%>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(function () {
var isHasCar="${sessionScope.sc==null}";
if (isHasCar=="true") {
$("#carstatus").hide();
} else {
$("#carstatus").show();
$("#bookName").text("${sessionScope.sc.bookName}");
$("#totalBookNumber").text("${sessionScope.sc.totalBookNumber}");
$("#totalMoney").text("${sessionScope.sc.totalMoney}");
}
$("a").click(function () {
$("#carstatus").show();
var url=this.href;
var args={"time": new Date()};
$.getJSON(url,args,function (data) {
$("#bookName").text(data.bookName);
$("#totalBookNumber").text(data.totalBookNumber);
$("#totalMoney").text(data.totalMoney);
});
return false;
});
})
</script>
</head>
<body>
<div id="carstatus">
<%-- 您已将xxx加入购物车,购物车中的书有xx本,总价格xxx钱。--%>
您已将  <span id="bookName"></span> 加入到购物车中,
购物车中的书有  <span id="totalBookNumber"></span> 本,
总价格  <span id="totalMoney"></span> 钱。
</div>
<br>
Java <a href="${pageContext.request.contextPath}/addToCar?id=Java&price=100">加入购物车</a>
<br><br>
Oracle <a href="${pageContext.request.contextPath}/addToCar?id=Oracle&price=200">加入购物车</a>
<br><br>
Structs2 <a href="${pageContext.request.contextPath}/addToCar?id=Structs2&price=300">加入购物车</a>
<br><br>
</body>
</html>
package com.join.beans;
import java.util.HashMap;
import java.util.Map;
public class ShoppingCar {
private Map<String, ShoppingCarItem> items=new HashMap<String, ShoppingCarItem>();
private String bookName;
public void addToCart(String bookName,int price) {
this.bookName=bookName;
if (items.containsKey(bookName)) {
ShoppingCarItem item=items.get(bookName);
item.setNumber(item.getNumber()+1);
} else {
ShoppingCarItem item=new ShoppingCarItem();
item.setBookName(bookName);
item.setPrice(price);
item.setNumber(1);
items.put(bookName,item);
}
}
public String getBookName() {
return bookName;
}
public int getTotalBookNumber() {
int total=0;
for (ShoppingCarItem item:items.values()) {
total+=item.getNumber();
}
return total;
}
public int getTotalMoney(){
int money=0;
for (ShoppingCarItem item:items.values()) {
money+=item.getNumber()*item.getPrice();
}
return money;
}
}
package com.join.beans;
public class ShoppingCarItem {
private int number;
private String bookName;
private int price;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
package com.join.Servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.join.beans.ShoppingCar;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet(name ="addToCarServlet",urlPatterns = "/addToCar",asyncSupported = true)
public class addToCarServlet extends HttpServlet {
private static final long serialVersionUID=1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String bookName=req.getParameter("id");
int price=Integer.parseInt(req.getParameter("price"));
HttpSession session=req.getSession();
ShoppingCar sc=(ShoppingCar) session.getAttribute("sc");
if (sc==null) {
sc=new ShoppingCar();
session.setAttribute("sc",sc);
}
sc.addToCart(bookName,price);
StringBuilder result=new StringBuilder();
result.append("{")
.append("\"bookName\": \""+bookName+"\"")
.append(",")
.append("\"totalBookNumber\": \""+sc.getTotalBookNumber()+"\"")
.append(",")
.append("\"totalMoney\": \""+sc.getTotalMoney()+"\"")
.append("}");
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
resp.getWriter().print(result);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>addToCarServlet</servlet-name>
<servlet-class>com.join.Servlet.addToCarServlet</servlet-class>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>addToCarServlet</servlet-name>
<url-pattern>/addToCar</url-pattern>
</servlet-mapping>
</web-app>