Ajax-验证用户名是否可用&典例应用之修改购物车
作者:互联网
Ajax
验证用户名是否可用
-
在WebContent下新建app1文件夹,文件夹下有index.jsp
-
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <!-- 1.导入jQuery库 2.获取name="username"的节点:username 3.为username添加change响应函数 3.1获取username的value属性值,去除前后空格且不为空.准备发送Ajax请求 3.2发送Ajax请求 检验username是否可用 3.3在服务端直接返回一个html的片段 3.4在客户端浏览器把其直接添加到#message的html种 --> <script type="text/javascript" src="${pageContext.request.contextPath}/scripts/jquery-1.9.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"/> </form> </body> </html>
-
-
新建一个com.atguigu.ajax.app.servlets包,包下新建ValiateUserNameServlet.java的servlet
-
import java.io.IOException; import java.util.Arrays; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ValiateUserNameServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<String> userNames=Arrays.asList("AAA","BBB","CCC"); String userName=request.getParameter("userName"); String result=null; if(userNames.contains(userName)) { result="<font color='red'>该用户名已经被使用</font>"; }else { result="<font color='green'>该用户名可以使用</font>"; } response.setCharacterEncoding("UTF-8");; response.setContentType("text/html;charset=UTF-8"); response.getWriter().print(result); } }
-
web.xml文件配置
<servlet> <description></description> <display-name>ValiateUserNameServlet</display-name> <servlet-name>ValiateUserNameServlet</servlet-name> <servlet-class>com.atguigu.ajax.app.servlets.ValiateUserNameServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ValiateUserNameServlet</servlet-name> <url-pattern>/valiateUserName</url-pattern> </servlet-mapping>
-
-
效果
典型应用_添加商品
-
在src下添加com.atguigu.ajax.app.beans包,包下有ShoppingCart.java和ShoppingCartItem.java
-
ShoppingCart.java
import java.util.HashMap; import java.util.Map; import com.atguigu.ajax.app.beans.ShoppingCartItem; public class ShoppingCart { //存放ShoppingCartItem的Map: 键:书名 值:ShoppingCartItem对象 private Map<String,ShoppingCartItem> items=new HashMap<String,ShoppingCartItem>(); private String bookName; public void addToCart(String bookName,int price) { this.bookName= bookName; if(items.containsKey(bookName)) { ShoppingCartItem item=items.get(bookName); item.setNumber(item.getNumber()+1); }else { ShoppingCartItem item=new ShoppingCartItem(); item.setBookName(bookName); item.setPrice(price); item.setNumber(1); items.put(bookName, item); } } public int getTotalBookNumber() { int total=0; for(ShoppingCartItem item:items.values()) { total+=item.getNumber(); } return total; } public int getTotalMoney() { int money=0; for(ShoppingCartItem item:items.values()) { money+=item.getNumber() * item.getPrice(); } return money; } public String getBookName() { return bookName; } }
-
ShoppingCartItem.java
public class ShoppingCartItem { 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; } }
-
-
在com.atguigu.ajax.app.servlets包下新建一个servlet
-
com.atguigu.ajax.app.servlets
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.atguigu.ajax.app.beans.ShoppingCart; import com.fasterxml.jackson.databind.ObjectMapper; public class AddToCartServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.获取请求参数: id,price String bookName=request.getParameter("id"); int price=Integer.parseInt(request.getParameter("price")); //2.获取购物车对象 HttpSession session=request.getSession(); ShoppingCart sc=(ShoppingCart) session.getAttribute("sc"); if(sc == null) { sc=new ShoppingCart(); session.setAttribute("sc", sc); } //3.把点击的选项加入到购物车中 sc.addToCart(bookName, price); //4.准备响应的JSON对象{"bookName":"","totalBookNumber":1,"totalMoney":1} //如从服务器返回JSON字符串,则属性名必须使用双引号 // StringBuilder result=new StringBuilder(); // result.append("{") // .append(" \"bookName \" : \" "+bookName+ " \" ") // .append(",") // .append(" \" totalBookNumber \" :" +sc.getTotalBookNumber()) // .append(" ,") // .append(" \" totalMoney \" :"+sc.getTotalMoney()) // .append("}"); //此处使用了JackSon,比上面代码简便许多 ObjectMapper mapper=new ObjectMapper(); String result=mapper.writeValueAsString(sc); System.out.println(result); //5.响应JSON对象 response.setContentType("text/javascript"); response.getWriter().print(result); } }
-
web.xml文件中配置
<servlet> <description></description> <display-name>AddToCartServlet</display-name> <servlet-name>AddToCartServlet</servlet-name> <servlet-class>com.atguigu.ajax.app.servlets.AddToCartServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AddToCartServlet</servlet-name> <url-pattern>/addToCart</url-pattern> </servlet-mapping>
-
为了使用JackSon需要导入三个jar包
jackson-annotations-2.2.1.jar
jackson-core-2.2.1.jar
jackson-databind-2.2.1.jar
-
-
在WebContent下新建app2的文件夹,文件夹下有index.jsp
-
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <!-- 1.获取当前页面的所有的a节点,并未每一个a节点都添加onclick响应函数,同时取消其默认行为 2.准备发送Ajax请求:url(a节点的href属性值); args(时间戳) 3.响应为一个JSON对象,包括:bookName,totalBookNumber,totalMoney 4.把对应的属性添加到对应的位置 --> <script type="text/javascript" src="${pageContext.request.contextPath}/scripts/jquery-1.9.1.min.js"></script> <script type="text/javascript"> $(function() { var isHashCart= "${sessionScope.sc == null}"; if(isHashCart == "true"){ $('#cartstatus').hide(); }else{ $('#cartstatus').show(); $("#bookName").text("${sessionScope.sc.bookName}"); $("#totalBookNumber").text("${sessionScope.sc.totalBookNumber}"); $("#totalMoney").text("${sessionScope.sc.totalBookMoney}"); } $("a").click(function() { $('#cartstatus').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="cartstatus"> 您已经将 <span id="bookName"></span> 加入购物车 购物车中的书有 <span id="totalBookNumber"></span> 本 总价格 <span id="totalMoney"></span> 钱 </div> <br><br> Java <a href="${pageContext.request.contextPath}/addToCart?id=Java&price=100">加入购物车</a> <br><br> Oracle <a href="${pageContext.request.contextPath}/addToCart?id=Oracle&price=200">加入购物车</a> <br><br> Struts2 <a href="${pageContext.request.contextPath}/addToCart?id=Struts2&price=100">加入购物车</a> <br><br> </body> </html>
-
-
效果图
使用JackSon
-
1)使用jar包
- jackson-annotations-2.2.1.jar
jackson-core-2.2.1.jar
jackson-databind-2.2.1.jar
- jackson-annotations-2.2.1.jar
-
2)具体的使用步骤
- Ⅰ创建org.codehaus.jackson.map.ObjectMapper对象
- Ⅱ 调用ObjectMapper的writerValueAsString方法把Java对象或集合转为JSON字符串
- ObjectMapper mapper=new ObjectMapper();
Customer customer =new Customer(“Xuefeng”,“1001”);
String jsonStr=mapper.writeValueAsString(customer); - List customers=Arrays.asList(customer,new Customer(“tianjinfeng”,“1002”));
jsonStr=mapper.writeValueAsString(customers);
- ObjectMapper mapper=new ObjectMapper();
- Ⅲ注意:
- ①JackSon根据getter来定位Json对象的属性,而不是字段
- ②可以在类的getter方法上添加注解:com.fasterxml.jackson.annotation.JsonIgnore在转为JSON对象可以忽略此属性!
-
测试
public class Customer { public Customer(String name, String id) { super(); this.name = name; this.id = id; } private String name; private String id; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCity() { return "BEIJING"; } @JsonIgnore public String getBirth() { return "2000-8-30"; } public static void main(String[] args) throws JsonProcessingException { //1.导入jar包 //2.创建ObjectMapper 对象 ObjectMapper mapper=new ObjectMapper(); //3.调用mapper的writerValueAsString()方法把一个对象转为一个JSON字符串 Customer customer =new Customer("Xuefeng","1001"); String jsonStr=mapper.writeValueAsString(customer); System.out.println(jsonStr); //4.注意 JackSon使用getter方法来定位JSON对象的属性 //5.可以通过注解import com.fasterxml.jackson.annotation.JsonIgnore; //来忽略某一个getter定义的属性 List<Customer> customers=Arrays.asList(customer,new Customer("tianjinfeng","1002")); jsonStr=mapper.writeValueAsString(customers); } }
标签:典例,String,bookName,购物车,Ajax,new,sc,import,public 来源: https://blog.csdn.net/Aqours/article/details/100833453