使用Java基于MVC模式开发一个简单商品管理系统

引言:java+servlet实现的一个简单的商品管理系统(仅数百行代码,不含多余的CSS、JS等)

备注:项目在MyEclipse、Eclipse下运行通过,可完成简单的商品增、删、改、查操作。

适用于学习JavaWeb 2-3个月的初学者

 

附上完整项目包,包含数据库脚本dbms.sql和数据库驱动jar包。

地址: https://pan.baidu.com/s/1sDnd-ysXSrg0ZJBj9tBxsw

密钥: 4vrs

2020年7月3日 14:55更新,最新代码以百度云中打包的文件为准。
------------------------------更新记录-------------------------------

7、添加了根据条件查询用户的功能  2020年7月3日 11:56

6、添加了根据条件查询商品的功能  2020年6月26日 11:56

5、添加了用户注册和用户查询 2019年12月22日 14:52

4、针对读者的反馈,规范了页面和后台代码中的参数,添加了注释 2019年12月21日 12:32

3、针对读者的反馈,进行的相关更新。 2019年12月17日 23:26

2、针对读者的反馈,重新修改了源码。 2019年6月20日 17:41:53

1、读者反馈无法登录,问题原因是,文章6.1章节,登录页面使用的伪代码,页面属性和java bean不对应,无法登录。

现已修改。 2019年6月12日 20:52:26

注意:本文基于mysql 5.0开发,jdbc驱动包版本要对应。

--------------------------END-------------------------

环境:

  • 机器环境:Windows 7 64bit
  • JDK:1.6
  • 数据库:MySql 5.0(客户端工具SQLyog v10.2)
  • IDE:MyEclipse 9.0 M1、Eclipse Oxygen
  • 连接数据库jar包:mysql-connector-java-5.1.7-bin.jar
  • 测试浏览器:Chrome、Sougou浏览器、IE11.0、MyEclipse内置浏览器

正文:

此简易的商品管理系统,包括前端、后台和数据库三部分。前端使用jsp页面(使用div+css布局),

后端使用MVC模式,数据库为简单的两张表,用户表和商品表。

 前台布局包括:

top(首栏)、banner(横幅部分)、left(左侧导航栏)、right(内容部分,使用了frame框架)。

 系统描述:

用户登录后跳转至商品管理页面(图1-1),banner显示当前用户,点击用户名(超链接)

可进入用户管理页,可对用户进行增(注册用户)、删、改(修改用户名、密码等)操作。

航栏有显示产品和添加产品。显示产品页显示全部商品,操作栏可进行更新、删除操作。

 系统前台效果:

图1-1 

系统演示:

 

                                                                              图1-2

模糊查询

                                                                                                 图1-3

数据库表结构:

                                                                               图1-3

      项目文件夹组织结构:

 

                                                                             图1-4

     后台部分java代码部分:

1、javabean:

1.1、Product.java

package com.zjl.bean;
/**
 * 商品实体类
 * @author Administrator
 *
 */
public class Product {

    private int id;
    private String name;
    private String addr;
    private double price;

    //省略getter、setter方法,详见打包的项目文件

}
 1.2、User.java
package com.zjl.bean;
/**
 * 用户实体类
 * @author Administrator
 *
 */
public class User {
	
	private int id;
	private String name;
	private String password;
	private String type;
	
	//省略getter、setter方法,详见打包的项目文件
}


2、conn

2.1 ConnectDatabase.java

package com.zjl.conn;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
 * 数据库连接工具类
 * @author Administrator
 *
 */
public class ConnectDatabase {
	
	private static final String DRIVER_STRING="com.mysql.jdbc.Driver";
	private static final String URL_STRING="jdbc:mysql://localhost:3306/dbms";
	private static final String USER_STRING="root";
	private static final String PASS_STRING="admin";
	
	public static Connection getConnection(){
		Connection connection=null;
		
		try {
			Class.forName(DRIVER_STRING);
			connection=DriverManager.getConnection(URL_STRING, USER_STRING, PASS_STRING);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return connection;
	}
	public void realse(Connection conn,PreparedStatement ps,ResultSet rs){
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(ps!=null){
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}


3、dao层

3.1、DaoFactory.java

package com.zjl.dao;

import com.zjl.service.IProductDao;
import com.zjl.service.IUserDao;
/**
 * DAO工厂类,为DAO调用者提供DAO实例对象
 * @author Administrator
 *
 */
public class DaoFactory {
	public static IUserDao getUserDao(){
		return new UserDaoImp();
	}
	public static IProductDao getProductDao(){
		return new ProductImp();
	}
}

 3.2、ProductImp.java

package com.zjl.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.zjl.bean.Product;
import com.zjl.bean.User;
import com.zjl.conn.ConnectDatabase;
import com.zjl.service.IProductDao;
/**
 * 商品操作接口实现类,实现商品的增加、删除、更新、添加等操作
 * @author Administrator
 *
 */
public class ProductImp implements IProductDao {
	PreparedStatement ps = null;
	public boolean insert(Product p) {
		String sql ="insert into product(name,addr,price) values(?,?,?)";
		int n =0;
		try{
		ps = ConnectDatabase.getConnection().prepareStatement(sql);
		
		ps.setString(1, p.getName());
		ps.setString(2, p.getAddr());
		ps.setDouble(3, p.getPrice());
		n=ps.executeUpdate();
		}catch (Exception e) {
		e.printStackTrace();
		}
		return n>0;
	}

	public boolean delete(Product p) {
		String sql ="delete from product where id="+p.getId();
		int n=0;
		try{
		ps=ConnectDatabase.getConnection().prepareStatement(sql);
		n=ps.executeUpdate();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return n>0;
	}

	public boolean update(Product p) {
		String sql = "update product set name=?,addr=?,price=? where id=?";
		int n = 0;
		try{
		ps=ConnectDatabase.getConnection().prepareStatement(sql);
		ps.setString(1, p.getName());
		ps.setString(2, p.getAddr());
		ps.setDouble(3, p.getPrice());
		ps.setInt(4, p.getId());
		
		n=ps.executeUpdate();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return n>0;
	}

/**
*根据map参数模糊查询商品,map为空时全部查询。
*/
	public List<Product> queryProduct(Map<String, Object> map) {
		StringBuffer sql= new StringBuffer("select * from product where 1 =1");
		if(map.get("keyword")!=null && map.get("keyword")!=""){
			sql.append(" and name like '"+"%"+map.get("keyword")+"%'"
					+"or addr like '"+"%"+map.get("keyword")+"%'"+
					"or price like '"+"%"+map.get("keyword")+"%'"
			);
		}
		List<Product> list = new ArrayList<Product>();
		try{
		ps = ConnectDatabase.getConnection().prepareStatement(sql.toString());
		ResultSet rs = ps.executeQuery();
		while(rs.next()){
			Product p = new Product();
			p.setId(rs.getInt("id"));
			p.setName(rs.getString("name"));
			p.setAddr(rs.getString("addr"));
			p.setPrice(rs.getDouble("price"));
			list.add(p);
		
		}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	public Product queryById(Product p) {
		Product product = null;
		String sql = "select * from product where id="+p.getId();
		try{
		ps = ConnectDatabase.getConnection().prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		if(rs.next()){
			product  = new Product();
			product.setId(rs.getInt("id"));
			product.setName(rs.getString("name"));
			product.setAddr(rs.getString("addr"));
			product.setPrice(rs.getDouble("price"));
					
					
		}
		}catch(Exception e){
			e.printStackTrace();
		}
		return product;
	}

}

 

3.3、UserImp.java

package com.zjl.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.zjl.bean.Product;
import com.zjl.bean.User;
import com.zjl.conn.ConnectDatabase;
import com.zjl.service.IUserDao;
/**
 * 用户接口操作实现类,实现用户相关的基本操作
 * @author Administrator
 *
 */
public class UserDaoImp implements IUserDao {

	PreparedStatement ps = null;
	/**
	 * 用户注册
	 */
	public boolean insert(User u) {
		int n=0;
		String sql="insert into user(name,password) values(?,?)";
		try{
		ps=ConnectDatabase.getConnection().prepareStatement(sql);
		ps.setString(1, u.getName());
		ps.setString(2, u.getPassword());
		
		n = ps.executeUpdate();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return n>0;
	}

	public boolean delete(User u) {
		String sql="delete from user where id=?";
		int n = 0;
		try{
		ps=ConnectDatabase.getConnection().prepareStatement(sql);
		ps.setInt(1, u.getId());
		n=ps.executeUpdate();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return n>0;
	}

	public boolean update(User u) {
		return false;
	}
	/**
	 * 用户登录
	 */
	public User queryById(User u) {
		User user =null;
		String sql="select * from user where name=? and password=?";
		try{
		ps = ConnectDatabase.getConnection().prepareStatement(sql);
		ps.setString(1,u.getName());
		ps.setString(2,u.getPassword());
		ResultSet rs = ps.executeQuery();
		if(rs.next()){
			user=new User();
			user.setId(rs.getInt("id"));
			user.setName(rs.getString("name"));
			user.setPassword(rs.getString("password"));
			user.setType(rs.getString("type"));
		}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return user;
	}

	/**
*查询用户
*/
public List<User> queryUser(Map<String, Object> map) {
		StringBuffer sql= new StringBuffer("select * from user where 1 =1");
		if(map.get("keyword")!=null && map.get("keyword")!=""){
			sql.append(" and id like '"+"%"+map.get("keyword")+"%'"
					+"or name like '"+"%"+map.get("keyword")+"%'"
			);
		}
		List<User> list = new ArrayList<User>();
		try{
		ps = ConnectDatabase.getConnection().prepareStatement(sql.toString());
		ResultSet rs = ps.executeQuery();
		while(rs.next()){
			User user = new User();
			user.setId(rs.getInt("id"));
			user.setName(rs.getString("name"));
			user.setPassword(rs.getString("password"));
			list.add(user);
		
		}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
/**
*修改用户界面查询用户
*/
	public User queryByUserId(User u) {
		User user =null;
		String sql="select * from user where id=?";
		try{
		ps = ConnectDatabase.getConnection().prepareStatement(sql);
		ps.setInt(1,u.getId());
		ResultSet rs = ps.executeQuery();
		if(rs.next()){
			user=new User();
			user.setId(rs.getInt("id"));
			user.setName(rs.getString("name"));
			user.setPassword(rs.getString("password"));
			user.setType(rs.getString("type"));
		}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return user;
	}
}

 

4、接口

4.1、IProductDao.java

package com.zjl.service;

import java.util.List;
import java.util.Map;

import com.zjl.bean.Product;
import com.zjl.bean.User;
/**商品操作接口
 * @author Administrator
 *
 */
public interface IProductDao {
	public boolean insert(Product p);
	public boolean delete(Product p);
	public boolean update(Product p);
	public List<Product> queryProduct(Map<String, Object> map);
	public Product queryById(Product p);
}

 

4.2、IUserDao.java

package com.zjl.service;

import java.util.List;
import java.util.Map;

import com.zjl.bean.User;
/**
 * 用户操作接口
 * @author Administrator
 *
 */
public interface IUserDao {
		public boolean insert(User u);
	public boolean delete(User u);
	public boolean update(User u);
	public User queryById(User u);
	public User queryByUserId(User u);
	public List<User> queryUser(Map<String, Object> map);
}

 

5、Servlet

5.1、登录servlet

 

package com.zjl.servlet;

import java.io.IOException;
import java.io.PrintWriter;

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

import com.zjl.bean.User;
import com.zjl.dao.DaoFactory;
import com.zjl.service.IUserDao;
/**
 * 用户登录servlet,处理用户登录
 * @author Administrator
 *
 */
public class LoginServlet extends HttpServlet {

	
	public LoginServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
	}

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

			this.doPost(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");

			//获取login.jsp中用户登录表单中提交的username
			String name = request.getParameter("username");
			//获取login.jsp中用户登录表单中提交的password
			String password = request.getParameter("password");
			
			//实例化一个user,将前台获取的username,password赋值给user实例的属性
			User user = new User();
			user.setName(name);
			user.setPassword(password);
			
			//调用DAO,进行用户登录
			IUserDao dao = DaoFactory.getUserDao();
			if(dao.queryById(user)!=null){
				//登录成功则请求转发至首页
				request.getRequestDispatcher("main.jsp").forward(request, response);
			}else{
				//登录失败则重定向至登录页
				response.sendRedirect("login.jsp");
			}
		
	}

	public void init() throws ServletException {
	}

}

 

5.2、商品管理servlet

 

package com.zjl.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

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

import com.sun.corba.se.impl.protocol.giopmsgheaders.Message;
import com.zjl.bean.Product;
import com.zjl.dao.DaoFactory;
import com.zjl.service.IProductDao;

/**
 * 商品管理Servlet,处理商品删除、增加、修改、新增等操作
 * @author Administrator
 *
 */
public class OperatorServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public OperatorServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
	}

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

		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		//获取前台参数,根据参数选择对应的servlet方法进行业务处理
		String op = request.getParameter("op");
		
		if("update".equals(op)){//更新商品
			updateService(request,response);
		}else if("del".equals(op)){//删除商品
			deleteService(request,response);
		}else if("insert".equals(op)){//添加商品
			insertService(request,response);
		}else if("select".equals(op)){//查询商品
			selectService(request,response);
		}
		
		
	}
	/**
	 * 查询商品
	 * @param request
	 * @param response
	 */
	private void selectService(HttpServletRequest request,
			HttpServletResponse response) {
		
		  IProductDao dao = DaoFactory.getProductDao();
		  String searchText = request.getParameter("searchText");
		  Map<String,Object> map = new HashMap<String, Object>();;
		  map.put("keyword", searchText);
		  List<Product> list = dao.queryProduct(map);
		  request.setAttribute("productList", list);
		  try{
		  if(list!=null){
			  request.getRequestDispatcher("product.jsp").forward(request, response);
		  }else{
			  response.sendRedirect("main.jsp");
		  }
		  }
		  catch(Exception e){
			  e.printStackTrace();
		  }
	}
	/**
	 * 添加商品
	 * @param request
	 * @param response
	 */
	private void insertService(HttpServletRequest request,
			HttpServletResponse response) {
		
		//获取前台传递的三个参数,其中id在数据中使用自增字段,无需手动输入
		String name=request.getParameter("name");
		String addr=request.getParameter("addr");
		double price = Double.parseDouble(request.getParameter("price"));
		
		Product p = new Product(name, addr, price);
		IProductDao dao = DaoFactory.getProductDao();
		try{
		if(dao.insert(p)){
			request.getRequestDispatcher("product.jsp").forward(request, response);
		}else{
			response.sendRedirect("insert.jsp");
		}}
		catch(Exception e){
			e.printStackTrace();
		}
		
	}
	/**
	 * 删除商品
	 * @param request
	 * @param response
	 */
	private void deleteService(HttpServletRequest request,
			HttpServletResponse response) {
		
		//接收前台传递的待删除商品ID,根据id删除对应商品
		//delete from product where id ="id";
		int id =Integer.parseInt(request.getParameter("id"));
		Product p = new Product();
		p.setId(id);
		IProductDao dao = DaoFactory.getProductDao();
		try{
		if(dao.delete(p)){
			request.getRequestDispatcher("product.jsp").forward(request, response);
			
		}else{
			response.sendRedirect("product.jsp");
		}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * 更新商品
	 * @param request
	 * @param response
	 */
	private void updateService(HttpServletRequest request,
			HttpServletResponse response) {
		//获取前台更新商品的参数,根据商品id进行更新
		//update product set 
		//product.name ="xxx",product.addr="xxx",product.price="xxx" 
		//where id ="待删除商品id";
		
		int id = Integer.parseInt(request.getParameter("id"));
		String name =request.getParameter("name");
		  String addr = request.getParameter("addr");
		  double price = Double.parseDouble(request.getParameter("price"));
		 
		  Product p = new Product(id, name, addr, price);
		  IProductDao dao = DaoFactory.getProductDao();
		  try{
		  if(dao.update(p)){
			  request.getRequestDispatcher("product.jsp").forward(request, response);
		  }else{
			  response.sendRedirect("update.jsp");
		  }
		  }
		  catch(Exception e){
			  e.printStackTrace();
		  }
	}

	public void init() throws ServletException {
	}

}

5.3、用户管理servlet

package com.zjl.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

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

import com.sun.corba.se.impl.protocol.giopmsgheaders.Message;
import com.zjl.bean.Product;
import com.zjl.bean.User;
import com.zjl.dao.DaoFactory;
import com.zjl.service.IProductDao;
import com.zjl.service.IUserDao;

/**
 * 用户Servlet,处理用户登录,用户注册等
 * @author Administrator
 *
 */
public class UserServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public UserServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
	}

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

		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		//获取前台参数,根据参数选择对应的servlet方法进行业务处理
		String op = request.getParameter("op");
		
		if("register".equals(op)){//用户注册
			registerService(request,response);
		}else if("select".equals(op)){//查看用户
			selectService(request,response);
		}
	}

	/**
	 * 用户注册
	 * @param request
	 * @param response
	 */
	private void registerService(HttpServletRequest request,
			HttpServletResponse response) {
		
		//获取前台传递的三个参数,其中id在数据中使用自增字段,无需手动输入
		String name=request.getParameter("name");
		String password=request.getParameter("password");
		String password2 = request.getParameter("password2");
		
		User user =null;
		if(password.equals(password2)) {
			user = new User(name,password);
		}else {
			try {
				response.sendRedirect("register.jsp");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		IUserDao dao = DaoFactory.getUserDao();
		try{
		if(dao.insert(user)){
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}else{
			response.sendRedirect("register.jsp");
		}}
		catch(Exception e){
			e.printStackTrace();
		}
		
	}
	/**
	 * 查询用户
	 * @param request
	 * @param response
	 */
	private void selectService(HttpServletRequest request,
			HttpServletResponse response) {
		
		  IUserDao dao = DaoFactory.getUserDao();
		  String searchText = request.getParameter("searchText");
		  Map<String,Object> map = new HashMap<String, Object>();;
		  map.put("keyword", searchText);
		  List<User> list = dao.queryUser(map);
		  request.setAttribute("userList", list);
		  try{
		  if(list!=null){
			  request.getRequestDispatcher("user.jsp").forward(request, response);
		  }else{
			  response.sendRedirect("main.jsp");
		  }
		  }
		  catch(Exception e){
			  e.printStackTrace();
		  }
	}

	public void init() throws ServletException {
	}

}

6、前台页面

6.1、用户登录页

 

<%@ 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>用户登录</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
</head>
<body>
	<center>
		<!--处理登录的后台Servlet方法,Login。具体路径在web.xml中配置 -->
		<form action="Login" method="post">
		
			<!-- 用户名,后台LoginServlet中接收的值需和此处一致 -->
			用户名: <input type="text" name="username" /><br>
			
		    <!--密码,后台LoginServlet中接收的值需和此处一致 -->
			<br> 密&nbsp;&nbsp;码: <input type="password" name="password" /> <br>
			<br> <input type="submit" value="登录" /> &nbsp;&nbsp; <input
				type="reset" value="重置" /> <a href="register.jsp">注册</a>
		</form>
	</center>
</body>
</html>

 

6.2、主页

<%@ 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>主页</title>
    <style type="text/css">
    	#box{
    		width:850px;
    		margin:0 auto;
    	}
    	#top{
    	width:850px;
    	height:120px;
    	background-color:RGB(99,175,233);
    	
    	border:2px solid RGB(99,175,233);
    	}
    	#left{
    	widht:160px;	
    	height:498px;
    	float:left;
    	background-color:RGB(99,175,233);
    	text-align: left;
    	border:1px solid RGB(99,175,233);
    	
    	
    	}
    	#banner{
    	float:left;
    		width:850px;
    		height:41px;
    		border:2px solid RGB(99,175,233);
    		
    	}
    	#right{
    	 width:741px;
    	 height:500px;
    	 float:left;
    	     	 
    	}
    	#if{
    		width:744px;
    		height:496px;
    		border:2px solid RGB(99,175,233);
    	
    	}
    	body{
    		widht:100%;
    		height:100%;
    		
    	}
    	a{
    		text-decoration: none;
    		
    	}
    	ul{
    		list-style-type: none;
    		padding:0 20px;
    	}
    	#banneruser{
    		width:160px;
    		height:22px;
    	    margin-top: 9px;
            margin-left: 18px;
    	}
    </style>
  </head>
  
  <body>
  	<div id="box">
    	<div id="top">
    		
    	</div>
    	<div id="banner">
    		<!-- 显示当前用户,参数需和登录页用户名字段相符 -->
    		<div id="banneruser">当前用户:<a href=""><%=request.getParameter("username") %></a></div>
    	</div>
    	<div id="left">
    	<ul>
    		<li>
    			<a href="OperatorServlet?op=select" target="frame">显示产品</a>
    		</li>
    		<li>
    			<a href="insert.jsp" target="frame">添加产品</a>
    		</li>
    		<li>
    			<a href="UserServlet?op=select" target="frame">显示用户</a>
    		</li>
    		
    		
    	</ul>    
    	</div>
    	
    	<div id="right">
    		<iframe id="if" name="frame"></iframe>
    	</div>
   </div>
  </body>
</html>

 

6.3、商品展示页

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.zjl.dao.DaoFactory"%>
<%@page import="com.zjl.service.IProductDao"%>
<%@page import="com.zjl.bean.Product" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%
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>显示产品信息</title>
   <script>
   	function fun(val){
   		var r=confirm("确认删除吗?");
   		if(r){
   			location.href="OperatorServlet?op=del&id="+val;
   		}
   	}
   </script>
   <style>
   a{
    		text-decoration: none;
    		
    	}
   </style>
   
  </head>
  
  <body>
	<div>
		<form action="OperatorServlet?op=select" method="post"
			 class="search">
			<input style="border-radius: 0; width: 328;" name="searchText"
				type="text" placeholder="请输入名称或产地"> <input name="查询商品"
				type="submit" value="查询商品">
		</form>

	</div>
	<center>
	<!-- 这是新的商品展示页,使用jstl表达式,遍历后台传递的值 -->
		<table border="1" style="border:2px solid RGB(73,161,225)">
		<tr>
    			<th width="100">编号</th>
    			<th width="100">名称</th>
    			<th width="100">产地</th>
    			<th width="100">价格</th>  		
    			<th colspan="2" width="200">操作</th>	
    		</tr>
			<c:forEach var="Product" items="${productList}">
				<tr align="center">

					<td>${Product.id}</td>
					<td>${Product.name}</td>
					<td>${Product.addr}</td>
					<td>${Product.price}</td>
					<td><a href="update.jsp?id=${Product.id}&op=update">更新</a></td>
    				<td><a href="javascript:void(0);" onclick="fun(${Product.id})">删除</a></td>
				</tr>
			</c:forEach>
		</table>
		<!-- 这是旧的商品展示页 -->
    	<%-- <table border="1" style="border:2px solid RGB(73,161,225)">
    		<tr>
    			<th width="100">编号</th>
    			<th width="100">名称</th>
    			<th width="100">产地</th>
    			<th width="100">价格</th>  		
    			<th colspan="2" width="200">操作</th>	
    		</tr>
    		<%
    		IProductDao dao = DaoFactory.getProductDao();
    		 Map<String,Object> map = new HashMap<String,Object>();
    		List<Product> list = dao.queryProduct(map);
    		for(Product p:list){
    		%>
    		<tr>
    			<td><%=p.getId() %></td>
    			<td><%=p.getName() %></td>
    			<td><%=p.getAddr() %></td>
    			<td><%=p.getPrice() %></td>
    			<td><a href="update.jsp?id=<%=p.getId()%>&op=update">更新</a></td>
    			<td><a href="javascript:void(0);" onclick="fun(<%=p.getId() %>)">删除</a></td>
    		</tr>
    		<%} %>
    	</table>
 --%>    </center>
  </body>
</html>

 

6.4、商品更新页

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.zjl.bean.Product"%>
<%@page import="com.zjl.dao.DaoFactory"%>
<%@page import="com.zjl.service.IProductDao"%>

<%
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>更新产品</title>
    <style>
    	
    	input{
    		border:1px solid RGB(99,175,233);
    	}
    	}
    </style>
  </head> 
  <%
  request.setCharacterEncoding("utf-8");
  response.setContentType("text/html;charset=utf-8");
  
  int id =Integer.parseInt(request.getParameter("id"));
 
  Product p = new Product();
  p.setId(id);
  
  IProductDao dao = DaoFactory.getProductDao();
  p=dao.queryById(p);
  
  %>
  <body>
   	<center>
   	<h2>更新产品信息</h2>
   	 <form action="OperatorServlet?op=update" method="post">
   	 	<table border="0" >
   	 		<tr>
   	 			<td>编号</td>
   	 			<td>
   	 			<input type="text" name="id" readonly="readonly" value="<%=p.getId() %>"/>
   	 			</td>
   	 		</tr>
   	 		<tr>
   	 			<td>名称</td>
   	 			<td>
   	 			<input style="color:#7a7a7a" type="text" name="name" value="<%=p.getName()%>"/>
   	 			</td>
   	 		</tr>
   	 		<tr>
   	 			<td>产地</td>
   	 			<td>
   	 			<input style="color:#7a7a7a" type="text" name="addr" value="<%=p.getAddr()%>"/>
   	 			</td>
   	 		</tr>
   	 		<tr>
   	 			<td>价格</td>
   	 			<td>
   	 			<input style="color:#7a7a7a" type="text" name="price" value="<%=p.getPrice()%>"/>
   	 			</td>
   	 	   </tr>
   	 			
   	 		
   	 	</table>
   	 	<input type="submit" value="提交"/>&nbsp;&nbsp;
   	 	<input type="reset" value="重置"/>
   	 </form>
   	</center>
  </body>
</html>

 

6.5、商品添加页

 

<%@ 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>添加商品</title>
    <style>
    	input{
    		border:1px solid RGB(99,175,233);
    	}
    </style>
  </head>
  
  <body>
   	<center>
   		<h2>添加商品</h2>
   		<form action="OperatorServlet?op=insert" method="post">
   			
   			名称:<input type="text" name="name"/><br>
   			产地:<input type="text" name="addr"/><br>
   			价格:<input type="text" name="price"/><br>
   			<input type="submit" value="提交"/>&nbsp;&nbsp;
   			<input type="reset" value="重置"/>
   		</form>
   	</center>
  </body>
</html>

6.6、用户注册页

<%@ 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>用户注册</title>
    <style>
    	input{
    		border:1px solid RGB(99,175,233);
    	}
    </style>
  </head>
  
  <body>
   	<center>
   		<h2>用户注册</h2>
   		<form action="UserServlet?op=register" method="post">
   			
   			用户名:<input type="text" name="name"/><br>
   			密码:<input type="text" name="password"/><br>
   			确认密码:<input type="text" name="password2"/><br>
   			<input type="submit" value="提交"/>&nbsp;&nbsp;
   			<input type="reset" value="重置"/>
   		</form>
   	</center>
  </body>
</html>

6.7、用户显示页

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.zjl.dao.DaoFactory"%>
<%@page import="com.zjl.service.IUserDao"%>
<%@page import="com.zjl.bean.User" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%
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>显示用户信息</title>
   <script>
   	function fun(val){
   		var r=confirm("确认删除吗?");
   		if(r){
   			location.href="UserServlet?op=del&id="+val;
   		}
   	}
   </script>
   <style>
   a{
    		text-decoration: none;
    		
    	}
   </style>
   
  </head>
  
  <body>
  <div>
		<form action="UserServlet?op=select" method="post"
			 class="search">
			<input style="border-radius: 0; width: 328;" name="searchText"
				type="text" placeholder="请输入用户编号或姓名"> <input name="查询用户"
				type="submit" value="查询用户">
		</form>

	</div>
    <center>
     <table border="1" style="border:2px solid RGB(73,161,225)">
		<tr>
    			<th width="100">编号</th>
    			<th width="100">用户名</th>
    		    <th width="100">密码</th>
    			<th colspan="2" width="200">操作</th>
    		</tr>
			<c:forEach var="User" items="${userList}">
				<tr align="center">

					<td>${User.id}</td>
					<td>${User.name}</td>
					<td>${User.password}</td>
					<td><a href="updateUser.jsp?id=${User.id}&op=update">更新</a></td>
    				<td><a href="javascript:void(0);" onclick="fun(${User.id})">删除</a></td>
				</tr>
			</c:forEach>
		</table>
    <!-- 这是旧的用户信息页 -->
    	<%-- <table border="1" style="border:2px solid RGB(73,161,225)">
    		<tr>
    			<th width="100">编号</th>
    			<th width="100">用户名</th>
    		    <th width="100">密码</th>
    			<th colspan="2" width="200">操作</th>
    		</tr>
    		<%
    		IUserDao dao = DaoFactory.getUserDao();
    		List<User> list = dao.queryUser();
    		for(User user:list){
    		%>
    		<tr>
    			<td><%=user.getId() %></td>
    			<td><%=user.getName() %></td>
    			<td><%=user.getPassword() %></td>
    			<td><a href="updateUser.jsp?id=<%=user.getId()%>&op=update">更新</a></td>
    			<td><a href="javascript:void(0);" onclick="fun(<%=user.getId() %>)">删除</a></td>
    		</tr>
    		<%} %>
    	</table> --%>
    </center>
  </body>
</html>

6.8、用户更新页

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.zjl.bean.User"%>
<%@page import="com.zjl.dao.DaoFactory"%>
<%@page import="com.zjl.service.IUserDao"%>

<%
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>更新产品</title>
    <style>
    	
    	input{
    		border:1px solid RGB(99,175,233);
    	}
    	}
    </style>
  </head> 
  <%
  request.setCharacterEncoding("utf-8");
  response.setContentType("text/html;charset=utf-8");
  
  int id =Integer.parseInt(request.getParameter("id"));
 
  User u = new User();
  u.setId(id);
  
  IUserDao dao = DaoFactory.getUserDao();
  u=dao.queryByUserId(u);
  
  %>
  <body>
   	<center>
   	<h2>更新用户信息</h2>
   	 <form action="UserServlet?op=update" method="post">
   	 	<table border="0" >
   	 		<tr>
   	 			<td>编号</td>
   	 			<td>
   	 			<input type="text" name="id" readonly="readonly" 
value="<%=u.getId() %>"/>
   	 			</td>
   	 		</tr>
   	 		<tr>
   	 			<td>姓名</td>
   	 			<td>
   	 			<input style="color:#7a7a7a" type="text" name="name" 
value="<%=u.getName()%>"/>
   	 			</td>
   	 		</tr>
   	 		<tr>
   	 			<td>密码</td>
   	 			<td>
   	 			<input style="color:#7a7a7a" type="text" name="addr" 
value="<%=u.getPassword()%>"/>
   	 			</td>
   	 		</tr>
   	 			
   	 		
   	 	</table>
   	 	<input type="submit" value="提交"/>&nbsp;&nbsp;
   	 	<input type="reset" value="重置"/>
   	 </form>
   	</center>
  </body>
</html>

7、xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Java20180130MVC</display-name>
  
  <!--项目启动后,默认首页 -->
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- servlet名称声明,登录Servlet -->
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.zjl.servlet.LoginServlet</servlet-class>
  </servlet>
  <!-- servlet名称声明,商品操作servlet -->
  <servlet>
    <servlet-name>OperatorServlet</servlet-name>
    <servlet-class>com.zjl.servlet.OperatorServlet</servlet-class>
  </servlet>
  <!-- servlet名称声明,用户相关servlet -->
  <servlet>
    <servlet-name>UserServlet</servlet-name>
    <servlet-class>com.zjl.servlet.UserServlet</servlet-class>
  </servlet>

  <!--指定servlet映射路径 -->
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <!-- 指定/Login下的所有资源都由上文声明的LoginServlet处理 -->
    <url-pattern>/Login</url-pattern>
  </servlet-mapping>
  
  <servlet-mapping>
    <servlet-name>OperatorServlet</servlet-name>
    <!-- 指定/OperateServlet下的所有资源都由上文声明的OperateServlet处理 -->
    <url-pattern>/OperatorServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <!-- 指定/UserServlet下的所有资源都由上文声明的UserServlet处理 -->
    <url-pattern>/UserServlet</url-pattern>
  </servlet-mapping>
</web-app>


文末:

 

时间仓促,系统很简单,主要功能涉及到了数据库的增、删、改、查等操作,Servlet的配置及

使用,MVC思想的应用,DIV+CSS简单布局等。可以给初学者一个简单的参考,也是对自己

学习的一个记录。欢迎各位浏览,不吝赐教!

 

 

 

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页