欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Session实现简单购物车

程序员文章站 2022-03-15 09:48:51
...

主要用于对Session对象的使用,大致过程由创建到销毁,即购物车的加入商品和清除购物车等一系列动作。Image类实现动态验证码。

(源码可以直接使用,注意路径问题)

Image类实现验证码功能

package com.ayit.session;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Image extends HttpServlet {

	/**
	 *使用response实现验证码
	 *	-生成图片
	 *	-生成随机的数字和字母
	 *	-把数字和字母画到图片上
	 *	-把图片显示到页面上
	 */
	Random r = new Random();
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		
		//生成图片
		BufferedImage image = new BufferedImage(200,50,BufferedImage.TYPE_3BYTE_BGR);
		
		
		//设置背景颜色
		Graphics2D g2d = (Graphics2D) image.getGraphics();
		g2d.setColor(Color.white);
		g2d.fillRect(0, 0, 200, 50);
		
		
		//创建一个StringBuffer存储字符串
		StringBuffer sb = new StringBuffer();
		
		//生成随机数
		String word="23456789abcdefghjkmnopqrstuvwxyz";
		g2d.setColor(Color.red);
		int x =50,y=30;		
		for (int i = 0; i < 4; i++) {
			//设置字体的样式
			Font font = randomFont();
			g2d.setFont(font);

			//返回字符串里面字符的下标
			int len = r.nextInt(word.length());
			//根据位置得到具体的字符
			char ch = word.charAt(len);
			sb.append(ch);
			//旋转的效果rotate(弧度,x,y)
			//+-30度旋转
			int jiaodu = r.nextInt(60)-30;
			double h = jiaodu*Math.PI/180;
			g2d.rotate(h, x, y);//旋转
			
			g2d.setColor(randomColor());
			//把生成的字符画到图片上
			g2d.drawString(ch+"", x, y);

			//旋转之后在转回去
			g2d.rotate(-h,x,y);
			
			x+=25;
			
			
			
		}
		
		
		// 把验证码放到session里面
		request.getSession().setAttribute("image1", sb.toString());
		
		//增加三条干扰线
		int x1,x2,y1,y2;
		
		for(int i=1;i<4;i++)
		{
			x1 = r.nextInt(200);
			x2 = r.nextInt(200);
			y1 = r.nextInt(50);
			y2 = r.nextInt(50);
			
			g2d.setColor(randomColor());
			//划线
			g2d.drawLine(x1,y1,x2,y2);
		}

		OutputImage(response, image);

	}



	private void OutputImage(HttpServletResponse response, BufferedImage image)
			throws IOException, FileNotFoundException {
		//把图片显示到页面上
		ImageIO.write(image,"jpg",response.getOutputStream());
//		int mc = r.nextInt(800);
//		ImageIO.write(image,"jpg",new FileOutputStream("D:/"+mc+".jpg"));
	}
	
	
	
	private Font randomFont () {
		String[] fontNames  = {"宋体", "黑体", "楷体","方正舒体","华文彩云","华文琥珀"};
		int index = r.nextInt(fontNames.length);
		String fontName = fontNames[index];
		int style = r.nextInt(4);
		int size = r.nextInt(5) + 24; 
		return new Font(fontName, style, size);
	}
		
	private Color randomColor () {
	
		int red = r.nextInt(150);
		int green = r.nextInt(150);
		int blue = r.nextInt(150);
		return new Color(red, green, blue);
	}

	/**
	 *
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

login.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>
    <title>Login.html</title>
	
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>
  
  <body>
    <h1>登录页面</h1>
    <h2>${msg12}</h2>
    <form action="/day10/Login" method="post">
    	Username:<input type="text" name="username"/><br/>
    	Password:<input type="password" name="pwd"/><br/>
    	image:<input type="text" name="image"/><br/>
    	<img  id ="img1" alt="code" src="/day10/Image"/><br/>
    	<a href="javascript:void(0)" onclick="loadCode()">看不清,换一张</a>
    	
    	<input type="submit" value="登录"/>
    </form>
  </body>
  <script type="text/javascript">
 		function loadCode(){
 		//实现看不清换一张
 			var img1 = document.getElementById("img1");
 			//向src重新设置地址
 			img1.src = "/day10/Image?"+new Date().getTime();
 		} 
  </script>
</html>

Login类实现验证码判断功能,学过数据库以后,实现用户名和密码的验证

package com.ayit.session;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Login extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 得到输入的验证码
		request.setCharacterEncoding("utf-8");
		String imageText = request.getParameter("image");

		// 得到图片的验证码
		String imageCode = (String) request.getSession().getAttribute("image1");

		if (!imageText.equals(imageCode)) {
			// 设置一个值request
			request.setAttribute("msg12", "验证码错误");

			// 转发到登录页面
			request.getRequestDispatcher("/session/login.jsp").forward(request,
					response);
			return;
		} else {
			request.getRequestDispatcher("/session/product.jsp").forward(
					request, response);
		}
	}

	/**
	 *
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

登录成功后来到product.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="com.ayit.utils.MyCookieUtils"%>
<%
	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>
<base href="<%=basePath%>">

<title>My JSP 'product.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

</head>

<body>
	<img alt="1" src="/day10/img/1.jpg" />
	<a href="/day10/SessionDemo1?id=1" />手电
	</a>
	<img alt="2" src="/day10/img/2.jpg" />
	<a href="/day10/SessionDemo1?id=2" />手机
	</a>
	<img alt="3" src="/day10/img/3.jpg" />
	<a href="/day10/SessionDemo1?id=3" />电视
	</a>
	<img alt="4" src="/day10/img/4.jpg" />
	<a href="/day10/SessionDemo1?id=4" />冰箱
	</a>
</body>
</html>

SessionDemo1类实现加入购物车功能,该类主要体现了Session对象的用法

package com.ayit.session;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SessionDemo1 extends HttpServlet {

	/**
	 * 根据id得到商品名称
	 * 1、判断是否是第一次购物
	 * 2、如果是,创建购物车,把商品名称和数量放到购物车
	 * 3、如果不是
	 * 		-判断购物车是否存在相同的商品
	 * 			--存在,原来的商品数量+1,放到购物车
	 * 			--不存在,把名称和数量加到购物车
	 *
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//根据id得到商品名称
		String id1 = request.getParameter("id");
		int id = Integer.parseInt(id1);
		String[] names = {"手电","手机","电视","冰箱"};
		String name = names[id-1];
		
		//判断是否是第一次购物
		Map<String,Integer> map = (Map<String,Integer>)request.getSession().getAttribute("cart");
		if(map==null)
		{
			map = new HashMap<String, Integer>();
			map.put(name, 1);
		}
		else
		{
			//不是第一次,判断购物车是否有相同名称的商品
			if(map.containsKey(name))
			{
				int num = map.get(name);
				map.put(name, num+1);
			}else
			{
				//直接放名称和数量
				map.put(name, 1);
			}
		}
		
		//把购物车放到session里面
		request.getSession().setAttribute("cart", map);
		
		//输出两个超链接,继续购物和去结算
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write("<a href='/day10/session/product.jsp'>继续购物</a><br/>");
		response.getWriter().write("<a href='/day10/session/cart.jsp'>去结算</a>");
	}

	/**
	 *
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

cart.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>
<base href="<%=basePath%>">

<title>My JSP 'cart.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

</head>

<body>
	<h1>结算页面</h1>
	<a href="/day10/clear">清空购物车</a>
	<%
  	   Map<String,Integer> map =( Map<String,Integer>) request.getSession().getAttribute("cart");
       if(map==null)
       {
     %>
	<h2>没有任何购物信息</h2>
	<% 
       }else
       {
       //有购物信息,显示名称和数量
       Set<String> keys = map.keySet();
       for(String key : keys)
       {
       int num = map.get(key);
   %>
	<h3>
		名称:<%=key%>
		, 数量:<%=num %></h3>
	<%
   		}
   	}
    %>
</body>
</html>

clear类最后实现的是清空购物车,主要用于销毁Session对象

package com.ayit.session;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class clear extends HttpServlet {

	/**
	 *清空购物车
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		//销毁session
		session.invalidate();
		
		response.sendRedirect("/day10/session/cart.jsp");
	}

	/**
	 *
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}