本文实现一个简单的 java web 项目,包括以下5个功能:
1. 登录
用户默认主页index.jsp , 可选择登录功能,输入用户名和密码,若登录成功,则进入产品管理总页面main.jsp。若不成功仍退回index.jsp
2. 注册
用户默认主页index.jsp , 可选择注册功能 ,若注册,则进入 register.jsp
3. 管理产品(增加,删除,查看)
登录成功后,进入产品管理总页面main.jsp。第一次进入main.jsp,默认显示所有产品列表。在此页面上更实现 查询某个产品记录,添加产品,批量删除,选中一项产品查看详情,实现分页功能。
3.1 添加产品
3.2 查询"圣女果"
3.3 选择“香蕉” ,点击 “查看”
4. 退出
用户点击“退出”时,清除session,退回主页面index.jsp
5. 过滤器
若用户没有登录成功,而直接访问 main.jsp 或 addProduct.jsp ,则被过滤器过滤到 index.jsp . 因为有成功登录,验证其身份后,才有权利访问产品和管理产品。否则将被过滤到默认主页index.jsp.
例如:在地址栏直接输入:http://192.168.0.103:8080/xianfengProject/main.jsp,则被过滤到index.jsp
-------------------------------------------------------------------------------
项目环境:
操作系统:win7
实现技术:jsp+servlet
数据库: mysql5.5.20 , Navicat_for_MySQL_11.0.10
服务器:apache-tomcat-7.0.40
开发平台: MyEclipse10
--------------------------------------------------------------------------------
说明:
1. 数据库
数据库名:mydb , 共两张表.
表一:userinfo (id , username , pswd)
表二:product (proid , proname, proprice , proaddress , proimage)
product (proid , proname, proprice , proaddress , proimage)表结构:
userinfo (id , username , pswd)表结构如下:
2. MyEclipse 工程目录
----------------------------------------------------------------------------------------------------------------------
1. index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>先锋管理系统欢迎您</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript"> function login(){ var th = document.form1; if(th.username.value==""){ alert("用户名不能为空!"); th.username.focus(); return; } if(th.pswd.value==""){ alert("密码不能为空!"); th.pswd.focus(); return; } th.action = "<%=path%>/servlet/LoginAction"; th.submit(); } </script> </head> <body> <div style="text-align:center"> <form name="form1" action="" method="post"> <table style="margin:auto"> <tr> <td colspan="2"> 先锋管理系统欢迎你! </td> </tr> <tr> <td>用户名:</td> <td><input type="text" name="username"></input></td> </tr> <tr> <td>密 码:</td> <td><input type="password" name="pswd"></input></td> </tr> <tr> <td colspan="2" align="center"> <button type="button" name="" value="" onclick="login()">登录</button> <button type="button" name="" value="" onclick="javascript:location.href=‘register.jsp‘">注册</button> </td> </tr> </table> </form> </div> </body> </html>
2. register.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>注册新用户</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript"> function dosubmit(){ var th = document.form1; if(th.username.value==""){ alert("用户名不能为空!"); th.username.focus(); return; } if(th.pswd.value==""){ alert("密码不能为空!"); th.pswd.focus(); return; } th.action="<%=path%>/servlet/RegisterAction"; th.submit(); } function back(){ alert("退回主页!"); th = document.form1; th.acton="<%=path%>/index.jsp"; th.submit; } </script> </head> <body> <div style="text-align:center"> <form action="" name="form1" method="post"> <table style="margin:auto"> <tr> <td colspan="3"> 用户注册 </td> </tr> <tr> <td>用户名:</td> <td><input type="text" name="username"></input></td> <td>必须填写!</td> </tr> <tr> <td>密 码:</td> <td><input type="password" name="pswd"></input></td> <td>必须填写!</td> </tr> <tr> <td colspan="3" align="center"> <button type="button" name="" onclick="dosubmit()" >确定</button> <button type="button" name="" value="" onclick="javascript:location.href=‘index.jsp‘" >返回</button> </td> </tr> </table> </form> </div> </body> </html>
3.main.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ page import="com.util.*" %> <%@ page import="com.product.*" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; //获取 session 中的 username; String username = (String)session.getAttribute("username"); //获取从 servlet ProductActiion 中 传递的参数(数据库查询的结果) List<Map<String,Object>> list =(List<Map<String,Object>>) request.getAttribute("listProduct"); // 获取 分页对象 DividePage dividePage = (DividePage) request.getAttribute("dividePage"); // 获取查询的关键词 String productName = (String) request.getAttribute("productName"); if(list==null){ //第一次进 main.jsp页面,默认加载所有的产品 ProductService service = new ProductDao(); int totalRecord = service.getItemCount(""); dividePage = new DividePage(5,totalRecord,1); int start = dividePage.fromIndex(); int end = dividePage.toIndex(); list = service.listProduct("", start, end); } %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>产品管理</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript"> function searchProduct(){ var th = document.form2; th.action="<%=path%>/servlet/ProductAction?action_flag=search"; th.submit(); } function first(){ window.location.href = "<%=path%>/servlet/ProductAction?action_flag=search&pageNum=1"; } function next(){ window.location.href = "<%=path%>/servlet/ProductAction?action_flag=search&pageNum=<%=dividePage.getCurrentPage()+1%>"; } function forward(){ window.location.href = "<%=path%>/servlet/ProductAction?action_flag=search&pageNum=<%=dividePage.getCurrentPage()-1%>"; } function end(){ window.location.href = "<%=path%>/servlet/ProductAction?action_flag=search&pageNum=<%=dividePage.getPageCount() %>"; } function changePage(currentPage){ window.location.href = "<%=path%>/servlet/ProductAction?action_flag=search&pageNum="+currentPage; } function selectAll(flag){ var ids = document.getElementsByName("ids"); for(var i = 0 ; i < ids.length ; i++){ ids[i].checked = flag; } } function getSelectedCount(){ var ids = document.getElementsByName("ids"); var count = 0; for(var i = 0 ; i < ids.length ; i++) { ids[i].checked==true?count++:0; } return count; } function del(){ if(getSelectedCount()==0){ alert("至少选择一个删除项!"); return; } var th = document.form1; th.action="<%=path%>/servlet/ProductAction?action_flag=del"; th.submit(); } function getSelectedValue(){ var ids = document.getElementsByName("ids"); for(var i = 0 ; i < ids.length ; i++) { if(ids[i].checked){ return ids[i].value; } } } function view(){ if(getSelectedCount()<1){ alert("至少选择一个查看项!"); return; }else if(getSelectedCount()>1){ alert("只能选择一个查看项!"); return; } var th = document.form1; th.action="<%=path%>/servlet/ProductAction?action_flag=view&proid="+getSelectedValue(); th.submit(); } function logout(){ window.location.href="<%=path %>/servlet/LogoutAction?action_flag=logout"; } </script> </head> <body> <div> <table width=60% align="center"> <tr> <td align="left"><font size=2>欢迎您的光临,<%=username%><br><a href="javascript:logout();">退出</a></font></td> </tr> <tr> <td align="center"> <form name = "form2" action="" method="post"> <table> <tr> <td colspan="2">产品信息查询</td> </tr> <tr> <td >产品名称</td> <td ><input type="text" name="proname" value="<%= productName!=null?productName:"" %>"/></td> </tr> <tr> <td colspan="2" align="center"> <button type="button" onclick="searchProduct()" >查询</button> <button type="button" onclick="javascript:location.href=‘<%=path %>/addProduct.jsp‘">添加</button> </td> </tr> </table> </form> </td> </tr> <tr> <td height=50> </td> </tr> <tr> <td> 查询结果</td> </tr> <tr> <td > <form name="form1" action="" method="post"> <table border=1 width=100%> <tr align="center"> <td width=10%><input type="checkbox" name="checkall" onclick="javascript:selectAll(this.checked);" /></td> <td width=30%>产品名称</td> <td width=30%>产品产地</td> <td>产品价格</td> </tr> <% if(list!=null && !list.isEmpty()){ for(Map<String,Object> map :list){%> <tr align="center"> <td width=10%><input type="checkbox" name="ids" value="<%=map.get("proid") %>"/></td> <td width=30%><%=map.get("proname") %></td> <td width=30%><%=map.get("proaddress") %></td> <td><%=map.get("proprice") %></td> <%} }else{%> <tr align="center"> <td width=10%><input type="checkbox" name="" /></td> <td width=30%></td> <td width=30%></td> <td></td> </tr><% } %> </table> </form> </td> </tr> <tr> <td> <button type="button" onclick="javascript:del();">删除</button> <button type="button" onclick="javascript:view();" >查看</button> </td> </tr> <tr> <td colspan="4" align="center"> 共<%=dividePage.getPageCount() %>页 <a href="javascript:first();">首页</a> <a href="javascript:forward();">上一页</a> <a href="javascript:next();">下一页</a> <a href="javascript:end();">尾页</a> 跳转到<select name="select" onchange="changePage(this.value)"> <% int pageCount = dividePage.getPageCount(); if(pageCount>0){ for(int i = 1 ; i<=pageCount;i++){%> <option value="<%=i %>" <%= (i==dividePage.getCurrentPage()?"selected":"")%>> <%=i %> </option> <% } }else{// 无记录 %> <option value="1">1</option> <%} %> </select> </td> </tr> </table> </div> </body> </html> 原文 http://blog.csdn.net/neu_yousei/article/details/23943857
4.addProduct.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>新增产品</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript"> function dosubmit(){ var th = document.form1; th.action="<%= path%>/servlet/ProductAction?action_flag=add"; th.submit(); } </script> </head> <body> <div align="center"> <table width=70% style="margin:auto;"> <tr><td align="center" height=150 valign="bottom">产品信息添加</td></tr> <tr> <td> <form id="form1" name="form1" action="" method="post" enctype="multipart/form-data"> <table border=1 style="margin:auto"> <tr > <td>产品名称</td> <td><input type="text" name="proname" id="proname"/></td> <td>产品价格</td> <td><input type="text" name="proprice" id="proprice"/></td> </tr> <tr> <td>产品产地</td> <td colspan="3"><input type="text" name="proaddress" id="proaddress"/></td> </tr> <tr> <td>产品图片</td> <td colspan="3"><input type="file" name="proimage" id="proimage" size=35/></td> </tr> </table> </form> </td> </tr> <tr> <td colspan="4" align="center"> <button type="button" onclick="javascript:dosubmit();">确定</button> <button type="button" onclick="javascript:location.href=‘main.jsp‘">返回</button> </td> </tr> </table> </div> </body> </html>
5. viewProduct.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; Map<String,Object> map = (Map<String,Object>)request.getAttribute("productMap"); %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>查看产品</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <div align="center"> <table width=60% style="margin:auto"> <tr> <td height=100> </td> </tr> <tr> <td > 产品信息 </td> </tr> <tr> <td> <table width = 99% border =1 > <tr align="center"> <td width = 20%>产品名称</td> <td width = 30%><%=map.get("proname") %></td> <td width = 20%>产品价格</td> <td><%=map.get("proprice") %></td> </tr> <tr align="center"> <td >产品产地</td> <td colspan=3><%=map.get("proaddress") %></td> </tr> <tr align="center"> <td>产品图片</td> <td colspan=3><img src="<%=path%>/upload/<%=map.get("proimage") %>"></td> </tr> </table> </td> </tr> <tr> <td align="center"> <button type="button" onclick="javascript:location.href=‘<%=path %>/main.jsp‘">确定</button> <button type="button" onclick="javascript:history.go(-1)">返回</button> </td> </tr> </table> </div> </body> </html>
6.LoginAction.java
package com.login; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginAction extends HttpServlet { private LoginService service; /** * Constructor of the object. */ public LoginAction() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); String path = request.getContextPath(); String username = request.getParameter("username"); String pswd = request.getParameter("pswd"); List<Object> params = new ArrayList<Object>(); params.add(username); params.add(pswd); boolean flag = service.login(params); if (flag) { request.getSession().setAttribute("username", username); response.sendRedirect(path+"/main.jsp"); }else{ response.sendRedirect(path+"/index.jsp"); } out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here service = new LoginDao(); } }
7.LoginDao.java
package com.login; import java.sql.SQLException; import java.util.List; import java.util.Map; import javax.mail.Flags.Flag; import com.jdbc.JdbcUtils; public class LoginDao implements LoginService { private JdbcUtils jdbcUtils; public LoginDao() { // TODO Auto-generated constructor stub jdbcUtils = new JdbcUtils(); } @Override public boolean login(List<Object> params) { // TODO Auto-generated method stub boolean flag = false; try { jdbcUtils.getConnection(); String sql = "select * from userinfo where username = ? and pswd = ?"; Map<String, Object> map = jdbcUtils.findSimpleResult(sql, params); flag = !map.isEmpty()?true:false; } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ //关闭数据库 jdbcUtils.releaseConn(); } return flag; } }
8.LoginService.java
package com.login; import java.util.List; public interface LoginService { public boolean login(List<Object> params); }
9. MyFilter.java
package com.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyFilter implements Filter { public MyFilter() { // TODO Auto-generated constructor stub } @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { // 过滤用户请求,判断是否登录 HttpServletRequest httpServletRequest = (HttpServletRequest)request; HttpServletResponse httpServletResponse = (HttpServletResponse)response; httpServletRequest.setCharacterEncoding("utf-8"); httpServletResponse.setCharacterEncoding("utf-8"); String username = (String)httpServletRequest.getSession().getAttribute("username"); if (username == null) { String path = httpServletRequest.getContextPath(); httpServletResponse.sendRedirect(path+"/index.jsp"); } filterChain.doFilter(httpServletRequest, httpServletResponse); } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
10.RegisterAction.java
package com.register; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RegisterAction extends HttpServlet { private RegisterService service; /** * Constructor of the object. */ public RegisterAction() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); String path = request.getContextPath(); String username = request.getParameter("username"); String pswd = request.getParameter("pswd"); List<Object> params = new ArrayList<Object>(); params.add(username); params.add(pswd); boolean flag = service.registerUser(params); if (flag) { response.sendRedirect(path+"/index.jsp"); } out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here service = new RegisterDao(); } }
11. RegisterDao.java
package com.register; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.jdbc.JdbcUtils; public class RegisterDao implements RegisterService { private JdbcUtils jdbcUtils; public RegisterDao() { // TODO Auto-generated constructor stub jdbcUtils = new JdbcUtils(); } /* 完成对用户注册的dao的编写 * @see com.register.service.RegisterService#registerUser(java.util.List) */ @Override public boolean registerUser(List<Object> params) { // TODO Auto-generated method stub boolean flag = false; try { jdbcUtils.getConnection(); String sql = "insert into userinfo(username,pswd) values(?,?)"; flag = jdbcUtils.updateByPreparedStatement(sql, params); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ //关闭数据库连接 jdbcUtils.releaseConn(); } return flag; } }
12. RegisterService.java
package com.register; import java.util.List; public interface RegisterService { //完成用户注册功能 public boolean registerUser(List<Object> params); }
13. ProductAction.java
package com.product; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.ServletException; 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 com.util.DividePage; import com.util.UUIDTools; public class ProductAction extends HttpServlet { private ProductService service; /** * Constructor of the object. */ public ProductAction() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); String action_flag = request.getParameter("action_flag"); if (action_flag.equals("add")) { addProduct(request,response); }else if (action_flag.equals("search")) { listProduct(request,response); }else if (action_flag.equals("del")) { delProduct(request,response); }else if (action_flag.equals("view")) { viewProduct(request,response); } out.flush(); out.close(); } private void viewProduct(HttpServletRequest request, HttpServletResponse response) { // TODO Auto-generated method stub String proid = request.getParameter("proid"); Map<String, Object> map = service.viewProduct(proid); request.setAttribute("productMap", map); try { request.getRequestDispatcher("/viewProduct.jsp").forward(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /**批量删除产品 * @param request * @param response */ private void delProduct(HttpServletRequest request, HttpServletResponse response) { // TODO Auto-generated method stub System.out.println("进入del"); //获得复选框的值 String[] ids = request.getParameterValues("ids"); for (int i = 0; i < ids.length; i++) { System.out.println("ids["+i+"]="+ids[i]); } boolean flag = service.delProduct(ids); System.out.println("删除flag:"+flag); if (flag) { try { request.getRequestDispatcher("/main.jsp").forward(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private void listProduct(HttpServletRequest request, HttpServletResponse response) { // TODO Auto-generated method stub String productName = request.getParameter("proname"); String pageNum = request.getParameter("pageNum"); System.out.println("参数 pageNum :"+pageNum); if (productName == null) { productName = ""; } int totalRecord = service.getItemCount(productName); //获取总的记录数 int currentPage = 1; DividePage dividePage = new DividePage(5, totalRecord);//默认第一页开始 if (pageNum != null) { currentPage = Integer.parseInt(pageNum); dividePage.setCurrentPage(currentPage); } //记录从第几行开始 int start = dividePage.fromIndex(); //显示几条记录 int end = dividePage.toIndex(); System.out.println("currentPageNum :"+ dividePage.getCurrentPage() +", start = "+start +", end = "+end); List<Map<String, Object>> list = null; try { list = service.listProduct(productName , start , end); request.setAttribute("listProduct", list); request.setAttribute("dividePage", dividePage); request.setAttribute("productName",productName ); request.getRequestDispatcher("/main.jsp").forward(request, response); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } private void addProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ //表单含有文件要提交 String path = request.getContextPath(); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); servletFileUpload.setFileSizeMax(3*1024*1024);//单个文件大小限制3M servletFileUpload.setSizeMax(6*1024*1024);//上传文件总大小 List<FileItem> list = null; List<Object> params = new ArrayList<Object>(); params.add(UUIDTools.getUUID()); // 参数传 product表的主键 try { //解析request的请求 list = servletFileUpload.parseRequest(request); //取出所有表单的值,判断非文本字段和文本字段 for(FileItem fileItem : list){ if (fileItem.isFormField()) {//是文本字段 String fileItemName = fileItem.getFieldName(); //获取 <input>控件的 名称 String fileItemValue = fileItem.getString("utf-8");//获取<input>控件的值 if (fileItemName.equals("proname")) { params.add(fileItemValue); //参数传入 proname }else if (fileItemName.equals("proprice")) { params.add(fileItemValue);//参数传入 proprice }else if (fileItemName.equals("proaddress")) { params.add(fileItemValue);////参数传入 proaddress } }else{ //非文本字段 String imageName = fileItem.getName(); //获取文件名称 params.add(imageName);//参数传入 proimage //String path = request.getRealPath("/upload"); String upload_dir = request.getServletContext().getRealPath("/upload");//获取服务器端 /upload 路径 File uploadFile = new File(upload_dir+"/"+imageName); System.out.println("---upload_dir--->>"+uploadFile); fileItem.write(uploadFile); } } // 把产品加入数据库 boolean flag = service.addProduct(params); if (flag) { response.sendRedirect(path+"/main.jsp"); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here service = new ProductDao(); } }
package com.product; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.jdbc.JdbcUtils; public class ProductDao implements ProductService { private JdbcUtils jdbcUtils; public ProductDao() { // TODO Auto-generated constructor stub jdbcUtils = new JdbcUtils(); } @Override public boolean addProduct(List<Object> params) { boolean flag = false; try { jdbcUtils.getConnection(); String sql = "insert into product(proid,proname,proprice,proaddress,proimage) values(?,?,?,?,?)"; flag = jdbcUtils.updateByPreparedStatement(sql, params); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ // 关闭数据库连接 jdbcUtils.releaseConn(); } return flag; } @Override public List<Map<String, Object>> listProduct(String proname ,int start ,int end) { // TODO Auto-generated method stub List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); List<Object> params = new ArrayList<Object>(); try { jdbcUtils.getConnection(); String sql = "select * from product where 1=1 and proname like ? limit ? ,?"; if(proname.equals("")){ sql = "select * from product limit ? ,?"; params.add(start); params.add(end); }else{ params.add("%"+proname+"%"); params.add(start); params.add(end); } list = jdbcUtils.findMoreResult(sql, params); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally{ jdbcUtils.releaseConn(); } return list; } //查询总记录数 @Override public int getItemCount(String proname) { // TODO Auto-generated method stub int count = 0; Map<String, Object> map = null; List<Object> params = null; try { jdbcUtils.getConnection(); String sql = "select count(*) totalCount from product where 1=1 and proname like ?"; if(proname.equals("")){ sql = "select count(*) totalCount from product"; }else{ params = new ArrayList<Object>(); params.add("%"+proname+"%"); } map = jdbcUtils.findSimpleResult(sql, params); count = Integer.parseInt(map.get("totalCount").toString()); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally{ // 关闭数据库连接 jdbcUtils.releaseConn(); } return count; } @Override public boolean delProduct(String[] ids) { boolean flag = false; try { jdbcUtils.getConnection(); if (ids!=null) { String[] sql = new String[ids.length]; for(int i = 0 ; i< ids.length; i++){ sql[i] = "delete from product where proid = ‘"+ids[i]+"‘"; System.out.println(sql[i]); } flag = jdbcUtils.deleteByBatch(sql); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally{ // 关闭数据库连接 jdbcUtils.releaseConn(); } return flag; } @Override public Map<String, Object> viewProduct(String proid) { // TODO Auto-generated method stub Map<String, Object> map = null; try { jdbcUtils.getConnection(); List<Object> params = new ArrayList<Object>(); params.add(proid); String sql = "select * from product where proid = ?"; map = jdbcUtils.findSimpleResult(sql, params); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally{ // 关闭数据库连接 jdbcUtils.releaseConn(); } return map; } }
15. ProductService.java
package com.product; import java.util.List; import java.util.Map; public interface ProductService { public boolean addProduct(List<Object> params); //列出产品,为了分页,加上参数 start,end public List<Map<String, Object>> listProduct(String proname , int start , int end); //获取总的记录数 public int getItemCount(String proname); //批处理删除产品 public boolean delProduct(String[] ids); //查询单个产品 public Map<String, Object> viewProduct(String proid); }
16. JdbcUtils.java
package com.jdbc; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.mysql.jdbc.Driver; public class JdbcUtils { // 定义数据库的用户名 private final String USERNAME = "root"; // 定义数据库的密码 private final String PASSWORD = "123456"; // 定义数据库的驱动信息 private final String DRIVER = "com.mysql.jdbc.Driver"; // 定义访问数据库的地址 private final String URL = "jdbc:mysql://localhost:3306/mydb"; // 定义访问数据库的连接 private Connection connection; // 定义sql语句的执行对象 private PreparedStatement pstmt; // 定义查询返回的结果集合 private ResultSet resultSet; // 实现批处理的功能 private Statement stmt; public JdbcUtils() { // TODO Auto-generated constructor stub try { Class.forName(DRIVER); System.out.println("注册驱动成功!!"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block System.out.println("注册驱动失败!!"); } } // 定义获得数据库的连接 public Connection getConnection() { try { connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (Exception e) { // TODO: handle exception System.out.println("Connection exception !"); } return connection; } /** 实现批处理删除 * @param sql * @return * @throws SQLException */ public boolean deleteByBatch(String[] sql) throws SQLException{ boolean flag = false; stmt = connection.createStatement(); if (sql!=null) { //判断数组是否为空,不能用length来判断,否则可能会报空指针异常。 for(int i = 0 ; i<sql.length ; i++){ stmt.addBatch(sql[i]); } int[] count = stmt.executeBatch(); if (count!=null) { flag = true; } } return flag; } /** * 完成对数据库标的增加删除和修改的操作 * * @param sql * @param params * @return * @throws SQLException */ public boolean updateByPreparedStatement(String sql, List<Object> params) throws SQLException { boolean flag = false; int result = -1;// 表示当用户执行增加删除和修改的操作影响的行数 int index = 1; // 表示 占位符 ,从1开始 pstmt = connection.prepareStatement(sql); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); // 填充占位符 } } result = pstmt.executeUpdate(); flag = result > 0 ? true : false; return flag; } /** * 查询返回单条记录 * * @param sql * @param params * @return * @throws SQLException */ public Map<String, Object> findSimpleResult(String sql, List<Object> params) throws SQLException { Map<String, Object> map = new HashMap<String, Object>(); pstmt = connection.prepareStatement(sql); int index = 1; if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } resultSet = pstmt.executeQuery(); // 返回查询结果 ResultSetMetaData metaData = pstmt.getMetaData(); // 获取 结果中,一行所有列的结果 int cols_len = metaData.getColumnCount(); // 获得列的总数 while (resultSet.next()) { for (int i = 0; i < cols_len; i++) { String col_name = metaData.getColumnName(i + 1); // 获得第i列的字段名称 Object col_value = resultSet.getObject(col_name);// 返回 第i列的内容值 if (col_value == null) { col_value = ""; } map.put(col_name, col_value); } } return map; } /** * 查询返回多条记录 * * @param sql * @param params * @return * @throws SQLException */ public List<Map<String, Object>> findMoreResult(String sql, List<Object> params) throws SQLException { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); pstmt = connection.prepareStatement(sql); int index = 1; // 表示占位符 if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } resultSet = pstmt.executeQuery(); // 返回查询结果集合 ResultSetMetaData metaData = resultSet.getMetaData(); // 获得列的结果 while (resultSet.next()) { Map<String, Object> map = new HashMap<String, Object>(); int cols_len = metaData.getColumnCount(); // 获取总的列数 for (int i = 0; i < cols_len; i++) { String col_name = metaData.getColumnName(i + 1); // 获取第 i列的字段名称 // ,列计算从1开始 Object col_value = resultSet.getObject(col_name); // 获取第i列的内容值 if (col_value == null) { col_value = ""; } map.put(col_name, col_value); } list.add(map); } return list; } /** * 查询返回单个JavaBean(使用java反射机制) * * @param sql * @param params * @param cls * @return * @throws Exception */ public <T> T findSimpleRefResult(String sql, List<Object> params, Class<T> cls) throws Exception { T resultObject = null; int index = 1; // 占位符 pstmt = connection.prepareStatement(sql); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); // 填充占位符 } } resultSet = pstmt.executeQuery(); // 获取查询结果 ResultSetMetaData metaData = resultSet.getMetaData(); // 获取列的信息 int cols_len = metaData.getColumnCount(); // 获取总的列数 while (resultSet.next()) { // 通过反射机制创建实例 resultObject = cls.newInstance(); // java反射机制 for (int i = 0; i < cols_len; i++) { String col_name = metaData.getColumnName(i + 1); // 获取第i列的名称 Object col_value = resultSet.getObject(col_name); // 获取第i列的值 if (col_value == null) { col_value = ""; } Field field = cls.getDeclaredField(col_name); field.setAccessible(true);// 打开 JavaBean的访问 private权限 field.set(resultObject, col_value); } } return resultObject; } /** 查询返回多个JavaBean(通过java反射机制) * @param sql * @param params * @param cls * @return * @throws Exception */ public <T> List<T> findMoreRefResult(String sql, List<Object> params, Class<T> cls) throws Exception { List<T> list = new ArrayList<T>(); int index = 1; //占位符 pstmt = connection.prepareStatement(sql); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } resultSet = pstmt.executeQuery(); // 返回查询结果集合 ResultSetMetaData metaData = resultSet.getMetaData(); // 返回列的信息 int cols_len = metaData.getColumnCount(); // 结果集中总的列数 while (resultSet.next()) { // 通过反射机制创建一个java实例 T resultObject = cls.newInstance(); for (int i = 0; i < cols_len; i++) { String col_name = metaData.getColumnName(i + 1); // 获得第i列的名称 Object col_value = resultSet.getObject(col_name); // 获得第i列的内容 if (col_value == null) { col_value = ""; } Field field = cls.getDeclaredField(col_name); field.setAccessible(true); // 打开JavaBean的访问private权限 field.set(resultObject, col_value); } list.add(resultObject); } return list; } /**关闭数据库访问 * @throws SQLException */ public void releaseConn(){ if (resultSet!=null) { try { resultSet.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } if(stmt!=null){ try { stmt.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } if (pstmt!=null) { try { pstmt.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } if (connection!=null) { try { connection.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } } }
17. DividePage.java
package com.util; public class DividePage { private int pageSize ; //每一页的记录数 private int totalRecord;//总记录数 private int currentPage;//当前第几页 public DividePage(int pageSize, int totalRecord, int currentPage) { this.pageSize = pageSize; this.totalRecord = totalRecord; setCurrentPage(currentPage); } public DividePage(int pageSize, int totalRecord) { this(pageSize,totalRecord,1); } //获取总页数 public int getPageCount(){ int pageCount = totalRecord/pageSize; int mod = totalRecord%pageSize; if (mod!=0) { pageCount++; } return pageCount; } // mysql : select * from product limit 5,10 表示查询记录行 第6到15行。 //起始记录从第几行开始(mysql 记录默认从第0行开始) public int fromIndex(){ return (currentPage-1)*pageSize; } //要查询的的尾记录相对于起始记录的偏移量,即一页的记录数 public int toIndex(){ return pageSize; } public void setCurrentPage( int currentPage){ if (getPageCount()!=0) {//有记录 int validPage = currentPage<1?1:currentPage; validPage = validPage>getPageCount()?getPageCount():validPage; this.currentPage = validPage; } else{ // 0条记录 this.currentPage = 1; } } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotalRecord() { return totalRecord; } public void setTotalRecord(int totalRecord) { this.totalRecord = totalRecord; } public int getCurrentPage() { return currentPage; } }
18. UUIDTools.java
package com.util; import java.util.UUID; public class UUIDTools { public UUIDTools() { // TODO Auto-generated constructor stub } /**返回一个 6位的字符串 * @return */ public static String getUUID(){ UUID uuid = UUID.randomUUID(); return uuid.toString().replaceAll("-", "").substring(0, 6); } }
20. LogoutAction.java
package com.logout; 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; public class LogoutAction extends HttpServlet { /** * Constructor of the object. */ public LogoutAction() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String path = request.getContextPath(); String action_flag = request.getParameter("action_flag"); if (action_flag.equals("logout")) { request.getSession().removeAttribute("username"); response.sendRedirect(path+"/index.jsp"); } } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
21. web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>RegisterAction</servlet-name> <servlet-class>com.register.RegisterAction</servlet-class> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>LoginAction</servlet-name> <servlet-class>com.login.LoginAction</servlet-class> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>ProductAction</servlet-name> <servlet-class>com.product.ProductAction</servlet-class> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>LogoutAction</servlet-name> <servlet-class>com.logout.LogoutAction</servlet-class> </servlet> <servlet-mapping> <servlet-name>RegisterAction</servlet-name> <url-pattern>/servlet/RegisterAction</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>LoginAction</servlet-name> <url-pattern>/servlet/LoginAction</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ProductAction</servlet-name> <url-pattern>/servlet/ProductAction</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>LogoutAction</servlet-name> <url-pattern>/servlet/LogoutAction</url-pattern> </servlet-mapping> <!-- 配置 过滤器 --> <filter> <filter-name>MyFilter</filter-name> <filter-class>com.filter.MyFilter</filter-class> </filter> <filter-mapping> <filter-name>MyFilter</filter-name> <!-- /*表示过滤所有页面 ,/main.jsp 表示只过滤main.jsp页面--> <url-pattern> /main.jsp</url-pattern> </filter-mapping> <filter-mapping> <filter-name>MyFilter</filter-name> <!-- /*表示过滤所有页面 /addProduct.jsp 表示只过滤addProduct.jsp页面--> <url-pattern>/addProduct.jsp</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
注意:
1. 使用过滤器,要引入jar包:servlet-2_5-api.jar
2. 使用jdbc连接mysql , 要引入jar包:mysql-connector-java-5.1.7-bin.jar
3. 文件上传,要引入2个jar包:
commons-fileupload-1.3.1.jar 和
commons-io-2.4.jar