JavaWeb實戰之開發網上購物系統(超詳細)

一、項目描述

基於B/S三層架構設計的購物系統,可以更好地符合”高內聚,低耦合”的設計思想。表現層(UI)通過JSP在瀏覽器上實現界面展示,通過Servlet接受用戶請求並生成驗證碼等實時信息;數據訪問層(DAL)通過JDBC對DBMS進行訪問;二者之間的業務邏輯層(BLL)通過Service進行連接。同時面向接口編程提高規范化。這隻是我自己用兩三天的時間做的小項目,距離真正的購物系統差距還是很大的,僅供初學者參考,很多邏輯缺陷不必太糾結,以後有時間會再寫一篇博客對這個項目進行相關測試。

如果隻需要代碼可直接通過書簽欄跳轉至相關文件。

二、項目演示

這是購物系統首頁,是仿照華為商城設計的,當然也可以說是仿照小米商城,這二者的頁面設計並無本質區別,具體實現借助於Bootstrap,商品信息通過後臺數據庫讀取,商品表見下

在這裡插入圖片描述
在這裡插入圖片描述

點擊任意商品進入詳情界面

在這裡插入圖片描述

如果此時點擊加入購物車會調用Servlet中的doPost方法,進而通過登陸信息是否讀取成功判斷登陸狀態,如果未登錄則轉至登錄界面並提示相關信息,背景漸變色借助於webgradients選取,同時實現正則驗證與驗證碼相關功能

在這裡插入圖片描述

我們先註冊再登錄,這裡註冊洛的相關信息

在這裡插入圖片描述

註冊成功

在這裡插入圖片描述
在這裡插入圖片描述

之後我們登錄並將心儀的商品加入購物車,查看購物車,這裡會一致顯示當前登錄用戶信息

在這裡插入圖片描述

提交訂單後查看訂單,這裡借助jQuery做瞭一個下拉框,可以查看後臺數據庫關於此訂單的全部信息,這裡提交訂單相當於付款,所以未設退貨功能,因此數據刪除隻能借助於後臺數據庫。

在這裡插入圖片描述

最後點擊註銷返回主頁

在這裡插入圖片描述

三、部分代碼

JdbcUtils.java

用於加載驅動並獲得與數據庫的連接的工具類

package common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JdbcUtil {
	static Connection connection;
	public static Connection getCon() {
		//加載驅動
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String url = "jdbc:mysql://localhost:3306/shoppingsystem?characterEncoding=utf-8";
		String username = "root";
		String password = "123";
		
		//獲得連接
		try {
			connection = DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return connection;
	}
	public static void closeAll(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (preparedStatement != null) {
			try {
				preparedStatement.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
、

People.java

與數據庫中用戶表相匹配的用戶類

package entity;

public class People {
	private String id;
	private String password;
	private String name;
	private String email;
	private String address;
	
	public People() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	public People(String id, String password, String name, String email, String address) {
		super();
		this.id = id;
		this.password = password;
		this.name = name;
		this.email = email;
		this.address = address;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "People [id=" + id + ", password=" + password + ", name=" + name + ", email=" + email + ", address="
				+ address + "]";
	}
	
}

InterfacePeopleDao.java

對用戶信息進行相關操作的接口

package dao;

import java.util.List;

import entity.People;

public interface InterfacePeopleDao {
	public abstract int insertPeople(String id, String password, String name, String email, String address);
	
	public abstract int deletePeople(String id);
	
	public abstract int updatePeople(String id, String password, String name, String email, String address);
	
	public abstract People checkPeople(String id, String password);
	
	public abstract List<People> findAllPeople();
}

PeopleDao.java

對上述接口的實現

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import common.JdbcUtil;
import entity.People;

public class PeopleDao implements InterfacePeopleDao {
	private Connection connection;
	private PreparedStatement preparedStatement;
	private ResultSet resultSet;

	@Override
	public int insertPeople(String id, String password, String name, String email, String address) {
		String sql = "mistake";
		if (id != "" && password != "" && name != "" && email != "" && address != "") {
			sql = "insert into people (id, password, name, email, address)" + "values('" + id + "','" + 
					password + "','" + name + "','" + email + "','" + address + "');";
		}
		System.out.println("insertPeople()的sql語句:" + sql);
		
		int result = 0;
		connection = JdbcUtil.getCon();
		try {
			preparedStatement = connection.prepareStatement(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			result = preparedStatement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		JdbcUtil.closeAll(connection, preparedStatement, resultSet);
		return result;
	}

	@Override
	public int deletePeople(String id) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int updatePeople(String id, String password, String name, String email, String address) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public People checkPeople(String id, String password) {
		String sql = null;
		if (id != null && password != null) {
			sql = "select * from people where id = '" + id + "' and password = '" + password + "'";
		}
		System.out.println("checkPeople()的sql語句:" + sql);
		
		People people = null;
		connection = JdbcUtil.getCon();
		try {
			preparedStatement = connection.prepareStatement(sql);
			resultSet = preparedStatement.executeQuery();
			if (resultSet.next()) {
				people = new People();
				people.setId(resultSet.getString(1));
				people.setPassword(resultSet.getString(2));
				people.setName(resultSet.getString(3));
				people.setEmail(resultSet.getString(4));
				people.setAddress(resultSet.getString(5));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.closeAll(connection, preparedStatement, resultSet);
		}
		return people;
	}

	@Override
	public List<People> findAllPeople() {
		// TODO Auto-generated method stub
		return null;
	}

}

InterfacPeopleService.java

在業務邏輯層中將表現層與數據訪問層進行連接,由於項目本身並不復雜,所以隻是簡單實現瞭方法傳遞

package service;

import java.util.List;

import entity.People;

public interface InterfacePeopleService {
	public abstract int insertPeople(String id, String password, String name, String email, String address);
	
	public abstract int deletePeople(String id);
	
	public abstract int updatePeople(String id, String password, String name, String email, String address);
	
	public abstract People checkPeople(String id, String password);
	
	public abstract List<People> findAllPeople();
}

PeopleService.java

對上述接口的實現

package service;

import java.util.List;

import dao.InterfacePeopleDao;
import dao.PeopleDao;
import entity.People;

public class PeopleService implements InterfacePeopleService {
	private InterfacePeopleDao peopleDao;
	
	public PeopleService() {
		peopleDao = new PeopleDao();
	}

	@Override
	public int insertPeople(String id, String password, String name, String email, String address) {
		return peopleDao.insertPeople(id, password, name, email, address);
	}

	@Override
	public int deletePeople(String id) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int updatePeople(String id, String password, String name, String email, String address) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public People checkPeople(String id, String password) {
		return peopleDao.checkPeople(id, password);
	}

	@Override
	public List<People> findAllPeople() {
		// TODO Auto-generated method stub
		return null;
	}

}

CheckCode.java

在內存中生成驗證碼圖片並輸出到客戶端

package servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/CheckCode")
public class CheckCode extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static int width=70;
    private static int height=25;
       
	public CheckCode() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/**
		 * request是客戶端瀏覽器發出的請求被封裝形成的一個HttpServletRequest公共接口類對象
		 * session對象存儲特定用戶會話所需的屬性及配置信息, 這樣當用戶在應用程序的Web頁之間跳轉時, 存儲在session對象中的變量將不會丟失, 而是在整個用戶會話中一直存在下去
		 * getSession()與getSession(true)一樣, 獲取request對象關聯的session對象, 如果沒有session, 則返回一個新的session
		 */
		HttpSession session=request.getSession();
		response.setContentType("image/jpeg");// 設置生成的文檔類型為jpg
		ServletOutputStream servletOutputStream = response.getOutputStream();
		
		/*設置瀏覽器不要緩存此圖片*/
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		
		/**
		 * 創建內存圖片並獲得其圖形上下文
		 * Image是一個抽象類, BufferedImage是其實現類, 是一個帶緩沖區圖像類, 主要作用是將一幅圖片加載到內存中
		 * BufferedImage生成的圖片在內存裡有一個圖像緩沖區, 利用這個緩沖區我們可以很方便地操作這個圖片
		 */
		BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics graphics=image.getGraphics();
		
		char[] rands=generCode();// 產生隨機的驗證碼
		drawRands(graphics, rands);// 產生圖像
		graphics.dispose();// 結束圖像的繪制過程,完成圖像
		
		/*將圖像輸出到客戶端*/
		ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
		ImageIO.write(image, "jpeg", byteArrayOutputStream);
		byte[] buf=byteArrayOutputStream.toByteArray();
		response.setContentLength(buf.length);
		servletOutputStream.write(buf);
		byteArrayOutputStream.close();
		servletOutputStream.close();
		
		session.setAttribute("checkcode", new String(rands));// 將當前的驗證碼寫入到session中	
		
	}
	
	private char[] generCode() {
    	//定義驗證碼的字符表
    	String chars="0123456789";
    	char[] rands=new char[5];
    	for(int i=0;i<5;i++) {
    		int rand=(int)(Math.random()*10);
    		rands[i]=chars.charAt(rand);
    	}
    	return rands;
    }
	
	private void drawRands(Graphics g,char[] rands) {
		g.setColor(Color.WHITE);
		g.setFont(new Font(null, Font.ITALIC|Font.BOLD, 18));
		
		/*在不同高度上輸出驗證碼的每個字符*/
		g.drawString("" + rands[0], 0, 18);
		g.drawString("" + rands[1], 14, 18);
		g.drawString("" + rands[2], 28, 18);
		g.drawString("" + rands[3], 42, 18);
		g.drawString("" + rands[4], 56, 18);
		System.out.print("當前驗證碼:");
		System.out.println(rands);
	}

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

}

到此這篇關於Java實戰之利用JavaWeb開發購物系統(超詳細)的文章就介紹到這瞭,更多相關JavaWeb購物系統內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!