尚硅谷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域中的对象实现信息的显示. ...
随机推荐
- DataFrame-选择与切片
取得DataFrame对象reviews的description列的前10个值(或者说reviews前10行的description列): reviews.iloc[:10].loc[:,'descr ...
- Nuxt.js
nuxt.js简单来说是Vue.js的通用框架,最常用的就是SSR(服务端渲染),nuxt.js这个框架,用Vue开发多页面应用,并在服务端完成渲染,可以直接用命令把我们制作的vue项目生成为静态的h ...
- 报错:The server cannot be started because one or more of the ports are invalid. Open the server editor and correct the invalid ports.
今天重装eclipse和Tomcat,启动时候报标题错“The server cannot be started because one or more of the ports are invali ...
- Java实现 LeetCode 837 新21点(DP)
837. 新21点 爱丽丝参与一个大致基于纸牌游戏 "21点" 规则的游戏,描述如下: 爱丽丝以 0 分开始,并在她的得分少于 K 分时抽取数字. 抽取时,她从 [1, W] 的范 ...
- Java实现 LeetCode 677 键值映射(字典树)
677. 键值映射 实现一个 MapSum 类里的两个方法,insert 和 sum. 对于方法 insert,你将得到一对(字符串,整数)的键值对.字符串表示键,整数表示值.如果键已经存在,那么原来 ...
- Java实现 LeetCode 76 最小覆盖子串
76. 最小覆盖子串 给你一个字符串 S.一个字符串 T,请在字符串 S 里面找出:包含 T 所有字母的最小子串. 示例: 输入: S = "ADOBECODEBANC", T = ...
- Java中多态举例说明
这里我也就大概说一下他们的关系, 接口就是动物,然而每一个类就是一种动物 给猫有两个功能:叫和睡觉 狗:叫 在f方法里面可以把猫的功能实现 但不能实现狗的功能 在主方法里面有一个猫有一个狗 分别调用 ...
- java实现猜算式
题目:猜算式 你一定还记得小学学习过的乘法计算过程,比如: x 15 ------ 273 ------ 请你观察如下的乘法算式 *** x *** -------- *** *** *** ---- ...
- java实现括号的匹配
括号的匹配 下面的代码用于判断一个串中的括号是否匹配 所谓匹配是指不同类型的括号必须左右呼应,可以相互包含,但不能交叉 例如: -(-[-]-)- 是允许的 -(-[-)-]- 是禁止的 对于 mai ...
- css实现朋友圈照片排列布局
纯css实现朋友圈不同数量图片不同布局 首先可以打开朋友圈观察不同图片数量的几种布局,也可参考下图示例: 可以发现 除1张图片,4张图片特殊外,其他数量图片均使用一行三列的方式排列: 假设有如下HTM ...