尚硅谷ajax视频教程2
7、7. 尚硅谷_佟刚_Ajax_典型应用_验证用户名是否可用
整个项目的目录路径如下所示

我们首先新建立一个web工程,在webroot下面新建立一个script的文件夹,导入jquer文件
接下来我们编写index.jsp文件,通过ajax的方式校验该用户名是否在后台已经被注册
index.jsp文件内容如下所示:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <!-- 第一步导入jquery文件夹 -->
<script type="text/javascript" src="${pageContext.request.contextPath}/scripts/jquery-2.1.1.js"></script>
<script type="text/javascript">
//第二步: //第二步:
$(function(){
//选择所有 <input> 元素:$(":input")
//第二步获得name=username的结点
//第三步为username添加change事件
$("input[name='username']").change(function (){ //第四步获得username 对应的value的值,去掉前后空格,准备发送ajax
//$(this)是一个JQuery对象,this是当前的dom元素对象,使用$()可以将dom对象转化成jquery对象,这里就可以调用jquery的方法
var value= $(this).val();
//去掉前后的空格$.trim(str)的作用是去掉字符串首尾空格
value = $.trim(value);
alert(value);
if(value != ""){
//发送post请求
//请求的ur地址 UserNameServlet对应的是一个Servlet
var href="${pageContext.request.contextPath}/UserNameServlet";
//请求的提交给服务器的参数,参数必须满足json的字符串格式
var args={"username":value,"time":new Date()};
//result是客户端返回的结果
$.post(href,args,function(result){ //返回的是一个html片段<font color="red">该用户名已经被注册</font>
// 我们要将该结果嵌入到id=message的div标签中:<div id="message"><font color="red">该用户名已经被注册</font></div>
$("#message").html(result);
}); }
}); }) </script>
</head> <body>
<h2>查询用户名是否被注册</h2></br>
<!-- 首先需要建立一个表单 -->
<form action="" method="post" >
<input type="text" name="username" />
<input type="submit" valeu="submit"/>
</br>
<div id="message"></div>
</form>
</body>
</html>
在后台我们编写一个servlet用于处理客户端的请求
package com.weiyuan.test; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class UserNameServlet extends HttpServlet { /**
* Constructor of the object.
*/
public UserNameServlet() {
super();
} /**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { this.doPost(request, response);
} /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//首先获得客户端请求过来传递的参数
String username = request.getParameter("username");
System.out.println("username :"+username);
String result = "";
if(username != null){
if("aaa".equalsIgnoreCase(username) || "bbb".equalsIgnoreCase(username)){
result= "<font color='red'>该用户名已经被注册</font";
}else{
result= "<font color='green'>该用户名可以正常使用</font";
}
//设置服务器返回的数据是html文件
response.setContentType("text/html");
//将数据返回回去
response.getWriter().write(result);
}
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }
该servlet需要在web.xml中配置映射路径,web.xml配置文件如下所示
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>TestAjax</display-name>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>UserNameServlet</servlet-name>
<servlet-class>com.weiyuan.test.UserNameServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>UserNameServlet</servlet-name>
<url-pattern>/UserNameServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
我们来看看程序运行的效果


相当的经典。
8、8. 尚硅谷_佟刚_Ajax_典型应用_添加商品
现在我们要实现购物车中,当用户点击某条购物项的时候,页面不发生跳转能够自动的发生变化

当点击某个菜单项的数据的增删的时候总的书的数量和总价会自动的发生变化,我们采用ajax的方式来实现,页面不发生跳转
这里主要是后台实现比较复杂
这里的页面是由每一个购物车的菜单项构成的,由多个菜单项。一个菜单项应该包括:当前购买书的类型,当前购买的数量,以及当前购买书数量的价格
然后遍历每个菜单项就可以获得当前购物车总的数量和价格了
我们首先定义一个商品的实体类
package cn.itcast.shop.product.beans; import java.util.Date; /**
* 商品的实体对象
* @author 传智.郭嘉
*
*/
public class Product {
private Integer pid;
//商品的名称
private String pname;
//商品的市场价格
private Double market_price;
//商品的现场价格
private Double shop_price;
//商品的图片地址
private String image;
//商品的具体描述
private String pdesc;
//是否是热门商品
private Integer is_hot;
//商品的上传日期
private Date pdate; public Integer getPid() {
return pid;
}
public void setPid(Integer pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Double getMarket_price() {
return market_price;
}
public void setMarket_price(Double market_price) {
this.market_price = market_price;
}
public Double getShop_price() {
return shop_price;
}
public void setShop_price(Double shop_price) {
this.shop_price = shop_price;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getPdesc() {
return pdesc;
}
public void setPdesc(String pdesc) {
this.pdesc = pdesc;
}
public Integer getIs_hot() {
return is_hot;
}
public void setIs_hot(Integer is_hot) {
this.is_hot = is_hot;
}
public Date getPdate() {
return pdate;
}
public void setPdate(Date pdate) {
this.pdate = pdate;
} }
第二步我们新建立一个购物车的菜单项,里面包括弄购物的商品,购买当前商品的数量,购物车由多个购物项构成
package cn.itcast.shop.cart.beans; import cn.itcast.shop.product.beans.Product; /**
* 购物项对象
* @author 传智.郭嘉
*
*/
public class CartItem {
private Product product; // 购物项中商品信息
private int count; // 购买某种商品数量
private double subtotal; // 购买某种商品小计
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
// 小计自动计算的.
public double getSubtotal() {
return count * product.getShop_price();
}
/*public void setSubtotal(double subtotal) {
this.subtotal = subtotal;
}
*/ }
第三步:我们封装购物车对象,对购物车进行操作包括购物车的增删改查操作
package cn.itcast.shop.cart.beans; import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map; /**
* 购物车对象
*
* @author 传智.郭嘉
*
*/
public class Cart implements Serializable{
// 购物车属性
// 购物项集合:Map的key就是商品pid,value:购物项
private Map<Integer, CartItem> map = new LinkedHashMap<Integer, CartItem>(); // Cart对象中有一个叫cartItems属性.
public Collection<CartItem> getCartItems(){
return map.values();
} // 购物总计:
private double total; public double getTotal() {
return total;
} // 购物车的功能:
// 1.将购物项添加到购物车
public void addCart(CartItem cartItem) {
// 判断购物车中是否已经存在该购物项:
/*
* * 如果存在:
* * 数量增加
* * 总计 = 总计 + 购物项小计
* * 如果不存在:
* * 向map中添加购物项
* * 总计 = 总计 + 购物项小计
*/
// 获得商品id.
Integer pid = cartItem.getProduct().getPid();
// 判断购物车中是否已经存在该购物项:
if(map.containsKey(pid)){
// 存在
CartItem _cartItem = map.get(pid);// 获得购物车中原来的购物项
_cartItem.setCount(_cartItem.getCount()+cartItem.getCount());
}else{
// 不存在
map.put(pid, cartItem);
}
// 设置总计的值
total += cartItem.getSubtotal();
} // 2.从购物车移除购物项
public void removeCart(Integer pid) {
// 将购物项移除购物车:
CartItem cartItem = map.remove(pid);
// 总计 = 总计 -移除的购物项小计:
total -= cartItem.getSubtotal();
} // 3.清空购物车
public void clearCart() {
// 将所有购物项清空
map.clear();
// 将总计设置为0
total = 0;
}
}
这里需要注意的是在购物车的Cart类中封装了一个方法
// Cart对象中有一个叫cartItems属性.
public Collection<CartItem> getCartItems(){
return map.values();
}
将购物车的购物项封装成一个set集合,这样在jsp页面的时候就可以对cartItems集合进行遍历,相当于在Cart类之后定义一个cartItems成员变量,提供了外界可以访问的get方法
如下图片所示

现在我们写一个简单的页面,通过ajax模拟下面的操作获得对应总的数量和操作

package com.weiyuan.test; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import cn.itcast.shop.cart.beans.Cart;
import cn.itcast.shop.cart.beans.CartItem;
import cn.itcast.shop.product.beans.Product; public class ProductServlet extends HttpServlet { /**
* Constructor of the object.
*/
public ProductServlet() {
super();
} /**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { this.doPost(request, response);
} /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//默认都是添加操作
//首先获得你添加进来的商品的id和商品的价格
String product_id = request.getParameter("product_id");
String product_proce = request.getParameter("product_price");
System.out.println("product_id:"+product_id);
System.out.println("product_price"+product_proce);
//将字符串转化成id类型
int id = Integer.parseInt(product_id);
Double shop_price = Double.parseDouble(product_proce);
Product product = new Product();
if(id == 1){
//说明是java对象 product.setPid(1);
product.setPname("java");
product.setShop_price(shop_price); }
if(id == 2){
//说明是mysql对象
product.setPid(2);
product.setPname("mysql");
product.setShop_price(shop_price);
}
//创建一个购物车菜单项将购物车添加到菜单项中
CartItem cartItem = new CartItem();
cartItem.setProduct(product);
//默认每次都是购买一本
cartItem.setCount(1); //然后获得购物车
Cart cart = (Cart) request.getSession().getAttribute("cart");
if (cart == null) {
cart = new Cart();
request.getSession().setAttribute("cart", cart);
}
//cartItem添加到购物车中
cart.addCart(cartItem); //获得购物车中总的购买的商品和价格返回给客户端
//我们采用字符串 } /**
* 获得购物车的方法:从session中获得购物车.
* @return
*/
private Cart getCart() { return cart; }
尚硅谷ajax视频教程2的更多相关文章
- 尚硅谷ajax视频教程1
1.+尚硅谷_佟刚_Ajax_概述.wmv 2.+尚硅谷_佟刚_Ajax_使用+XMLHttpRequest+实现+Ajax.wmv XMLHttpRequest 对象提供了对 HTTP 协议的完全的 ...
- 尚硅谷maven视频教程笔记
07.尚硅谷_Maven_部署Maven核心程序.avi 第一步先安装jdk 第二步下载maven 特别需要注意的是maven不能存储在有中文和空格的目录下面 3.调试是否安装成功,在cmd中输入 m ...
- 尚硅谷Java视频教程导航(学习路线图)
最近很火,上去看了看,对于入门的人还是有点作用的,做个记号,留着以后学习. Java视频教程下载导航(学习路线图) 网站地址:http://www.atguigu.com/download.shtml
- 2018年尚硅谷《全套Java、Android、HTML5前端视频》
全套整合一个盘里:链接:https://pan.baidu.com/s/1nwnrWOp 密码:h4bw 如果分类里没有请下载下边那些小项教程链接 感谢尚硅谷提供的视频教程:http://www.at ...
- 尚硅谷《全套Java、Android、HTML5前端视频》
尚硅谷<全套Java.Android.HTML5前端视频> (百万谷粉推荐:史上最牛.最适合自学的全套视频.资料及源码) [尚硅谷官网资料导航] 谷粒学院在线学习:http://www.g ...
- 3、尚硅谷_SSM高级整合_使用ajax操作实现修改员工的功能
当我们点击编辑案例的时候,我们要弹出一个修改联系人的模态对话框,在上面可以修改对应的联系人的信息 这里我们我们要编辑按钮添加点击事件弹出对话框 第一步:在页面中在新增一个编辑联系人的模态对话框 第二步 ...
- 3、尚硅谷_SSM高级整合_使用ajax操作实现删除的功能
点击删除的时候,要删除联系人,这里同点击编辑按钮一样给删除按钮添加点击事件的时候不能使用 $(".delete_btn").click(function(){ }); 这种方式,因 ...
- 3、尚硅谷_SSM高级整合_使用ajax操作实现增加员工的功能
20.尚硅谷_SSM高级整合_新增_创建员工新增的模态框.avi 1.接下来当我们点击增加按钮的时候会弹出一个员工信息的对话框 知识点1:当点击新增的时候会弹出一个bootstrap的一个模态对话框 ...
- 2、尚硅谷_SSM高级整合_使用ajax操作实现页面的查询功能
16.尚硅谷_SSM高级整合_查询_返回分页的json数据.avi 在上一章节的操作中我们是将PageInfo对象存储在request域中,然后list页面解析request域中的对象实现信息的显示. ...
随机推荐
- Parrot os笔记本推荐
parrot os基于debian开发的,因此同样适用于其他linux:笔记本集显最好,linux直接适用于intel,不用手动切换显卡,大多数linux玩家及pentester不需要高性能显卡,当然 ...
- PAT1033 旧键盘打字 (20分) (关于测试点4超时问题)
1033 旧键盘打字 (20分) 旧键盘上坏了几个键,于是在敲一段文字的时候,对应的字符就不会出现.现在给出应该输入的一段文字.以及坏掉的那些键,打出的结果文字会是怎样? 输入格式: 输入在 2 ...
- ES6背记手册
ES6规范 阮一峰的ES6在线教程 在线图书--Exploring ES6 ES6 tutorials babel在线教程--https://babeljs.io/docs/en/learn.html ...
- MethodHandle(方法句柄)系列之二:方法句柄的简单使用
二话不说,上代码 /** * * @author LiuYeFeng<897908343@qq.com> * @date 2015年4月8日 下午10:41:13 * @CopyRigh ...
- Java实现 蓝桥杯VIP 算法训练 P0504
算法训练 P0504 时间限制:1.0s 内存限制:256.0MB Anagrams指的是具有如下特性的两个单词:在这两个单词当中,每一个英文字母(不区分大小写)所出现的次数都是相同的.例如,Uncl ...
- python IDE pycharm的安装与使用
Python开发最牛逼的IDE——pycharm (其实其它的工具,例如eclipse也可以写,只不过比较麻烦,需要安装很多的插件,所以说pycharm是最牛逼的) pycharm,下载专业版的,不要 ...
- 几种常见的dfs模板
判断从v出发是否能走到终点 bool dfs(v){ if(v is 终点)return true; if(v is 旧点)return false; 将v标记为旧点: 对和v相邻的每个节点u{ if ...
- Java 入门教程
Java 入门教程 Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言. Java可运行于多个平台,如Windows, Mac OS,及其他多种UNIX版本的系统 ...
- .net core3.1 abp动态菜单和动态权限(动态菜单实现和动态权限添加) (三)
我们来创建动态菜单吧 首先,先对动态菜单的概念.操作.流程进行约束:1.Host和各个Tenant有自己的自定义菜单2.Host和各个Tenant的权限与自定义菜单相关联2.Tenant有一套默认的菜 ...
- 【Vulnhub】FristiLeaks v1.3
靶机信息 下载连接 https://download.vulnhub.com/fristileaks/FristiLeaks_1.3.ova.torrent https://download.vuln ...