本文實現一個簡單的 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="" οnclick="login()">登錄</button>
<button type="button" name="" value="" οnclick="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="" οnclick="dosubmit()" >確定</button>
<button type="button" name="" value="" οnclick="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" οnclick="searchProduct()" >查詢</button>
<button type="button" οnclick="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" οnclick="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" οnclick="javascript:del();">刪除</button>
<button type="button" οnclick="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" οnchange="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>
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" οnclick="javascript:dosubmit();">確定</button>
<button type="button" οnclick="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" οnclick="javascript:location.href='<%=path %>/main.jsp'">確定</button>
<button type="button" οnclick="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();
}
}
14.ProductDao.java
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