1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 登录和注销 基于Session的购物车案例 验证码的使用 防止表单重复提交

登录和注销 基于Session的购物车案例 验证码的使用 防止表单重复提交

时间:2023-08-20 07:25:51

相关推荐

登录和注销 基于Session的购物车案例 验证码的使用 防止表单重复提交

一:登录和注销:

登录login.jsp界面

<body><%//销毁sessionsession.invalidate();%><h3>用户登录</h3><apan style="color:red">${errorMsg}</apan><form action="/login" method="post">账号:<input type="text" name="username" required/><br/>密码:<input type="text" name="password" required/><br/><input type="submit" value=" 朕要登录 "/> </form></body>

设置登录商品列表的servlet

@WebServlet("/login")public class LoginServlet extends HttpServlet{private static final long serialVersionUID = 1L;private IUserDAO dao;public void init() throws ServletException {dao = new UserDAOImpl();}protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");//接收请求参数String username = req.getParameter("username");String password = req.getParameter("password");//调用业务方法处理请求User user = dao.getUserByUsername(username);//控制界面跳转if(user == null){req.setAttribute("errorMsg","亲,"+username+"该账号不存在或者被禁言,请联系管理员!");req.getRequestDispatcher("/login.jsp").forward(req, resp);return ;}//检测当前的账户密码是否正确if(!user.getPassword().equals(password)){req.setAttribute("errorMsg", "亲,"+username+"该账号或密码不正确");req.getRequestDispatcher("/login.jsp").forward(req, resp);return;}//把当前登录用户存储到Session中req.getSession().setAttribute("USER_IN_SESSION",user);resp.sendRedirect("/product");}}

跳转到商品列表的servlet

@WebServlet("/product")public class ProductServlet extends HttpServlet {private static final long serialVersionUID = 1L;private IProductDAO dao;public void init() throws ServletException {dao = new ProductDAOImpl();}//http://localhost/product 进入service方法,到底是保存,删除,查询//http://localhost/product?cmd=save //保存操作//http://localhost/product?cmd=delete //保存操作//http://localhost/product?cmd=edit //编辑操作//http://localhost/product //列表操作protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//--------------------------------------------//检查用户是否已经登录,判断session中是否存在USER_IN_SESSIONObject user = req.getSession().getAttribute("USER_IN_SESSION");if(user == null){resp.sendRedirect("/login.jsp");return ;}//--------------------------------------------req.setCharacterEncoding("UTF-8");String cmd = req.getParameter("cmd");if ("save".equals(cmd)) {this.saveOrUpdate(req, resp);} else if ("edit".equals(cmd)) {this.edit(req, resp);} else if ("delete".equals(cmd)) {this.delete(req, resp);} else {this.list(req, resp);}}//列表操作protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//1:接受请求参数,封装对象//2:调用业务方法处理请求List<Product> list = dao.list();req.setAttribute("p", list);//3:控制界面跳转req.getRequestDispatcher("/WEB-INF/views/product/product.jsp").forward(req, resp);}//编辑操作protected void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//1:接受请求参数,封装对象String sid = req.getParameter("id");if (haslength(sid)) {Long id = Long.valueOf(sid);//2:调用业务方法处理请求Product product = dao.get(id);req.setAttribute("p", product);}//3:控制界面跳转req.getRequestDispatcher("/WEB-INF/views/product/edit.jsp").forward(req, resp);}//删除操作protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {Long id = Long.valueOf(req.getParameter("id"));dao.delete(id);resp.sendRedirect(req.getContextPath()+"/product");}//新增或更新操作protected void saveOrUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String id = req.getParameter("id");String productName = req.getParameter("productName");String brand = req.getParameter("brand");String supplier = req.getParameter("supplier");BigDecimal salePrice = new BigDecimal(req.getParameter("salePrice"));BigDecimal costPrice = new BigDecimal(req.getParameter("costPrice"));//String cutoff = req.getParameter("cutoff");Long dir_id = Long.valueOf(req.getParameter("dir_id"));//Product product = new Product(productName,brand,supplier,salePrice,costPrice,cutoff,dir_id);Product p = new Product();p.setBrand(brand);p.setProductName(productName);p.setSupplier(supplier);p.setSalePrice(salePrice);p.setCostPrice(costPrice);p.setDir_id(dir_id);if (haslength(id)) {//更新p.setId(Long.valueOf(id));dao.update(p);} else {//新增dao.save(p);}resp.sendRedirect(req.getContextPath()+"/product");}private boolean haslength(String str) {return str != null && !"".equals(str.trim());}}

注销登录的servlet

@WebServlet("/logout")public class LogoutServlet extends HttpServlet{private static final long serialVersionUID = 1L;protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//方式1:删除session中key为USER_IN_SESSION的属性//req.getSession().removeAttribute("USER_IN_SESSION");//方式2:销毁session对象req.getSession().invalidate();//重新回到登录页面resp.sendRedirect("/login.jsp");}}

商品界面的JSP文件

<body><div align="center">当前登录用户:[${sessionScope.USER_IN_SESSION.username}]<a href="/logout">注销登录</a><!-- 此处也可以是"/login.jsp" --></div><hr/><a href="${pageContext.request.contextPath}/product?cmd=edit">添加商品</a><table border="1" width="80%" cellpadding="0" cellspacing="0"><tr style="background-color: orange"><th>id</th><th>productName</th><th>brand</th><th>supplier</th><th>salePrice</th><th>costPrice</th><th>cutoff</th><th>dir_id</th></tr><c:forEach items="${p}" var="p" varStatus="s"><tr style='background-color:${s.count % 2 == 0? "gray":""}'><td>${p.id}</td><td>${p.productName}</td><td>${p.brand}</td><td>${p.supplier}</td><td>${p.salePrice}</td><td>${p.costPrice}</td><td>${p.cutoff}</td><td>${p.dir_id}</td><td><a href="${pageContext.request.contextPath}/product?cmd=delete&id=${p.id}">删除</a><a href="${pageContext.request.contextPath}/product?cmd=edit&id=${p.id}">编辑</a></td></tr></c:forEach></table></body>

商品列表的添加跟编辑界面

<body> <div align="center">当前登录用户:[${sessionScope.USER_IN_SESSION.username}]<a href="/logout">注销登录</a><!-- 此处也可以是"/login.jsp" --></div><hr/><form action="${pageContext.request.contextPath}/product?cmd=save" method="post"><input type="hidden" name="id" value="${p.id}"/><br/>productName:<input type="text" name="productName" required value="${p.productName}"/><br/>brand:<input type="text" name="brand" required value="${p.brand}"/><br/>supplier:<input type="text" name="supplier" required value="${p.supplier}"/><br/>salePrice:<input type="number" name="salePrice" required value="${p.salePrice}"/><br/>costPrice:<input type="number" name="costPrice" required value="${p.costPrice}"/><br/>dir_id:<input type="number" name="dir_id" required value="${p.dir_id}"/><br/><br/><input type="submit" value='${p == null? "保存商品信息":"修改商品信息"}'/></form></body>

二:基于Session的购物车案例

购物车(ShoppingCart):生活:存放商品的小推车.应用:存储需要购买的商品信息. 购物车的设计:1):基于Session的购物车.购物车是存储到Session作用域的,浏览器一关闭购物车就没有了.2):基于Cookie的购物车.购物车是存储到Cookie中的,因为Cookie是存在浏览器中的,换一个浏览器,换一台电脑,不能共享购物车信息.3):基于Cookie + 数据库的购物车.购买商品时,如果还没有登录:此时就临时存储到Cookie中.购买商品时,如果已经登录,先读取Cookie中的数据,保存到数据库中,(任何位置都可以查看购物车信息)

商品列表JSP

<body><form action="/shoppingcart?cmd=save" method="post">商品名称:<select name="name"><option>iphone6s</option><option>ipad</option><option>iWatch</option></select><br/>购买数量:<input type="number" name="num" min="1" required/><br/><input type="submit" value=" 添加进购物车 "/></form></body>

从商品列表跳转到购物车列表的Servlet

@WebServlet("/shoppingcart")public class ShoppingCartServlet extends HttpServlet{private static final long serialVersionUID = 1L;protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");String cmd = req.getParameter("cmd");if("save".equals(cmd)){this.save(req, resp);}else if("delete".equals(cmd)){this.delete(req, resp);}resp.sendRedirect("/shoppingcart/cart_list.jsp");}//添加进购物车protected void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//1:接受请求参数String name = req.getParameter("name");String num = req.getParameter("num");String id = "";BigDecimal price = BigDecimal.ZERO;if("iphone6s".equals(name)){id = "123";price = new BigDecimal("5000");}else if("ipad".equals(name)){id = "456";price = new BigDecimal("3000");}else if("iWatch".equals(name)){id = "789";price = new BigDecimal("10000");}CartItem item = new CartItem(id,name,Integer.valueOf(num),price);//2:调用业务方法处理请求ShoppingCart cart = (ShoppingCart) req.getSession().getAttribute("SHOPPING_IN_SESSION");if(cart == null){cart = new ShoppingCart();req.getSession().setAttribute("SHOPPING_IN_SESSION",cart);}cart.save(item);//3:控制界面跳转}//从购物车中移除某个商品protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//1:接受请求参数String id = req.getParameter("id");//2:调用业务方法处理请求ShoppingCart cart = (ShoppingCart) req.getSession().getAttribute("SHOPPING_IN_SESSION");cart.delete(id);//3:控制界面跳转 }}

购物车列表

<body><h3>购物车列表</h3><table cellpadding="0" cellspacing="0" width="500" border="1"><tr><td>商品名称</td><td>零售价格</td><td>购买数量</td><td>操作</td></tr><c:if test="${empty SHOPPING_IN_SESSION.items}"><tr><td colspan="4">亲,购物车为空哦,快去<ahref="/shoppingcart/product_list.jsp">购物</a></td></tr></c:if><c:if test="${!empty SHOPPING_IN_SESSION.items}"><c:forEach items="${SHOPPING_IN_SESSION.items}" var="item"><tr><td>${item.name}</td><td>${item.price}</td><td>${item.num}</td><td><a href="/shoppingcart?cmd=delete&id=${item.id}">删除</a></td></tr></c:forEach><tr align="right"><td colspan="4">购物车总价:${SHOPPING_IN_SESSION.toalPrice}</td></tr></c:if></table></body>

购物车中的商品对象

@Datapublic class CartItem {private String id;private String name;private Integer num;private BigDecimal price;public CartItem() {}public CartItem(String id, String name, Integer num, BigDecimal price) {this.id = id;this.name = name;this.num = num;this.price = price;}}

购物车对象

public class ShoppingCart {//购物车中的多个商品对象private List<CartItem> items = new ArrayList<>();//购物车总价//private BigDecimal totalPrice;//把商品添加进购物车public void save(CartItem newItem) {for (CartItem item : items) {if (item.getId().equals(newItem.getId())) {item.setNum(item.getNum() + newItem.getNum());return;}}items.add(newItem);}//从购物车中移除指定ID的商品public void delete(String id){Iterator<CartItem> it = items.iterator();while(it.hasNext()){CartItem item = it.next();if(item.getId().equals(id)){//items.remove(item);//错误的it.remove();break;}}}//购物车中所有的商品public List<CartItem> getItems() {return items;}//购物车总价public BigDecimal getToalPrice(){BigDecimal totalPrice = BigDecimal.ZERO;for (CartItem item : items) {totalPrice = totalPrice.add(new BigDecimal(item.getNum()).multiply(item.getPrice()));}return totalPrice;}}

三:验证码的使用:

作用:防止恶意破解密码,刷票,论坛灌水,刷页.一般来说:互联网上的系统(登录/注册,发帖)等必须使用验证码.企业管理系统(MIS),就只能是企业内部访问,可以不需要验证码.

使用验证码进行登录的操作:![使用验证码进行登录的流程图](http://img./0309183934928?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2VpeGluXzQwMTYxNzA4/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)![用户登录的jsp流程图](http://img./0309184107276?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2VpeGluXzQwMTYxNzA4/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)

用户的jsp登录界面

<title>Insert title here</title><script type="text/javascript">function change(){//重新设置<img>元素的src属性document.getElementById("randomCodeImg").src="/randomCode?"+new Date().getTime();}</script><script type="text/javascript"></script></head><body> <h3>用户登录</h3><apan style="color:red">${errorMsg}</apan><form action="/randomLogin" method="POST">账&emsp;号:<input type="text" name="username" required/><br/>密&emsp;码:<input type="password" name="password" required/><br/>验证码:<input type="text" name="randomCode" size="5" maxlength="5" required/><img src="/randomCode" id="randomCodeImg" title="看不清,换一张" style="cursor: pointer" onclick="change();"><br/><input type="submit" value=" 朕要登录 "/> </form></body>

servlet处理用户的登录请求

@WebServlet("/randomLogin")public class RandomCodeLoginServlet extends HttpServlet{private static final long serialVersionUID = 1L;protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//1:接受请求参数String username = req.getParameter("username");String password = req.getParameter("password");String randomCode = req.getParameter("randomCode");//获取session中存储的随机数String randomCodeInSession = (String) req.getSession().getAttribute("RANDOMCODE_IN_SESSION");if(!randomCode.equalsIgnoreCase(randomCodeInSession)){req.setAttribute("errorMsg","亲,验证码不正确或已经过期!");req.getRequestDispatcher("/randomcode/login.jsp").forward(req, resp);return;}System.out.println("验证码OK");req.getSession().removeAttribute("RANDOMCODE_IN_SESSION");//避免重复提交.//-------------------------------------------------------------//登录判断//2:处理请求//3:控制界面跳转}}

产生验证码图片的Servlet

重点:把UUID产生的验证码数存储到Session的'RANDOMCODE_IN_SESSION'对象中.

@WebServlet("/randomCode")public class RandomCodeServlet extends HttpServlet{private static final long serialVersionUID = 1L;public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//生成随机数String randomCode = UUID.randomUUID().toString().substring(0,5);//把随机数放进Session中req.getSession().setAttribute("RANDOMCODE_IN_SESSION",randomCode);//创建图片对象int width = 80;int height = 40;int imageType = BufferedImage.TYPE_INT_RGB;BufferedImage image = new BufferedImage(width,height,imageType);//画板Graphics g = image.getGraphics();g.setColor(Color.YELLOW);//绘制一个实心的矩形g.fillRect(1,1, width - 2 ,height -2);//把随机数画进图片中g.setColor(Color.BLACK);//设置随机数的颜色Font font = new Font("宋体",Font.BOLD + Font.ITALIC,20);g.setFont(font);//设置随机数的字体和大小g.drawString(randomCode,10,28);//干扰线g.setColor(Color.GRAY);Random r = new Random();for (int i = 0; i < 100; i++) {g.fillRect(r.nextInt(width),r.nextInt(height),2,2);}//关闭g.dispose();//把图片对象以流的方式保存出去ImageIO.write(image,"jpg",resp.getOutputStream());}}

四:防止表单重复提交

表单的重复提交:根本原因:没有完整的进行一次请求页面-->提交页面的过程而完成数据提交造成重复提交的现象:1):由于服务器缓慢或网络延迟的原因,重复点击提交按钮2):已经提交成功,刷新成功页面(forward)3):已经提交成功,通过回退,再次点击提交按钮解决方案:一定的找到造成表单重复提交的根本原因.根本原因:没有进行完整的两次请求.第一次:先请求表单界面.第二次:再提交表单请求.解决方案:保证执行第二次之前,必须执行第一次.

根据MVC思想,进入登录界面要先进入Servlet

![防止表单重复提交的流程图](http://img./0309195904791?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2VpeGluXzQwMTYxNzA4/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)

开始登录之前的Servelt

@WebServlet("/input")public class InputServlet extends HttpServlet{private static final long serialVersionUID = 1L;protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//生成一个随机数(口令)String token = UUID.randomUUID().toString();//存放在Session中将来用于做判断req.getSession().setAttribute("TOKEN_IN_SESSION",token);req.setAttribute("token", token);req.getRequestDispatcher("/repeatsubmit/input.jsp").forward(req, resp);}}

jsp登录界面

<body> <form action="/transform" method="POST"><input type="hidden" name="token" value="${token}"/>转账金额:<input type="text" name="money" required/><br/><input type="submit" value=" 朕要转账 "/></form></body>

提交登录界面的Servlet请求

@WebServlet("/transform")public class TransformServlet extends HttpServlet{private static final long serialVersionUID = 1L;protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//表单中的口令String tokenInRequest = req.getParameter("token");//session中的口令String tokenInSession = (String) req.getSession().getAttribute("TOKEN_IN_SESSION");if(tokenInRequest.equals(tokenInSession)){//销毁session中的值req.getSession().removeAttribute("TOKEN_IN_SESSION");resp.setContentType("text/html;charset=UTF-8");PrintWriter out = resp.getWriter();String money = req.getParameter("money");System.out.println("转出"+money);out.print("转账成功@");}else{System.out.println("手贱....");}}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。