Design and Implementation of JavaWeb Commodity Sales System


Today, the blogger took a small task to develop a JavaWeb online ordering system. In addition, he wanted to change the system to a shoe city sales system, a medicine sales system, and a tea sales system. Don't say much, let's do it!
The customer requested to use a set of database operation tools provided by him. The blogger took a look and found that the package was quite complete. After discussing the price, he started work! The time limit is two days, four sets of procedures, and the difficulty is not low.

Tools introduction

First, let’s take a look at the database tools. The
database tools encapsulate the addition, deletion, and modification of the database. Among them, the query encapsulation is of two types: List and Page

The first is to encapsulate it as data in the form of a List linked list

// 执行返回多条记录的查询操作,结果被封装到List中。
	public List<Map<String, String>> getList(String sql, String[] params) {
		List<Map<String, String>> list = null;
		try {
			pstmt = con.prepareStatement(sql);
			ResultSet rs = pstmt.executeQuery();
			list = getListFromRS(rs);//将数据集信息进行封装
		} catch (Exception e) {
		} finally {
		return list;

The following is the encapsulated data set information, through the relevant method to obtain the name of the data table field and correspond to it

// 将结果集中的内容封装到List中
	private List<Map<String, String>> getListFromRS(ResultSet rs) throws SQLException {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		ResultSetMetaData rsmd = rs.getMetaData();
		while ( {
			Map<String, String> m = new HashMap<String, String>();
			for (int i = 1; i <= rsmd.getColumnCount(); i++) {
				String colName = rsmd.getColumnLabel(i);
				String s = rs.getString(colName);
				if (s != null) {
					m.put(colName, s);
		return list;

In this way, the data encapsulation is completed, and the method of Page is implemented by adding other attributes on the basis of List. The page tool adds a paging query attribute, and adds limit ** after the original sql statement. In addition, it is necessary to query the data of the entire data table to determine the number of pages to be paged, and then save the List as an Object to In the Map, then the total page number, current page number and other information are also encapsulated. In this way, the Page encapsulation is completed.

// 查询结果分页时,返回分页信息的Map,包括总页数,每页记录数和当前页中的记录。
	public Map<String, Object> getPage(String sql, String[] params, String curPage) {
		Map<String, Object> page = new HashMap<String, Object>();
		String newSql = sql + " limit " + (Long.parseLong(curPage) - 1) * PAGE_REC_NUM + "," + PAGE_REC_NUM;
		List<Map<String, String>> pageList = getList(newSql, params);
		sql = sql.toLowerCase();
		String countSql = "";
		if (sql.indexOf("group") >= 0) {
			countSql = "select count(*) as tempNum from (" + sql + ") as temp";
		} else {
			countSql = "select count(*) as tempNum " + sql.substring(sql.indexOf("from"));
		String count_s = (String) getMap(countSql, params).get("tempNum");
		long count = Long.parseLong(count_s);
		long totalPage = 0;
		if (count % PAGE_REC_NUM == 0)
			totalPage = count / PAGE_REC_NUM;
			totalPage = count / PAGE_REC_NUM + 1;
		page.put("list", pageList);
		page.put("totalPage", totalPage);
		page.put("curpage", curPage);
		page.put("recNum", PAGE_REC_NUM);
		return page;

Of course, we need to query only one piece of information, and we only need to get the first piece of information in the data set.

// 执行返回至多一条记录的查询操作,结果被封装到Map中。
	public Map<String, String> getMap(String sql, String[] params) {
		Map<String, String> m = null;
		List<Map<String, String>> l = getList(sql, params);
		if (l != null && l.size() != 0) {
			m = (Map<String, String>) (l.get(0));
		return m;

At this point, the encapsulation of the most important query operation in the project is completed, and the next step is to complete the operation of adding and deleting the database.

// 执行更新类(增删改)的SQL语句,SQL语句中含有占位符。
	public int update(String sql, String[] params) {
		int result = 0;
		try {
			pstmt = con.prepareStatement(sql);
			result = pstmt.executeUpdate();
		} catch (SQLException e) {
		} finally {
		return result;

In addition, the processing of placeholders requires filling

// 为预编译的SQL语句中的占位符?设置值,值被放在字符串数组params中。
	private void setParams(String[] params) {
		if (params != null) {
			for (int i = 0; i < params.length; i++) {
				try {
					pstmt.setString(i + 1, params[i]);
				} catch (SQLException e) {



In addition, there are packages for file upload tools

public static String uploadSingleFile(Part part, HttpServletRequest request) {
		String path = null;
		String fileName = getFileName(part);
		if (!fileName.equals("")) {
			// 得到上传文件的文件扩展名
			String fileExtName = getFileExtName(part);
			String newFileName = System.currentTimeMillis() + fileExtName;
			// 得到上传文件保存路径的服务器端硬盘物理路径
			String savePath = request.getServletContext().getRealPath("/img");
			File f = new File(savePath);
			if (!f.exists()) {
			// 文件上传
			try {
				part.write(savePath + File.separator + newFileName);
				path = "img/" + newFileName;
			} catch (IOException e) {
		return path;

In the development project, due to issues such as the date of placing the order, the blogger encapsulated the time tool

public String getTime(){
		Long timeStamp = System.currentTimeMillis();  //获取当前时间戳
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp)))); 
        return time;

At this point, the encapsulated tool class is introduced, and then we will use this set of tool classes to complete our project

Interface display

The four projects are all mall sales projects, and their tools are the same, so the projects are basically the same. The difference is in some methods, the naming of the classes and the front-end interface.
Let's show the interface of these four projects below

Pharmaceutical sales platform

Order online

Online Shoe City

Tea sales website

Backstage management system

Shopping cart page

Detailed development steps

Next, we will introduce the development steps of this project
First, we need to determine our front-end interface. Bloggers always make the interface by themselves before, but the results are always unsatisfactory. After that, they use some front-end frameworks, which are commonly used by bloggers. It is Bootstrap. In addition, some front-end interfaces will be used directly. In these four systems, the UI of the shoe city system is accumulated by bloggers, and the other three projects are developed by themselves. Related components, such as forms, buttons, etc., are applied. Overall, the interface is relatively simple.

If you need to learn, you can search BootStrap Chinese website learn related front-end interface development methods

Closer to home, start our development steps
JavaWeb generally follows the three-tier architecture or MVC design pattern, which is relatively close according to the customer’s demo.

A screenshot of the project directory is shown in the figure

Insert picture description here

According to step, they have to come performed by sending a request corresponding Servlet Servlet, then the logic code to call the service layer to obtain the data item and returning the package, rendering the final result is returned to the interface, a request to complete

Insert picture description here

then we Take the query operation as an example to explain the implementation steps.

For example

Take the product list in the back-end management system of Shoe City as an example. The query result includes List and some pagination attributes.
First of all, we need to know that if we want to get data, we have to send a servlet request.

Insert picture description here

Then, check the number and find the corresponding servlet.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String sname=request.getParameter("sname");//获取鞋子名称参数
		String curpage=request.getParameter("curpage");//获取当前页参数
		Map<String, Object> shoes=shs.getShoesPage(curpage,sname);
		request.setAttribute("shoes", shoes);	//将数据保存在request域中,可以在页面中显示	request.getRequestDispatcher("/admin/shoe_list.jsp").forward(request, response);//响应返还到相应页面

Service layer calls to implement database-related operations

public  Map<String, Object> getShoesPage(String curpage,String sname){
			String sql = "select id,shoes.sname sname,shoes.price price ,types.typename typename,shoes.image image from shoes inner join types on where shoes.sname like '%"+sname+"%' ";
			return db.getPage(sql, curpage);

At this point, the data is obtained, the information is encapsulated in the Map and then returned in turn, and finally to our interface.
Use the el expression to read our data from the request field.

<c:forEach items="${ }" var="shoe">
				<td style="width:80px;height:70px"><img src="${basePath}/${shoe.image }" style="width:60px;height:50px"></td>
				<td>${shoe.sname }</td>
				<td>${shoe.price }元</td>
				<td>${shoe.typename }</td>
				<td><a href="${basePath}/ShoeGetById?id=${ }"><button type="button" class="btn btn-success">编辑</button></a>
					<a href="${basePath}/ShoeDelServlet?id=${ }"><button type="button" class="btn btn-danger">删除</button></a>

Realize paging judgment

<nav aria-label="...">
				<ul class="pager">
								 <c:when test="${ eq 1  }">
								 <li><a href="#">上一页</a>
								 <li><a href="${basePath}/ShoeServlet?curpage=${ }&&sname=">上一页</a></li>
					<li><a href="#">第 ${} 页</a></li>
								 <c:when test="${ eq  }">
								 <li><a href="#">下一页</a>
								 <li><a href="${basePath}/ShoeServlet?curpage=${ }&&sname=">下一页</a></li>

At this point, the query operation of the project has been completed. As for the implementation of other methods, the same is true. I believe that by completing such a project, we can have a deeper understanding of JavaWeb technology.

The code word is not easy, give me a thumbs up!