零基础学习java------35---------删除一个商品案例,删除多个商品,编辑(修改商品信息),校验用户名是否已经注册(ajax)
一. 删除一个商品案例
将要操作的表格
思路图
前端代码
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Insert title here</title> </head> <body> <button> <a href="/day13/GetAllProducts">查詢商品列表</a> </button> <br /> <br /> <br /> <table border="1px" cellspacing="0" width="100%"> <tr> <th>id</th> <th>name</th> <th>category</th> <th>pnum</th> <th>description</th> <th>描述</th> </tr> <!-- 迭代获取数据,即遍历 --> <c:forEach items="${p_list }" var="product"> <tr> <td>${product.id}</td> <td>${product.name}</td> <td>${product.price}</td> <td>${product.category}</td> <td>${product.pnum}</td> <td>${product.description}</td> <td> <a href="/day13/DeleteOneProduct?id=${product.id }">删除</a> </td> </c:forEach> </table> </body> </html>
此处删除直接使用a标签发送请求,用form表单也可以,但写起来麻烦:
后段部分代码
servlet
DeleteOneProduct
public class DeleteOneProduct extends HttpServlet { private static final long serialVersionUID = 1L; DeleteOneService deleteOneService = new DeleteOneServiceImpl(); // 删除一个商品 protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); try { deleteOneService.deleteOneProduct(id); response.sendRedirect("/day13/GetAllProducts"); } catch (Exception e) { e.printStackTrace(); } } }
service层
DeleteOneService接口
public interface DeleteOneService { /** * 删除一个商品 */ public void deleteOneProduct(String id) throws Exception; }
接口实现类(DeleteOneServiceImpl)
public class DeleteOneServiceImpl implements DeleteOneService{ DeleteOneDao deleteOneDao = new DeleteOneDaoImpl(); @Override public void deleteOneProduct(String id) throws Exception { deleteOneDao.deleteOneProductFromDB(id); } }
dao层
DeleteOneDao接口
public interface DeleteOneDao { /** * 从数据库删除一个商品 */ public void deleteOneProductFromDB(String id) throws Exception; }
接口实现类(DeleteOneDaoImpl)
public class DeleteOneDaoImpl implements DeleteOneDao { // 创建数据库连接池,并放在静态代码块中 static QueryRunner runner; static { ComboPooledDataSource dataSource = new ComboPooledDataSource(); runner = new QueryRunner(dataSource); } /** * 从数据库中删除数据 */ @Override public void deleteOneProductFromDB(String id) throws SQLException { String sql = "delete from products where id= ?"; runner.update(sql, id); } }
二. 删除多个商品案例
思路:删除一个商品是前端发送删除请求(携带一个商品的id),删除多个商品则是前端发送删除请求(携带多个商品的id)
前端该如何选中多个商品呢?----->多选框,此处只能使用form表单,不然不能将多个id传至后端
前端代码
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Insert title here</title> </head> <body> <button> <a href="/day13/GetAllProducts">查詢商品列表</a> </button> <br /> <br /> <br /> <form action="/day13/DeleteManyProducts" method="POST"> <input type="submit" value="删除多个商品" /> <table border="1px" cellspacing="0" width="100%"> <tr> <th>id</th> <th>name</th> <th>category</th> <th>pnum</th> <th>description</th> <th>描述</th> </tr> <!-- 迭代获取数据,即遍历 --> <c:forEach items="${p_list }" var="product"> <tr> <td><input type="checkbox" name="id" value="${product.id}" /></td> <td>${product.name}</td> <td>${product.price}</td> <td>${product.category}</td> <td>${product.pnum}</td> <td>${product.description}</td> <td> <a href="/day13/DeleteOneProduct?id=${product.id }">删除</a> </td> </c:forEach> </table> </form> </body> </html>
部分截图
后段部分
DeleteManyProduct
public class DeleteManyProducts extends HttpServlet {
private static final long serialVersionUID = 1L;
ProductsService productsService = new ProductsServiceImpl();
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接收参数
String[] idList = request.getParameterValues("id");
for (String id : idList) {
try {
productsService.deleteManyProducts(id);
} catch (Exception e) {
e.printStackTrace();
}
}
response.sendRedirect("/day13/GetAllProducts");
}
}
其他部分类似删除第一个商品的案例
三 编辑(修改商品信息)
修改商品信息
(1)修改页面:添加一个修改商品的编辑页面
(2)点击编辑按钮,将当前的id发送到后台,后台根据此id查询商品
(3)将要修改的商品展示到点击编辑后跳转的页面上
(4)修改,将修改完的数据提交到后台,后台完成修改
(5)跳转到页面展示
大致步骤: 查询商品-->得到商品的列表---->点击编辑(传待修改---id)------>后台接收id信息并查询一条数据--->将数据放在域中,跳转(转发)至修改product信息页面(对应servlet:showProduct)---->表单提交修改后的数据---->后台(EditProduct)接收修改后的参数,经过层层调用,最终调用dao层的方法更新数据库信息------>重定向至查询所有商品的请求(GetAllProducts)
代码实现
第一部分:将要修改的商品查询并在页面上显示出来,然后修改
前端代码
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Insert title here</title> </head> <body> <form action="/day13/EditProduct" method="Post"> <input type="hidden" name="id" value="${product.id }" /><br/><br/> <input type="text" name="name" value="${product.name }" /><br/><br/> <input type="text" name="price" value="${product.price }" /><br/><br/> <input type="text" name="category" value="${product.category }" /><br/><br/> <input type="text" name="pnum" value="${product.pnum }" /><br/><br/> <input type="text" name="description" value="${product.description }" /><br/><br/> <button type="submit" >修改</button> </form> </body> </html>
后台部分
showProduct
public class showProduct extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ProductsService productsService = new ProductsServiceImpl();
try {
// 获取数据(id)
String id = request.getParameter("id");
Products product = productsService.getProductById(id);
// 将数据存入request域中
request.setAttribute("product", product);
// 转发
request.getRequestDispatcher("/edit.jsp").forward(request, response);;
} catch (Exception e) {
e.printStackTrace();
}
}
}
service层
接口
/**
* 根据商品id查询商品
* @param id
* @return
* @throws Exception
*/
public Products getProductById(String id) throws Exception;
实现类
// 根据id查询某个商品的信息
@Override
public Products getProductById(String id) throws Exception {
Products product = productsDao.getProductByIdFromDB(id);
return product;
}
dao层
接口
// 根据id从数据库中取一个商品
public Products getProductByIdFromDB(String id) throws Exception;
实现类
// 根据id从数据库中获取一个商品 @Override public Products getProductByIdFromDB(String id) throws Exception { String sql = "select * from products where id= ? "; Products product = runner.query(sql, new BeanHandler<>(Products.class), id); return product;
这部分代码运行的结果如下图
第二部分:点击上图修改后的代码
servlet
EditProduct
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ProductsService productsService = new ProductsServiceImpl();
try {
// 接收数据并存储至Products中
request.setCharacterEncoding("utf-8");
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
double price = Double.parseDouble(request.getParameter("price"));
String category = request.getParameter("category");
int pnum = Integer.parseInt(request.getParameter("pnum"));
String description = request.getParameter("description");
Products product = new Products(id, name, price, category, pnum, description);
productsService.editProductById(product);
response.sendRedirect("/day13/GetAllProducts");
} catch (Exception e) {
e.printStackTrace();
}
}
}
service
接口
/**
* 根据商品id编辑商品
* @param product
* @throws Exception
*/
public void editProductById(Products product) throws Exception;
实现类
// 根据id编辑某个商品的信息
@Override
public void editProductById(Products product) throws Exception {
productsDao.editProductByIdFromDB(product);
dao层
接口
// 根据id编辑数据库中某个商品
public void editProductByIdFromDB(Products product) throws Exception;
实现类
// 根据id编辑某个商品
@Override
public void editProductByIdFromDB(Products product) throws Exception {
String sql = "update products set name=?, price=?, category=?, pnum=?, description=? where id =?";
runner.update(sql, product.getName(), product.getPrice(), product.getCategory(), product.getPnum(), product.getDescription(),product.getId());
运行就能得到并在页面上显示修改后的页面
四. 校验用户名是否已经注册
1. Ajax
1.1 什么是ajax
Ajax(Asynchronous javaScript and XML)是一种异步请求或者发送数据的web开发技术,对于改善用户的体验和页面性能很有帮助。简单说,在不需要重新刷新页面的情况下,Ajax通过异步请求加载后台数据,并在网页上呈现出来。常见运用场景有表单验证是否登录成功、百度搜索下拉框提示等等
Ajax目的:提高用户体验,较少网络数据的传输量
1.2 Ajax原理
Ajax请求数据流程中最核心的依赖是浏览器提供的XMLHttpRequest对象,它相当于一个中间人,使得浏览器可以在发送HTTP请求与接收HTTP响应,浏览器接着做其他事情,等到XHR返回来的数据再渲染页面。理解
2. jQuery补充
jQuery对象
$(用来代表jQuery,这样写方便)对象 $()页面加载函数$(function(){})
选择器:选择要操作的元素
(1)id选择器 $("#id")
(2)class选择器 $(".class")
(3)元素选择器 $("div")
事件绑定:
$("#id").click(function(){}) :获取焦点
$("#id").blur(function(){}) :失去焦点
点击弹框
js对象(绑定事件时使用onclick)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <script type="text/javascript" src="../js/jquery-1.4.4.min.js"></script> <script type="text/javascript"> $(function(){ // 点击->弹框,js对象的绑定使用onclick document.getElementById("btn").onclick=function(){ alert("hello") } </script> <body> <button id="btn">点击</button> <input id="input" /> </body> </html>
jquery对象(绑定事件时用click)
// $.post,jquery对象的绑定使用click
$("#btn").click(function(){
$.post("/day14/AjaxDemo1")
})
失去焦点
$("#input").blur(function(){
$.post("/day14/AjaxDemo1")
})
3 发送请求(jquery的ajax请求方法)
3.1 $.post()
jQuery的ajax方法,异步的使用post方法请求后台
参数1 请求url
参数2 携带的请求数据(json格式)
参数3 请求成功以后执行的函数:接收后台数据 方法的参数类型可以为string Json xml html
参数4 json
案例(参数4不知道怎么放)
前端代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <script type="text/javascript" src="../js/jquery-1.4.4.min.js"></script> <script type="text/javascript"> //页面加载函数 $(function(){ $("#input").blur(function(){ $.post("/day14/AjaxDemo1",{"name":$("#input").val()},function(data){ alert(data) }) }) }) </script> <body> <button id="btn">点击</button> <input id="input" /> </body> </html>
AjaxDemo1代码
public class AjaxDemo1 extends HttpServlet { private static final long serialVersionUID = 1L; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.getWriter().write("这个世界会好吗"); } }
3.2 $.get()
形式与post相似
3.3 $.ajax
各参数代表什么
$.ajax({}) { url: “” , 路径 data:{}, 数据 type:””, 请求方式 post get dataType:”json” 默认的是text xml 接收请求成功后的响应数据的数据解析格式 success:function(data){ //data 成功时的回调函数 接收请求成功后的响应数据 回调函数体...... 将数据展示在页面 } }
案例
前端代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <script type="text/javascript" src="../js/jquery-1.4.4.min.js"></script> <script type="text/javascript"> $(function(){ $("#input").blur(function(){ $.ajax({ url:"/day14/AjaxDemo2", type:"POST", data:{"age":19}, dataType:"json", success:function(data){ alert(data.name) } }) }) }) </script> <body> <button id="btn">点击</button> <input id="input" /> </body> </html>
AjaxDemo2
public class AjaxDemo2 extends HttpServlet { private static final long serialVersionUID = 1L; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); System.out.println("haha"); String age = request.getParameter("age"); System.out.println(age); User user = new User("reba",22); String str = JSON.toJSONString(user); response.getWriter().write(str); } }
3.4 servlet模板
代码
package ${enclosing_package}; import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; public class ${primary_type_name} extends HttpServlet { private static final long serialVersionUID = 1L; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); } }
校验用户名是否注册
前端代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <script type="text/javascript" src="../js/jquery-1.4.4.min.js"></script> <script type="text/javascript"> $(function(){ $("#name").blur(function(){ $.ajax({ url:"/day14/AjaxDemo3", type:"POST", data:{"name":$("#name").val()}, dataType:"json", success:function(data){ if(data.status == 200){ $("#msg").html("<font color='green'>"+data.msg+"</font>") }else{ $("#msg").html("<font color='red'>"+data.msg+"</font>") } } }) }) }) </script> <body> <h1>注册页面</h1> <form action=""> 用户名<input type="text" id="name" name="username"/><span id="msg"></span> <br/><br/> 密 码<input type="password"><span id="msg"></span> <br/><br/> <button>注册</button> </form> </body> </html>
后端部分
servlet
AjaxDemo3
public class AjaxDemo3 extends HttpServlet { private static final long serialVersionUID = 1L; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); try { UserService userService = new UserServiceImpl(); String name = request.getParameter("name"); System.out.println(name); User user = userService.ajaxLogin(name); System.out.println(user); PageResult result = new PageResult(); if(user != null) { result.setStatus(400); result.setMsg("用户名已存在"); }else { result.setStatus(200); result.setMsg("可以注册"); } String res = JSON.toJSONString(result); System.out.println(res); response.getWriter().write(res); } catch (Exception e) { e.printStackTrace(); } } }
service
接口
public interface UserService { public User ajaxLogin(String name) throws Exception; }
接口实现类
public class UserServiceImpl implements UserService { UserDao userDao = new UserDaoImpl(); @Override public User ajaxLogin(String name) throws Exception { User user = userDao.getUserByUserNameFromDB(name); System.out.println("====1======"); return user; } }
dao
接口
public interface UserDao { //根据用户名查用户 public User getUserByUserNameFromDB(String name) throws Exception; }
接口实现类
public class UserDaoImpl implements UserDao{ static QueryRunner runner; static { ComboPooledDataSource dataSource = new ComboPooledDataSource(); runner = new QueryRunner(dataSource); } @Override public User getUserByUserNameFromDB(String name) throws Exception { String sql = "select * from user where username like ?"; //模糊查询 User user = runner.query(sql, new BeanHandler<>(User.class), "%"+name+"%"); return user; } }
pojo(略)