文章目录
1.Ajax验证用户名
1.程序框架图
2.修改MemberServlet
java
复制代码
//根据注册名判断数据库中是否存在并返回json格式的结果
public void isExistName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//获取用户名
String username = req.getParameter("username");
//判断是否存在
boolean res = memberService.isExistsUsername(username);
//返回json格式,使用map形式
Map<String, Boolean> map = new HashMap<>();
map.put("isExist", res);
//转换成json格式
Gson gson = new Gson();
String json = gson.toJson(map);
resp.getWriter().write(json);
}
3.修改login.jsp
js
复制代码
//绑定失去焦点事件
$("#username").blur(function () {
//获取信息,并向后端发送ajax请求
var username = $(this).val();
$.getJSON(
"memberServlet",
{
"action": "isExistName",
"username": username
},
function (data, status, xhr) {
//根据是否存在显示信息
if (data.isExist) {
$("span.errorMsg").text("用户名已存在!");
} else {
$("span.errorMsg").text("用户名可用!");
}
}
)
})
4.结果展示
2.Ajax判断验证码是否输入正确
1.修改MemberServlet
java
复制代码
//根据验证码判断是否正确,返回json格式的结果
public void judgementCodeText(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//获取验证码
String codeText = req.getParameter("codeText");
//获取验证码
HttpSession session = req.getSession();
Object kaptchaSessionKey = session.getAttribute(KAPTCHA_SESSION_KEY);
boolean res = false;
if (kaptchaSessionKey != null && ((String) kaptchaSessionKey).equalsIgnoreCase(codeText)) {
res = true;
}
//将信息保存在map中并以json格式返回
Map<String, Object> map = new HashMap<>();
map.put("judgementCodeText", res);
Gson gson = new Gson();
String json = gson.toJson(map);
resp.getWriter().write(json);
}
2.修改login.jsp
java
复制代码
//验证码绑定失去焦点事件
$("#code").blur(function () {
var codeText = $(this).val();
//发送Ajax请求
$.getJSON(
"memberServlet",
{
"action": "judgementCodeText",
"codeText": codeText
},
function (data, status, xhr) {
//根据是否存在显示信息
if (data.judgementCodeText) {
$("span.errorMsg").text("验证码正确!");
} else {
$("span.errorMsg").text("验证码错误!");
}
}
)
})
3.结果展示
3.Ajax添加购物车
1.程序框架图
2.修改CartServlet
java
复制代码
//根据物品信息添加到购物车,并以json格式返回数据
public void addItemByAjax(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//获取前端物品信息
Integer cartItemId = DataUtils.parseInt(req.getParameter("cartItemId"), -1);
String cartItemName = req.getParameter("cartItemName");
BigDecimal cartItemPrice = new BigDecimal(req.getParameter("cartItemPrice"));
//计算剩余数据项
Integer cartItemCount = 1;
BigDecimal cartItemTotalPrice = null;
//获取session
HttpSession session = req.getSession();
//获取存放物品信息的map
HashMap<Integer, CartItem> cart = (HashMap<Integer, CartItem>) session.getAttribute("Cart");
if (cart == null || cart.isEmpty()) { //如果map是空的或者没有数据
HashMap<Integer, CartItem> CartItemHashMap = new HashMap<>();
//只有一件,总价格就是一件的价格
cartItemTotalPrice = cartItemPrice;
//封装到bean中
CartItem cartItem = new CartItem(cartItemId, cartItemName, cartItemPrice, cartItemCount, cartItemTotalPrice);
CartItemHashMap.put(cartItemId, cartItem);
session.setAttribute("Cart", CartItemHashMap);
session.setAttribute("totalNum", cartItemCount);
session.setAttribute("allPrice", cartItemPrice);
} else {
//只要map里包含了同样的id则数量加一
if (cart.containsKey(cartItemId)) {
cartItemCount = cart.get(cartItemId).getCount() + 1;
}
//计算总价格
cartItemTotalPrice = cartItemPrice.multiply(new BigDecimal(cartItemCount));
//封装到bean中
CartItem cartItem = new CartItem(cartItemId, cartItemName, cartItemPrice, cartItemCount, cartItemTotalPrice);
cart.put(cartItemId, cartItem);
//重新计算总价和商品数量,并放到session中
CartItem.calTotalNumAndPrice(cart, session);
}
//将totalNum以json的形式返回
Map<String, Object> map = new HashMap<>();
map.put("cartTotalCount", (Integer) session.getAttribute("totalNum"));
Gson gson = new Gson();
String json = gson.toJson(map);
resp.getWriter().write(json);
}
2.修改index.jsp
3.解决问题---未登录直接添加购物车,ajax请求无法重定向到登录页面
1.解决方案
2.编写WebUtils判断是否是ajax请求
java
复制代码
package com.sxs.furns.utils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author 孙显圣
* @version 1.0
*/
public class WebUtils {
//判断是否是ajax请求
public static boolean isAjaxRequest(HttpServletRequest request, HttpServletResponse response) {
return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
}
}
3.修改MemberAuthorization(过滤器)
java
复制代码
package com.sxs.furns.filter;
import com.google.gson.Gson;
import com.sxs.furns.utils.WebUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* 普通权限认证
* @author 孙显圣
* @version 1.0
*/
public class MemberAuthorization implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpSession session = ((HttpServletRequest) servletRequest).getSession();
//进行普通权限认证
Object username = session.getAttribute("username");
Object admin = session.getAttribute("admin");
if (username != null || admin != null) {
//放行
filterChain.doFilter(servletRequest, servletResponse);
} else {
//如果不是ajax请求就正常执行
if (!WebUtils.isAjaxRequest((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse)){
//重定向到用户登录界面
((HttpServletResponse) servletResponse).sendRedirect("/jiaju_mail/views/member/login.jsp");
}
//如果是ajax请求,就返回一个url,以json形式
Map<String, Object> map = new HashMap<>();
map.put("url", "views/member/login.jsp");
String json = new Gson().toJson(map);
servletResponse.getWriter().write(json);
}
}
@Override
public void destroy() {
}
}
4.修改index.jsp
4.结果展示
1.未登录添加购物车,跳转到登录页面
2.登录之后添加购物车,ajax局部刷新
4.上传更新家居图片
1.需求分析
2.程序框架图
3.修改FurnServlet
java
复制代码
/**
* 读取表单信息,进行修改
*
* @param req
* @param resp
*/
public void updateFurn(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//判断是否为文件类型的表单
if (ServletFileUpload.isMultipartContent(req)) {
//构建一个解析上传文件数据的工具对象
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
//将这个对象给servletFileUpload,创建一个实例
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
//解决文件乱码
servletFileUpload.setHeaderEncoding("utf-8");
try {
//获取文件项列表
List<FileItem> list = servletFileUpload.parseRequest(req);
Furn furn = new Furn();
//ArrayList存储所有的普通表单字段
ArrayList<String> furnItems = new ArrayList<>();
//遍历文件项,判断是一个文件还是普通表单字段,做出不同的处理
for (FileItem fileItem : list) {
//普通表单字段处理
if (fileItem.isFormField()) {
//获取普通表单字段,添加到ArrayList中
String furnItem = fileItem.getString("utf-8");
furnItems.add(furnItem);
} else {
//文件项处理
//获取文件名,对名字进行处理,防止重名
String name = UUID.randomUUID() + "_" + System.currentTimeMillis() + fileItem.getName();
//创建将来要存放的目录,这里不加/也会被认为是上下文路径,跟地址栏无关,但是建议加上
String filePath = "/assets/images/product-image/";
//获取真实路径
String realPath = super.getServletContext().getRealPath(filePath);
//判断是否有这个目录,如果没有再创建
File file = new File(realPath);
if (!file.exists()) {
file.mkdirs();
}
//将文件拷贝到刚才创建的目录下
String fileFullPath = realPath + name;
fileItem.write(new File(fileFullPath));
//设置furn的imgPath
String imgPath = "assets/images/product-image/" + name;
furn.setImgPath(imgPath);
if (fileItem.getName() == null || "".equals(fileItem.getName())) {
//如果没有修改图片,则路径不变
//从数据库中查询该id对应的imgPath
//就这里查出来的结果跟数据库的imgPath结果不一致
Furn rawFurn = furnService.queryFurnById(DataUtils.parseInt(furnItems.get(0), 0));
imgPath = rawFurn.getImgPath();
}
furn.setImgPath(imgPath);
}
}
//将普通订单项结果放到furn中
furn.setId(DataUtils.parseInt(furnItems.get(0), 0));
furn.setName(furnItems.get(1));
furn.setMaker(furnItems.get(2));
furn.setPrice(new BigDecimal(furnItems.get(3)));
furn.setSales(DataUtils.parseInt(furnItems.get(4), 0));
furn.setStock(DataUtils.parseInt(furnItems.get(5), 0));
//获取pageNo
String pageNo = req.getParameter("pageNo");
//执行更新操作
if (furnService.updateFurn(furn)) {
//更新成功则重定向到展示页面
resp.sendRedirect(super.getServletContext().getContextPath() + "/manage/furnServlet?action=page&pageNo=" + pageNo);
} else {
System.out.println("更新失败");
}
} catch (FileUploadException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
4.修改furn_update.jsp
1.样式
java
复制代码
<style type="text/css">
/* 整体表格样式 */
.table-content table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
}
.table-content th,
.table-content td {
text-align: left;
padding: 12px;
border-bottom: 1px solid #ddd;
}
.table-content th {
background: linear-gradient(120deg, #006c70, #00b2a9);
color: #ffffff;
text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
}
.table-content tr:hover {
background-color: #f5f5f5;
}
/* 上传文件部分的样式 */
.table-content .product-thumbnail {
display: flex;
flex-direction: column;
align-items: center;
position: relative;
margin: 20px auto;
}
.table-content input[type="file"] {
width: 200px;
height: 200px;
opacity: 0;
position: absolute;
cursor: pointer;
z-index: 2; /* 确保文件输入位于图片上方 */
}
.table-content img {
border-radius: 50%;
width: 150px;
height: 150px;
object-fit: cover; /* 确保图片不会失真 */
border: 2px solid #009688; /* 图片边框颜色与表头一致 */
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); /* 轻微的阴影效果 */
}
/* 自定义文件上传提示样式 */
.product-thumbnail::before {
content: '点击或拖拽上传图片';
position: absolute;
width: 200px;
height: 200px;
background-color: rgba(0, 150, 136, 0.9);
color: white;
display: flex;
justify-content: center;
align-items: center;
text-align: center;
border-radius: 50%;
font-size: 16px;
transition: all 0.3s ease;
opacity: 0;
z-index: 1;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
font-weight: 600;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.product-thumbnail:hover::before {
opacity: 1;
}
/* 调整提交按钮样式 */
.table-content input[type="submit"] {
background: linear-gradient(120deg, #31B0D5, #2196F3);
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
transition: background-color 0.3s ease;
cursor: pointer;
font-size: 16px;
text-transform: uppercase;
letter-spacing: 1px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.table-content input[type="submit"]:hover {
background-color: #2196F3;
}
/* 响应式设计 */
@media (max-width: 768px) {
.product-thumbnail {
width: 150px;
height: 150px;
}
.product-thumbnail input[type="file"] {
width: 150px;
height: 150px;
}
.product-thumbnail img {
width: 150px;
height: 150px;
}
.product-thumbnail::before {
width: 150px;
height: 150px;
font-size: 14px;
}
.table-content input[type="submit"] {
padding: 8px 16px;
}
}
</style>
<script type="text/javascript">
function prev(event) {
//获取展示图片的区域
var img = document.getElementById("prevView");
//获取文件对象
var file = event.files[0];
//获取文件阅读器: Js的一个类,直接使用即可
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
//给img的src设置图片url
img.setAttribute("src", this.result);
}
}
</script>
3.修改td
5.解决bug,写sql的时候注意映射,映射,映射!!!(卡了2个小时才发现,醉了)
6.结果展示
1.点击上传图片
2.查看效果
3.点击修改家居,回到原页面
5.上传添加家居图片
1.修改FurnServlet
java
复制代码
/**
* 添加家居并重新获取家居信息,重定向到furn_manage.jsp
*
* @param req
* @param resp
*/
public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException, InvocationTargetException, IllegalAccessException {
//判断是否为文件类型的表单
if (ServletFileUpload.isMultipartContent(req)) {
//构建一个解析上传文件数据的工具对象
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
//将这个对象给servletFileUpload,创建一个实例
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
//解决文件乱码
servletFileUpload.setHeaderEncoding("utf-8");
try {
//获取文件项列表
List<FileItem> list = servletFileUpload.parseRequest(req);
Furn furn = new Furn();
//ArrayList存储所有的普通表单字段
ArrayList<String> furnItems = new ArrayList<>();
//遍历文件项,判断是一个文件还是普通表单字段,做出不同的处理
for (FileItem fileItem : list) {
//普通表单字段处理
if (fileItem.isFormField()) {
//获取普通表单字段,添加到ArrayList中
String furnItem = fileItem.getString("utf-8");
furnItems.add(furnItem);
} else {
//文件项处理
//获取文件名,对名字进行处理,防止重名
String name = UUID.randomUUID() + "_" + System.currentTimeMillis() + fileItem.getName();
//创建将来要存放的目录,这里不加/也会被认为是上下文路径,跟地址栏无关,但是建议加上
String filePath = "/assets/images/product-image/";
//获取真实路径
String realPath = super.getServletContext().getRealPath(filePath);
//判断是否有这个目录,如果没有再创建
File file = new File(realPath);
if (!file.exists()) {
file.mkdirs();
}
//将文件拷贝到刚才创建的目录下
String fileFullPath = realPath + name;
fileItem.write(new File(fileFullPath));
//设置furn的imgPath
String imgPath = "assets/images/product-image/" + name;
furn.setImgPath(imgPath);
if (fileItem.getName() == null || "".equals(fileItem.getName())) {
//如果没有修改图片,则路径设置默认的
imgPath = "assets/images/product-image/default.jpg";
}
furn.setImgPath(imgPath);
}
}
//将普通订单项结果放到furn中
furn.setName(furnItems.get(0));
furn.setMaker(furnItems.get(1));
furn.setPrice(new BigDecimal(furnItems.get(2)));
furn.setSales(DataUtils.parseInt(furnItems.get(3), 0));
furn.setStock(DataUtils.parseInt(furnItems.get(4), 0));
//获取pageNo
String pageNo = req.getParameter("pageNo");
//插入到数据库
if (furnService.add(furn)) {
//插入成功则重定向到家居显示的servlet
resp.sendRedirect(super.getServletContext().getContextPath() + "/manage/furnServlet?action=page&pageNo=" + pageNo);
} else {
System.out.println("插入失败");
}
} catch (FileUploadException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
2.修改furn_add.jsp
1.前端样式与前面一样
3.修改td
3.结果展示
1.准备添加家居
2.效果展示
3.添加之后