本文章主要介绍了一个简单的实例:用简单的MVC分层思想,使用数据库在web界面进行增删改查,以及上传,模糊查询+分页的实现。

1.util层(数据库连接管理) :连接数据库需要导包:mysql-connector-java-5.1.22-bin.jar

/*** Copyright (C), 2001-2015* This program is protected by copyright laws.* Project:            SMS* Comments:  Connection Maintain* JDK version:   1.7* Author:            ybgong,23665701@qq.com* Create Date:   2015/1/1* Modified By:* Modified Date:* Version  1.0*/
package com.fruits.util;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;//数据库连接管理
public class ConnectionManager {private static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/fruits?useUnicode=true&characterEncoding=UTF-8";private static final String DATABASE_USRE = "root";private static final String DATABASE_PASSWORD = "123456";// 返回连接public static Connection getConnection() {Connection dbConnection = null;try {Class.forName(DRIVER_CLASS);dbConnection = DriverManager.getConnection(DATABASE_URL,DATABASE_USRE, DATABASE_PASSWORD);} catch (Exception e) {e.printStackTrace();}return dbConnection;}// 关闭连接public static void closeConnection(Connection dbConnection) {try {if (dbConnection != null && (!dbConnection.isClosed())) {dbConnection.close();}} catch (SQLException sqlEx) {sqlEx.printStackTrace();}}// 关闭结果集public static void closeResultSet(ResultSet res) {try {if (res != null) {res.close();}} catch (SQLException e) {e.printStackTrace();}finally{res = null;}}/*** 关闭语句* * @param pStatement*            PreparedStatement*/public static void closeStatement(PreparedStatement pStatement) {try {if (pStatement != null) {pStatement.close();}} catch (SQLException e) {e.printStackTrace();}finally{pStatement = null;}}public static void closeSt(Statement Statement) {try {if (Statement != null) {Statement.close();}} catch (SQLException e) {e.printStackTrace();}finally{Statement = null;}}
}
2.mode(实体)层:
package com.fruits.model;
/*** * gId:     商品id;* gName:商品名称;* gPrice: 商品标价;* tId:   类型ID;* sId:   商店ID;* gStocks:库存量;* gImageUrl: 商品图片路径;* gIntroduce  :    商品介绍;* @author UC**/
public class Goods {private  String gId;private String gName;private double gPrice;private String tId;private   String sId;private double gStocks;private String gImageUrl;private String gIntroduce;public Goods() {super();}public Goods(String gId, String gName,  double gPrice,String tId,String sId, double gStocks, String gImageUrl, String gIntroduce) {super();this.gId = gId;this.gName = gName;this.gPrice = gPrice;this.tId = tId;this.sId = sId;this.gStocks = gStocks;this.gImageUrl = gImageUrl;this.gIntroduce = gIntroduce;}public String getgId() {return gId;}public void setgId(String gId) {this.gId = gId;}public String getgName() {return gName;}public void setgName(String gName) {this.gName = gName;}public String gettId() {return tId;}public void settId(String tId) {this.tId = tId;}public double getgPrice() {return gPrice;}public void setgPrice(double gPrice) {this.gPrice = gPrice;}public String getsId() {return sId;}public void setsId(String sId) {this.sId = sId;}public double getgStocks() {return gStocks;}public void setgStocks(double gStocks) {this.gStocks = gStocks;}public String getgImageUrl() {return gImageUrl;}public void setgImageUrl(String gImageUrl) {this.gImageUrl = gImageUrl;}public String getgIntroduce() {return gIntroduce;}public void setgIntroduce(String gIntroduce) {this.gIntroduce = gIntroduce;}      }
<span style="font-size:10px;">3.dao(接口)层:</span>
package com.fruits.dao;import java.util.List;import com.fruits.model.Goods;public interface IGoods {//增加商品int addGoods(Goods goods);//删除商品int deleteGoods(String gid);//查看商品(模糊查询)List<Goods>getGoodsByName(String gname);//查看商品(通过gid查询)List<Goods>getGoodsById(String gid);//得到总页数int allPage(int row,String gname);//根据分页显示List<Goods>getGoodsPage(int page,int pagesize);//分页显示(模糊查询)List<Goods> getGoods(int page, int pagesize,String gname);//修改商品int updateGoods(Goods goods);
}

4.dao.impl(实现)层:

package com.fruits.dao.impl;import java.sql.*;
import java.util.ArrayList;
import java.util.List;import com.fruits.dao.IGoods;
import com.fruits.model.Goods;
import com.fruits.util.ConnectionManager;public class GoodsImpl  implements IGoods{private Connection connection;private PreparedStatement pst;private ResultSet results;/*** 添加商品*/@Overridepublic int addGoods(Goods goods) {// TODO Auto-generated method stubtry {String sql = "insert into Goods(gid,gname,gprice,tid,sid,gstocks,gimageurl,gintroduce)value(?,?,?,?,?,?,?,?)";//String sql = "insert into Goods value('123', '1', 1.0, '101', '111', 1,'1', '1')";connection = ConnectionManager.getConnection();pst=connection.prepareStatement(sql);pst.setString(1, goods.getgId());pst.setString(2, goods.getgName());pst.setDouble(3, goods.getgPrice());pst.setString(4, goods.gettId());pst.setString(5, goods.getsId());pst.setDouble(6,goods.getgStocks() );pst.setString(7, goods.getgImageUrl());pst.setString(8, goods.getgIntroduce());return pst.executeUpdate();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();return 0;}finally{ConnectionManager.closeStatement(pst);ConnectionManager.closeConnection(connection);}}/*** 删除商品*/@Overridepublic int deleteGoods(String gid) {// TODO Auto-generated method stubtry {String sql = "delete from Goods where gid=?";connection = ConnectionManager.getConnection();pst = connection.prepareStatement(sql);pst.setString(1, gid);return pst.executeUpdate();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();return  0;}finally{ConnectionManager.closeStatement(pst);ConnectionManager.closeConnection(connection);}}/*** 通过gid查询商品* */@Overridepublic List<Goods>getGoodsById(String gid){List<Goods> goodsList = new ArrayList<Goods>();String sql = "select * from Goods where gid =?";try {connection = ConnectionManager.getConnection();pst = connection.prepareStatement(sql);pst.setString(1, gid);results = pst.executeQuery();while(results.next()){goodsList.add(new Goods(results.getString(1),results.getString(2),results.getDouble(3),results.getString(4),results.getString(5),results.getDouble(6),results.getString(7),results.getString(8)));}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{ConnectionManager.closeResultSet(results);ConnectionManager.closeStatement(pst);ConnectionManager.closeConnection(connection);}return goodsList;}/*** 查询商品(通过商品名模糊查询)*/@Overridepublic List<Goods> getGoodsByName(String gname) {// TODO Auto-generated method stubString sql = "select * from goods where gname like  '%"+gname+"%' ";List<Goods> list = new ArrayList<Goods>();try {connection = ConnectionManager.getConnection();pst = connection.prepareStatement(sql);results = pst.executeQuery();while(results.next()){list.add(new Goods(results.getString(1),results.getString(2),results.getDouble(3),results.getString(4),results.getString(5),results.getDouble(6),results.getString(7),results.getString(8)));}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}finally{ConnectionManager.closeResultSet(results);ConnectionManager.closeStatement(pst);ConnectionManager.closeConnection(connection);}return list;}/*** 更新商品*/@Overridepublic int updateGoods(Goods goods) {// TODO Auto-generated method stubString sql = "UPDATE goods SET gname=?,gprice=?,tid=?,sid=?,gstocks=? ,gimageurl =? ,gintroduce=? WHERE gid=?";try {connection = ConnectionManager.getConnection();pst = connection.prepareStatement(sql);pst.setString(1, goods.getgName());pst.setDouble(2, goods.getgPrice());pst.setString(3, goods.gettId());pst.setString(4, goods.getsId());pst.setDouble(5,goods.getgStocks() );pst.setString(6, goods.getgImageUrl());pst.setString(7, goods.getgIntroduce());pst.setString(8, goods.getgId());return pst.executeUpdate();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();return 0;}finally{ConnectionManager.closeStatement(pst);ConnectionManager.closeConnection(connection);}}/** * 获取总页数用于分页* row:每页显示数量*/@Overridepublic int allPage(int row,String gname) {// TODO Auto-generated method stubList<Goods> goodsList = new ArrayList<Goods>();int allp=0;try {connection = ConnectionManager.getConnection();pst = connection.prepareStatement("select * from Goods where gname like'%"+gname+"%' ");results = pst.executeQuery();while(results.next()){goodsList.add(new Goods(results.getString(1),results.getString(2),results.getDouble(3),results.getString(4),results.getString(5),results.getDouble(6),results.getString(7),results.getString(8)));}/* results = pst.getResultSet();results.next();*/int all = goodsList.size();
//          int all  = results.getInt(1);allp = (all-1)/row+1;} catch (SQLException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}return allp;}/** 分页显示* page:页数* * (non-Javadoc)* @see com.fruits.dao.IGoods#getGoodsPage(int, int)*/@Overridepublic List<Goods> getGoodsPage(int page, int pagesize) {// TODO Auto-generated method stubList<Goods> goodsList = new ArrayList<Goods>();String sql = "select* from goods order by gid limit "+(page-1)*pagesize+","+pagesize+"";try {connection = ConnectionManager.getConnection();pst = connection.prepareStatement(sql);results = pst.executeQuery();while(results.next()){goodsList.add(new Goods(results.getString(1),results.getString(2),results.getDouble(3),results.getString(4),results.getString(5),results.getDouble(6),results.getString(7),results.getString(8)));}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{ConnectionManager.closeResultSet(results);ConnectionManager.closeStatement(pst);ConnectionManager.closeConnection(connection);}return goodsList;}/** page:页数* pagesize:每页显示的数量* gname:商品名* 分页显示 +模糊查询(non-Javadoc)* @see com.fruits.dao.IGoods#getGoods(int, int, java.lang.String)*/@Overridepublic List<Goods> getGoods(int page, int pagesize, String gname) {// TODO Auto-generated method stubList<Goods> goodsList = new ArrayList<Goods>();String sql = "select* from goods where gname like '%"+gname+"%'  order by gid limit  ?,?";try {int a=(page-1)*pagesize;int b=pagesize;connection = ConnectionManager.getConnection();pst = connection.prepareStatement(sql);pst.setInt(1, a);pst.setInt(2, b);results = pst.executeQuery();while(results.next()){goodsList.add(new Goods(results.getString(1),results.getString(2),results.getDouble(3),results.getString(4),results.getString(5),results.getDouble(6),results.getString(7),results.getString(8)));}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{ConnectionManager.closeResultSet(results);ConnectionManager.closeStatement(pst);ConnectionManager.closeConnection(connection);}return goodsList;}}

*上传之前记得在WebContent下创建一个upload文件夹,因为eclipse在Tomcat上发布工程时文件是在eclipse下环境目录下E:\java\eclipseWorkspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Fruits

这边是自动会创建upload缓存文件夹存放文件,但是要调用就得在WebContent下创建一个upload。注意调用时路径不要出错,也不要有中文。

<span style="font-size:10px;">**UploadServlet(上传):</span>
package com.fruits.controller;import java.io.File;
import java.io.IOException;
import java.util.List;import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.filefilter.SuffixFileFilter;@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {private static final long serialVersionUID = 1L;public UploadServlet() {super();}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request,response);}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setContentType("text/heml;charset=utf-8");String type=request.getParameter("type");String uploadPath=this.getServletContext().getRealPath("/")+"upload"; //定义上传文件的服务器地址System.out.println(uploadPath);File folder = new File(uploadPath);  //根据该路径创建File对象if(!folder.exists()) //如果路径不存在则创建路径folder.mkdirs();String Gid=null,Gname=null,Gprice=null,Tid=null,Sid=null,Gstocks=null,Gimageurl=null,Gintroduce=null;try{if(ServletFileUpload.isMultipartContent(request)){   //判断是否获取的是文件DiskFileItemFactory disk=new DiskFileItemFactory();        //创建磁盘工厂,用来配置上传组件ServletFileUploaddisk.setSizeThreshold(20*1024);    //设置内存可存字节数disk.setRepository(disk.getRepository());    //设置存放临时文件的目录ServletFileUpload up = new ServletFileUpload(disk);   //创建新的上传文件句柄int maxsize=5*1024*1024;       //定义上传文件的大小List<FileItem> files = up.parseRequest(request);String[] suffixs =new String[]{".exe",".bat",".jsp"};//限制上传的文件类型SuffixFileFilter filter = new SuffixFileFilter(suffixs);for(FileItem fileItem : files){   if(!fileItem.isFormField()){String filePath = fileItem.getName(); //获取文件全路径名System.out.println(filePath+"1");String fileName="";int startIndex = filePath.lastIndexOf("\\");if(startIndex!=-1){ //对文件名进行截取fileName=filePath.substring(startIndex+1);}else{fileName=filePath;}Gimageurl=fileName;System.out.println(fileName+"2");if(fileItem.getSize()>maxsize){//message="文件太大了,不要超过5MB";break;}String fileSize=new Long(fileItem.getSize()).toString();if((fileName==null)||(fileName.equals(""))&&(fileSize.equals("0"))){//message="文件名不能为空,文件大小也不能为零!";break;}/*if((fileName == null) ||(fileName.equals(""))&&(fileItem.getSize()==0))continue;*/File saveFile=new File(uploadPath,fileName);boolean res = filter.accept(saveFile);        //if(res){//message = "禁止上传 *.exe、*.jsp、*.bat文件!";break;}else{fileItem.write(saveFile);                   //向文件写数据System.out.println("文件上传成功!");//message="文件上传成功!";}}else{String foename=fileItem.getFieldName(); //获取表单元素名    String con = fileItem.getString("utf-8");    //获取表单内容,注意编码方式if(foename.equals("gname")){Gname=con;}else if(foename.equals("gid")){Gid=con;}else if(foename.equals("gprice")){Gprice=con;}else if(foename.equals("tid")){Tid=con;}else if(foename.equals("sid")){Sid=con;}else if(foename.equals("gstocks")){Gstocks=con;}else if(foename.equals("gintroduce")){Gintroduce=con;}}}      }}catch(Exception e){e.printStackTrace();}request.setAttribute("Gid", Gid);request.setAttribute("gname", Gname);request.setAttribute("gprice", Gprice);request.setAttribute("tid", Tid);request.setAttribute("sid", Sid);request.setAttribute("gstocks", Gstocks);request.setAttribute("gimageurl", Gimageurl);request.setAttribute("gintroduce", Gintroduce);System.out.println(Gid+"\t"+Gname+"\t"+Gprice+"\t"+Tid+"\t"+Sid+"\t"+Gstocks+"\t"+Gimageurl+"\t"+Gintroduce);if(type.equals("a")){request.getRequestDispatcher("/GoodsServlet?type=a").forward(request, response);}else if(type.equals("up")){request.getRequestDispatcher("/GoodsServlet?type=up").forward(request, response);}}public void init(ServletConfig config) throws ServletException {super.init(config);}
}
<span style="font-size:10px;">**GoodsServlet:</span>
package com.fruits.controller;import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.fruits.dao.IGoods;
import com.fruits.dao.impl.GoodsImpl;
import com.fruits.model.Goods;/*** Servlet implementation class GoodsServlet*/
@WebServlet("/GoodsServlet")
public class GoodsServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public GoodsServlet() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoPost(request, response);}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubrequest.setCharacterEncoding("utf-8");//请求为UTF-8格式response.setContentType("text/html;charset=utf-8");//响应为UTF-8格式PrintWriter out = response.getWriter();IGoods goodsImpl  = new  GoodsImpl();String type = request.getParameter("type");String gid = request.getParameter("gid");//添加操作if(type.equals("a")){String Gid = (String) request.getAttribute("Gid");String gname = (String) request.getAttribute("gname");String tid = (String) request.getAttribute("tid");String gprice = (String) request.getAttribute("gprice");String sid = (String) request.getAttribute("sid");String gstocks = (String) request.getAttribute("gstocks");String gimageurl = (String) request.getAttribute("gimageurl");String gintroduce = (String) request.getAttribute("gintroduce");System.out.println(gname+"\t"+gprice+"\t"+Gid+"\t"+sid+"\t"+gstocks+"\t"+gimageurl+"\t"+gintroduce);Goods goods = new Goods(Gid, gname,  Double.parseDouble(gprice), tid,sid, Double.parseDouble(gstocks), gimageurl, gintroduce);int  i =goodsImpl.addGoods(goods);if(i>0){out.print("<script>alert('添加成功');window.location.href = 'GoodsServlet?type=s';</script>");}else{out.print("<script>alert('添加失败');window.history.back(-1);</script> ");}}//删除操作else if(type.equals("d")){goodsImpl.deleteGoods(gid);out.print("<script>window.location.href = 'GoodsServlet?type=s';</script> ");}//修改(跳转goodsUpade.jsp界面)else if(type.equals("u")){List<Goods> goodsList=goodsImpl.getGoodsById(gid);ServletContext context = this.getServletContext();request.setAttribute("GoodsList", goodsList);context.getRequestDispatcher("/jsp/goods/goodsUpdate.jsp").forward(request, response);}//更新操作else if(type.equals("up")){String Gid = (String) request.getAttribute("Gid");String gname = (String) request.getAttribute("gname");String tid = (String) request.getAttribute("tid");String gprice = (String) request.getAttribute("gprice");String sid = (String) request.getAttribute("sid");String gstocks = (String) request.getAttribute("gstocks");String gimageurl = (String) request.getAttribute("gimageurl");String gintroduce = (String) request.getAttribute("gintroduce");System.out.println(gname+"\t"+gprice+"\t"+Gid+"\t"+sid+"\t"+gstocks+"\t"+gimageurl+"\t"+gintroduce);Goods goods = new Goods(Gid, gname,  Double.parseDouble(gprice), tid,sid, Double.parseDouble(gstocks), gimageurl, gintroduce);int i = goodsImpl.updateGoods(goods);if(i>0){out.print("<script>alert('修改成功');window.location.href = 'GoodsServlet?type=s';</script>");}else{out.print("<script>alert('修改失败');window.history.back(-1);</script> ");}}//查询操作else if(type.equals("s")){String gname = "";if(request.getParameter("gname")!=null){gname = request.getParameter("gname");}List<Goods> goodsList=goodsImpl.getGoodsByName(gname);request.setAttribute("Gname", gname);request.setAttribute("GoodsList", goodsList);request.getRequestDispatcher("jsp/goods/goodsMainTain.jsp").forward(request, response);}}
}

JSP页面要实现上传功能首先要有jar包:commons-fileupload.jar,commons-io.jar,jstl.jar,standard.jar。

JSP页上传页面关键代码:
<form action="<%=path %>/UploadServlet?type=a" method="post" enctype="multipart/form-data">
<span style="white-space:pre"> </span>
<span style="white-space:pre">                 </span><div class="m2">
<span style="white-space:pre">                     </span><div class="n1">
<span style="white-space:pre">                         </span><input id="GId" name="gid" type="text"
<span style="white-space:pre">                             </span>value="" class="n2m" οnchange="judge()"
<span style="white-space:pre">                             </span> />
<span style="white-space:pre">                     </span></div>
<span style="white-space:pre">                     </span><div class="n1">
<span style="white-space:pre">                         </span><input id="GName" name="gname" type="text"
<span style="white-space:pre">                             </span>value="" class="n2m" οnchange="judge()" />
<span style="white-space:pre">                     </span></div>
<span style="white-space:pre">                     </span><div class="n1">
<span style="white-space:pre">                         </span><input id="GPrice" name="gprice" type="text"
<span style="white-space:pre">                             </span>value="" class="n2m" οnchange="judge()" />
<span style="white-space:pre">                     </span></div>
<span style="white-space:pre">                     </span><div class="n1">
<span style="white-space:pre">                         </span><input id="TID" name="tid" type="text"
<span style="white-space:pre">                             </span>value="" class="n2m" οnchange="judge()" />
<span style="white-space:pre">                     </span></div>
<span style="white-space:pre">                     </span><div class="n1">
<span style="white-space:pre">                         </span><input id="SID" name="sid" type="text"
<span style="white-space:pre">                             </span>value="" class="n2m" οnchange="judge()" />
<span style="white-space:pre">                     </span></div>
<span style="white-space:pre">                     </span><div class="n1">
<span style="white-space:pre">                         </span><input id="GStocks" name="gstocks" type="text"
<span style="white-space:pre">                             </span>value="" class="n2m" οnchange="judge()" />
<span style="white-space:pre">                     </span></div>
<span style="white-space:pre">                     </span><div class="n1">
<!-- 上传路径C:\Users\UC\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Fruits\upload -->
<span style="white-space:pre">                         </span><input id="GImageUrl" name="gimageurl" type="file"
<span style="white-space:pre">                             </span>value="" class="n2m" οnchange="judge()" />
<span style="white-space:pre">                     </span></div>
<span style="white-space:pre">                     </span><div class="n1">
<span style="white-space:pre">                         </span><input id="GIntroduce" name="gintroduce" type="text"
<span style="white-space:pre">                             </span>value="" class="n2m"
<span style="white-space:pre">                             </span>οnchange="judge()" />
<span style="white-space:pre">                     </span></div><span style="white-space:pre">    </span>
<span style="white-space:pre">         </span>
<span style="white-space:pre">                     </span><div class="n1" style="padding-top: 50px;" align="center">
<span style="white-space:pre">                         </span><input type="submit" value="确认添加"
<span style="white-space:pre">                             </span>style="width: 80%; height: 40px; border-left-style: none;  font-size: 16px;" />
<span style="white-space:pre">                     </span></div>
<span style="white-space:pre">                 </span></div>
<span style="white-space:pre">             </span></form>

JSP显示图片关键代码:

<%@page import="com.fruits.dao.impl.GoodsImpl"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"import="java.util.*,com.fruits.model.*,com.fruits.dao.*,com.fruits.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>商品管理界面</title>
<%
//request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
%></head>
<body>                <!-------------商品详情显示表-----------------------------><table align="center" class="hovertable" cellpadding="0"cellspacing="0"><tr ><th width="70px;">商品ID</th><th width="100px;">商品名称</th><th width="80px;">商品标价</th><th width="70px;">类型ID</th><th width="70px;">商店ID</th><th width="70px;">存储量</th><th width="100px;">商品图片</th><th width="140px;">商品介绍</th><th class="th_borber" colspan="2">操作</th></tr><% <pre name="code" class="html" style="font-size:10px;"><span style="white-space:pre">                   </span>request.setCharacterEncoding("utf8");

/* List<Goods> goodsList = (List<Goods>) request.getAttribute("GoodsList"); */ /* 显示商品信息 ↓ */for (Goods goods : goodsList) {out.print("<tr οnmοuseοver='this.style.backgroundColor='#ffff66';' οnmοuseοut='this.style.backgroundColor='#d4e3e5';'>");out.print("<td>" + goods.getgId() + "</td>");out.print("<td>" + goods.getgName() + "</td>");out.print("<td>" + goods.getgPrice() + "</td>");out.print("<td>" + goods.gettId() + "</td>");out.print("<td>" + goods.getsId() + "</td>");out.print("<td>" + goods.getgStocks() + "</td>");out.print("<td ><img src='http://localhost:8080/Fruits/upload/"+goods.getgImageUrl()+"' width='55px' height='55px'/></td>");out.print("<td>" + goods.getgIntroduce() + "</td>");out.println("<td ><a style='color:blue' href="+path+"/GoodsServlet?type=u&gid="+ goods.getgId() + ">修 改</a></td>");out.print("<td><a style='color:blue' href ="+path+"/GoodsServlet?type=d&gid="+ goods.getgId()+ " οnclick=\"return confirm('确定要删除吗?')\">删 除</a></td>");out.print("</tr>");}/* 显示商品信息 ↑ */%></body></html>

MySQL表结构:

/*
SQLyog v10.2
MySQL - 5.0.22-community-nt : Database - fruits
*********************************************************************
*//*!40101 SET NAMES utf8 */;/*!40101 SET SQL_MODE=''*/;/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`fruits` /*!40100 DEFAULT CHARACTER SET utf8 */;USE `fruits`;/*Table structure for table `goods` */DROP TABLE IF EXISTS `goods`;CREATE TABLE `goods` (`GID` varchar(20) NOT NULL default '' COMMENT '商品ID',`GName` varchar(20) NOT NULL default '' COMMENT '商品名称',`GPrice` double(8,2) default NULL COMMENT '商品价格',`TID` varchar(20) default NULL COMMENT '类型ID',`SID` varchar(20) default NULL COMMENT '商店ID',`GStocks` double(8,2) default NULL COMMENT '库存量',`GImageUrl` varchar(30) default NULL COMMENT '商品图片路径',`GIntroduce` varchar(250) default NULL COMMENT '商品介绍',PRIMARY KEY  (`GID`),KEY `TID` (`TID`),KEY `SID` (`SID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;/*Data for the table `goods` */insert  into `goods`(`GID`,`GName`,`GPrice`,`TID`,`SID`,`GStocks`,`GImageUrl`,`GIntroduce`) values ('101','苹果1',33.00,'111','201',20.00,'lanmei.jpg','介绍'),('102','苹果2',33.00,'111','201',20.00,'shanzhu.jpg','介绍'),('103','苹果3',33.00,'111','201',20.00,'qiyiguo.jpg','介绍'),('104','苹果4',33.00,'111','201',20.00,'PT_1.jpg','介绍'),('105','苹果5',33.00,'111','201',20.00,'pingguo.jpg','介绍'),('106','苹果6',33.00,'111','201',20.00,'pt.jpg','介绍'),('107','苹果7',33.00,'111','201',20.00,'pingguo.jpg','介绍'),('108','苹果8',33.00,'111','201',20.00,'pingguo.jpg','介绍'),('109','哈密瓜9',20.00,'222','201',20.00,'boluo.jpg','介绍'),('110','苹果10',33.00,'111','202',20.00,'boluo.jpg','介绍'),('111','哈密瓜11',20.00,'222','202',20.00,'chelizi.jpg','介绍'),('112','苹果12',33.00,'111','202',20.00,'duo.jpg_1024x1024q90.jpg','介绍'),('113','哈密瓜13',20.00,'222','202',20.00,'huolongguo.jpg','介绍'),('114','苹果14',33.00,'111','202',20.00,'duo.jpg_1024x1024q90.jpg','介绍'),('115','哈密瓜15',20.00,'222','201',20.00,'huolongguo.jpg','介绍'),('116','苹果16',33.00,'111','201',20.00,'huolongguo.jpg','介绍'),('117','哈密瓜17',20.00,'222','202',20.00,'juzi.jpg_430x430q90.jpg','介绍'),('118','苹果18',33.00,'111','201',20.00,'juzi.jpg_430x430q90.jpg','介绍'),('119','哈密瓜19',20.00,'222','202',20.00,'lanmei.jpg','介绍'),('120','苹果20',33.00,'111','202',20.00,'li.jpg','介绍'),('121','哈密瓜21',20.00,'222','202',20.00,'lanmei.jpg','介绍'),('122','苹果22',33.00,'111','202',20.00,'li.jpg','介绍'),('123','苹果23',33.00,'111','201',20.00,'li.jpg','介绍'),('124','苹果24',33.00,'111','201',20.00,'liping_1.jpg','介绍'),('125','苹果25',33.00,'111','201',20.00,'liping_1.jpg','介绍'),('126','苹果26',33.00,'111','201',20.00,'liping_2.jpg','介绍'),('127','哈密瓜27',20.00,'222','201',20.00,'yezi.jpg','介绍'),('128','哈密瓜28',20.00,'222','201',20.00,'pt.jpg','介绍'),('129','哈密瓜29',20.00,'222','201',20.00,'LP_3.jpg','介绍'),('130','哈密瓜30',20.00,'222','201',20.00,'mangguo.jpg','介绍');/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

接下来介绍JSP显示数据分页+模糊查询:

AImin管理JSP:
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"import="java.util.*,com.fruits.model.*,com.fruits.dao.*,com.fruits.util.*"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%@include file="../top.jsp"%>
<%@include file="../left.jsp"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Admin管理界面</title>
<link rel="stylesheet" type="text/css"href="<%=path%>/css/admin-all.css" />
<link rel="stylesheet" type="text/css" href="<%=path%>/css/base.css" />
<style type="text/css">
table.hovertable {font-family: verdana, arial, sans-serif;font-size: 11px;color: #333333;border-width: 1px;border-color: #999999;border-collapse: collapse;width: 960px;
}table.hovertable th {height: 37px;background-color: #c7d8b8;border-width: 1px;padding: 8px;border-style: solid;border-color: #a9c6c9;font-size: 15px;
}table.hovertable tr {background-color: #dce4d5;
}table.hovertable td {border-width: 1px;padding: 8px;border-style: solid;border-color: #bacaab;font-size: 14px;text-align: center;
}
.bt{background-color: #c9daba;
}
</style>
<script language="javascript">function confirmDel(str) {return confirm(str);}
</script>
</head>
<body><div class="warp"><% request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");%><!--右边开始--><div class="right_c"></div><div class="Conframe"><!--右侧代码内容部分开始(白色区域内)  --><!--------------------查询区域----------------><divstyle="width: 90%; height: 60px; padding-left: 250px; margin-top: 20px;"><form action="<%=path%>/PageServlet" method="post"><span style="font-size: 18px">请输入管理员账号:</span> <input type="text"name="AdminId" style="width: 200px; height: 20px;" value=""> <inputtype="submit" value="查询"style="width: 150px; height: 30px; margin-left: 20px; border-style: none; background-color: #c9daba;"οnmοuseοver=""></form></div><!------------------------------------------><!-------------商品详情显示表-----------------------------><table align="center" class="hovertable" cellpadding="0"cellspacing="0"><tr><th class="th_border">管理员账号</th><th class="th_border">管理员密码</th><th class="th_borser"></th><th class="th_borser"></th></tr><c:forEach items="${admin1}" var="admin2" varStatus="status"><tr><td>${admin2.adminID}</td><td>${admin2.aPassword}</td><td><a style='color:blue' href="<%=path %>/AdminServlet?type=u&AdminId=${admin2.adminID}">修 改</a></td><td><a style='color:blue' href="<%=path %>/AdminServlet?type=d&AdminId=${admin2.adminID}"οnclick="return confirmDel('确定要删除吗')">删 除</a></td></tr></c:forEach></table><table align="center" class="hovertable" cellpadding="0" cellspacing="0"><tr><!-- <form action="PageServlet" method="post"> --><% if(session.getAttribute("AdminId")==null){session.setAttribute("AdminId", "");}%><c:if test="${currentpageno>1}"><td align="center"><form action="PageServlet" method="post"><input type="hidden"  name="AdminId" value="<%=session.getAttribute("AdminId")%>" /><input type="submit"  value="首页" /> <input type="hidden"  name="currentpageno" value="<%=1%>" /> <%-- <a href="PageServlet?currentpageno=<%=1%>">首页</a> --%></form></td><td align="center"><form action="PageServlet" method="post"><input type="hidden"  name="AdminId" value="<%=session.getAttribute("AdminId")%>" /><input type="submit"  value="上一页" /> <input type="hidden"  name="currentpageno" value="${currentpageno-1}" /> <%-- <a href="PageServlet?currentpageno=${currentpageno-1}">上一页</a> --%></form></td></c:if><c:if test="${currentpageno<PageCount}"><td align="center"><form action="PageServlet" method="post"><input type="hidden"  name="AdminId" value="<%=session.getAttribute("AdminId")%>" /><input type="submit"  value="下一页" /> <input type="hidden"  name="currentpageno" value="${currentpageno+1}" /> <%-- <a href="PageServlet?currentpageno=${currentpageno+1}">下一页</a> --%></form></td><td align="center"><form action="PageServlet" method="post"><input type="hidden"  name="AdminId" value="<%=session.getAttribute("AdminId")%>" /><input type="submit"  value="最后一页" /> <input type="hidden"  name="currentpageno" value="${PageCount}" /> <%-- <a href="PageServlet?currentpageno=${PageCount}">最后一页</a> --%></form></td></c:if><td align="center"><form action="PageServlet" method="post"><input type="hidden"  name="AdminId" value="<%=session.getAttribute("AdminId")%>" /><input type="text" name="currentpageno" width="5px" /> <input type="submit" value="Go" /></form></td><td align="center">第${currentpageno}页一共${PageCount}页<!--  </form> --></td></tr></table><!--右侧结算(白色区域内)  --></div><!--右边结束--></div>
</body>
</html>

略去Admin的实体层和接口层

实现层Impl:

package com.fruits.dao.impl;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;import com.fruits.dao.IAdmin;
import com.fruits.model.Admin;
import com.fruits.util.ConnectionManager;public class AdminImpl implements IAdmin{private Connection connection;private PreparedStatement pst;private ResultSet rs;private static int pagesize = 3;/*** 获取所有管理员*/@Overridepublic  List<Admin> getAllAdmin() {List<Admin> adminList = new ArrayList<Admin>();try {connection = ConnectionManager.getConnection();pst = connection.prepareStatement("select * from Admin");rs = pst.executeQuery();while (rs.next()) {adminList.add(new Admin(rs.getString(1),rs.getString(2)));}}// 处理数据库异常catch (SQLException exception) {exception.printStackTrace();return null;}// 释放资源finally {ConnectionManager.closeResultSet(rs);ConnectionManager.closeStatement(pst);ConnectionManager.closeConnection(connection);}return adminList;}/*** 添加管理员*/@Overridepublic int addAdmin(Admin admin) {try {connection = ConnectionManager.getConnection();pst = connection.prepareStatement("insert into Admin values (?,?)");pst.setString(1, admin.getAdminID());pst.setString(2, admin.getaPassword());return pst.executeUpdate(); } catch (SQLException e) {e.printStackTrace();return 0;}   // 释放资源finally {ConnectionManager.closeStatement(pst);ConnectionManager.closeConnection(connection);}}/*** 删除管理员*/@Overridepublic int deleteAdmin(String id) {try {connection = ConnectionManager.getConnection();pst = connection.prepareStatement("delete from Admin where aID=?");pst.setString(1,id);return pst.executeUpdate(); } catch (SQLException e) {e.printStackTrace();return 0;}finally {ConnectionManager.closeStatement(pst);ConnectionManager.closeConnection(connection);}}/*** 修改管理员*/@Overridepublic  int updateAdmin(Admin admin) {try {connection = ConnectionManager.getConnection();String sql = "update Admin set APassword=? where AID=?";pst = connection.prepareStatement(sql);    pst.setString(1, admin.getaPassword());pst.setString(2, admin.getAdminID());return pst.executeUpdate(); } catch (SQLException e) {e.printStackTrace();return 0;}finally {ConnectionManager.closeStatement(pst);ConnectionManager.closeConnection(connection);}}/*** 以ID精确查找管理员*/@Overridepublic List<Admin> findAdminById(String id) {List<Admin> adminList = new ArrayList<Admin>();try {connection = ConnectionManager.getConnection();pst = connection.prepareStatement("select * from Admin where AID=?");pst.setString(1, id);rs = pst.executeQuery();while (rs.next()) {adminList.add(new Admin(rs.getString(1),rs.getString(2)));}}// 处理数据库异常catch (SQLException exception) {exception.printStackTrace();return null;}// 释放资源finally {ConnectionManager.closeResultSet(rs);ConnectionManager.closeStatement(pst);ConnectionManager.closeConnection(connection);}return adminList;}/*** 以ID模糊查找管理员*/@Overridepublic List<Admin> getAdminById(String aId) {List<Admin> adminList = new ArrayList<Admin>();try {connection = ConnectionManager.getConnection();pst = connection.prepareStatement("select * from Admin where AID like '%" +aId+"%' ");rs = pst.executeQuery();while (rs.next()) {adminList.add(new Admin(rs.getString(1),rs.getString(2)));}}// 处理数据库异常catch (SQLException exception) {exception.printStackTrace();return null;}// 释放资源finally {ConnectionManager.closeResultSet(rs);ConnectionManager.closeStatement(pst);ConnectionManager.closeConnection(connection);}return adminList;}
//=====================查询========================================@Overridepublic List<Admin> getAdminList(int currentPageNo,String aId) {List<Admin> adminList = new ArrayList<Admin>();int beginRecord = (currentPageNo - 1) * pagesize;int endRecord =pagesize;String sql="select * from Admin where AID like '%" +aId+"%' limit " + beginRecord + ","    + endRecord;System.out.println(sql);rs = ExecuteQuery(sql);try {while (rs.next()) {adminList.add(new Admin(rs.getString(1),rs.getString(2)));}} catch (SQLException e) {e.printStackTrace();}// 释放资源finally {ConnectionManager.closeResultSet(rs);ConnectionManager.closeStatement(pst);ConnectionManager.closeConnection(connection);}return adminList;}@Overridepublic int getPageCount(String aId) {int total = 0;int pageCount = 0;rs = ExecuteQuery("select count(*) from Admin where AID like '%" +aId+"%' ");try {if (rs.next()) {total = rs.getInt(1);pageCount = (total - 1) / pagesize + 1;}} catch (SQLException e) {e.printStackTrace();}// 释放资源finally {ConnectionManager.closeResultSet(rs);ConnectionManager.closeStatement(pst);ConnectionManager.closeConnection(connection);}return pageCount;}// 通用的查询方法public ResultSet ExecuteQuery(String sql) {try {connection = ConnectionManager.getConnection();pst = connection.prepareStatement(sql);rs = pst.executeQuery();} catch (SQLException e) {e.printStackTrace();}return rs;}
}

PageServlet:实现分页功能

package com.fruits.controller;import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;import javax.servlet.ServletException;
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;import com.fruits.dao.IAdmin;
import com.fruits.dao.impl.AdminImpl;
import com.fruits.model.Admin;@WebServlet("/PageServlet")
public class PageServlet extends HttpServlet {private static final long serialVersionUID = 1L;public PageServlet() {super();}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request,response);}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");    //查询操作String aId="";if(request.getParameter("AdminId")!=null){//aId = request.getParameter("AdminId");HttpSession session1 =request.getSession();session1.setAttribute("AdminId", request.getParameter("AdminId"));aId = request.getParameter("AdminId");}String pageno = request.getParameter("currentpageno");int currentpageno = 1;if (pageno != null) {currentpageno = Integer.parseInt(pageno);}List<Admin> adminList = new AdminImpl().getAdminList(currentpageno,aId);request.setAttribute("admin1", adminList);request.setAttribute("currentpageno", currentpageno);request.setAttribute("PageCount", new AdminImpl().getPageCount(aId));request.getRequestDispatcher("/jsp/admin/adminMainTain.jsp").forward(request,response);}}

以上代码为本人拙作,如有更好的建议,请大家指出!一起学习.

MVC分层+JDBC+数据库+Servlet实现JSP文件上传和显示+模糊查询+分页相关推荐

  1. JSP 文件上传下载系列之二[Commons fileUpload]

    前言 关于JSP 文件上传的基础和原理在系列一中有介绍到. 这里介绍一个很流行的组件commons fileupload,用来加速文件上传的开发. 官方的介绍是:  让添加强壮,高性能的文件到你的se ...

  2. 原生Servlet文件上传和下载Servlet多个文件上传

    2019独角兽企业重金招聘Python工程师标准>>> 转载:原文连接https://blog.csdn.net/HaHa_Sir/article/details/81744629 ...

  3. 【JSP HTTP 状态码】【JSP 表单处理】【JSP 过滤器】【JSP Cookie 处理】【JSP Session】【JSP 文件上传】

    JSP HTTP 状态码 HTTP请求与HTTP响应的格式相近,都有着如下结构: 以状态行+CRLF(回车换行)开始 零行或多行头模块+CRLF 一个空行,比如CRLF 可选的消息体比如文件,查询数据 ...

  4. Flask与微信小程序之文件上传与显示

    文章目录 Flask与微信小程序之文件上传与显示 背景 flask_uploads应用 flask_uploads的使用步骤 1 安装flask-uploads模块 2 在文件夹中导入需要用到的库 3 ...

  5. Struts2实现文件上传并显示实时进度

    基于浏览器的文件上传,特别是对于通过<input type="file">标签来实现上传的情况, 存在着严重的性能问题,因为用户提交了文件之后,在浏览器把文件上传到服务 ...

  6. php中图片文件上传,显示缩略图

    php中图片文件上传,显示缩略图 htm代码块: <meta charset="utf-8" /> <style>img {max-width: 100px ...

  7. Knife4j文件上传不显示上传选择文本域

    Knife4j文件上传不显示上传选择文本域 升级新版本过后不显示上传文件按钮 前置配置 配置效果 解决方式 整体代码贴图 升级新版本过后不显示上传文件按钮 官方解决方法:并不能解决knife4j3.0 ...

  8. jsp文件上传_文件上传

    一.文件上传的目的--脚本文件 文件上传的一共可造成三种危害,从低到高分别是,任意内容文件,html文件,脚本文件. 任意内容文件 任意内容文件指的是虽然文件后缀不可控,但是文件内容可控,比如我可以上 ...

  9. jsp文件上传_猿蜕变系列7——也说说springMVC上传姿势

    看过之前的蜕变系列文章,相信你对springMVC有了一定的认识.对springMVC的异常处理,也有了一定的认识.今天我们来开启新讨论,讲一讲web开发中会经常遇到的一个功能,文件上传. 猿蜕变同样 ...

最新文章

  1. Mysql组复制故障恢复测试
  2. hibernate 集合类(Collections)映射
  3. axure文本框值相加_Axure教程:计数文本域实现
  4. SQL Server【一】简介和基本概念和命令
  5. 深入浅出SharePoint——WSS升级和数据迁移
  6. 【目标检测】NMS和soft-NMS详解及代码实现
  7. class反编译成java_Java黑科技之源:JVMTI完全解读
  8. Trick(三)——循环左移的实现
  9. java 反射 构造器_Java之类的构造器(反射)
  10. 计算机全息图的制作与在线,基于Matlab的计算全息图的制作与数字再现的研究精选.doc...
  11. C语言常见面试题汇总
  12. 4米乘以12米CAD图_【超干货】CAD铺装排版下料之路径阵列
  13. 网络适配器消失不见?
  14. JavaScript 实现 标签页 切换效果
  15. Map接口总结与HashMap源码分析
  16. 为什么NR PDCP SDU最大为9000?
  17. android ui设计最新字体,2017年最新最直白的app界面设计字体规范
  18. Proxy与Reflect详解
  19. arm服务器虚拟x86,x86服务器与arm
  20. Precision T7910 图形工作站win7和linux双系统安装

热门文章

  1. 计算机任务无法结束,电脑无法通过任务管理器结束一些卡死的程序怎么解决
  2. java播放器_java播放器
  3. 爱情麻辣烫的江湖秘笈
  4. 独热码one-hot code
  5. 微信小程序免费HTTPS证书申请搭建教程(2)---安装SSL并使用HTTPS访问
  6. 程序员架构修炼之道:如何设计“易理解”的系统架构?
  7. 阿里云相关-弹性公网IP
  8. ip virtual-reassembly:IP虚拟分片重组
  9. 山东十大计算机排名2015,山东省各市人口数量2015年排名
  10. 收集一些JAVA实习生面试值得注意的问题