servlet實現商品商場項目

1.1javascript

1.建立四個包DButils reposiable service servletJPKcss

DButils包中的類jdbcutils.java 用於獲取工具類DButils工具類的DataSourcehtml

Reposiable包中的類marketBean.java 用於封裝產品的信息java

Service包中的類 insert.java  query.java  queryBach.java分別是對數據進行處理sql

servletJPK包中的類 carServlet.java marketServlet.java uploadServlet.java數據庫

2.在WebRoot下建立market文件夾 market中有img文件夾 cart.jsp,market,jsp student_index.jsp,upload.jspapache

Img文件夾,存儲圖片session

cart.jsp 購物車頁面app

market.jsp 商品頁面jsp

student_index.jsp 商品總頁面

upload.jsp 後臺上傳商品信息頁面

3用到的導入包以下圖

4數據庫信息以下圖

cart表

market表

商品的後臺首頁 upload.jsp

Upload代碼

<form action="/word4/uploadServlet" method="post" enctype="multipart/form-data"  >

序號:<input name="id"><br>

選擇圖片:<input type="file" name="file"><br>

商品描述:<input name="message"><br>

商品價格:<input name="name"><br>

<input type="submit" value="提交">

</form>

  

uploadServlet.java 封裝upload.jsp發過來的數據,代碼以下

package servletJPK;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.mchange.io.FileUtils;

import reposiable.marketBean;
import service.insert;


@WebServlet("/uploadServlet")
@MultipartConfig
public class uploadServlet extends HttpServlet
{
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
    {
        Part part = req.getPart("file");
        String id=req.getParameter("id");
        String message=req.getParameter("message");
        String name=req.getParameter("name");
        String fileName = part.getSubmittedFileName();
        marketBean m=new marketBean();
        System.out.println(fileName);
        m.setId(Integer.parseInt(id));
        m.setImg("./market/img/"+fileName);
        m.setMessage(message);
        m.setName(name);
        if(m.getImg()!=null){
        	insert in=new insert();
        	try {
				in.insertmarket(m);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        String dir = req.getServletContext().getRealPath("/market/img");
        part.write(dir+"\\"+fileName);
        System.out.println("寫入成功");
        }else
        {
        	System.out.println("寫入失敗");
        }
    }

        
    

    private static final long serialVersionUID = 1L;
}

  

1.3數據庫查詢信息以下student_index.js頁面圖

Cart.jsp購物車頁面圖

代碼整合

jdbcutils.java類代碼

package DButils;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;

public class jdbcutils
{
	private static ComboPooledDataSource ds = new ComboPooledDataSource();
    public jdbcutils()
    {
    }

    public static Connection getConnection()
        throws SQLException
    {
        return ds.getConnection();
    }

    public static DataSource getDataSource()
    {
        return ds;
    }
}

  

marketBean.java類代碼

package reposiable;


public class marketBean
{
	private int id;
    private String img;
    private String message;
    private String name;
    public marketBean()
    {
    }

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    public String getImg()
    {
        return img;
    }

    public void setImg(String img)
    {
        this.img = img;
    }

    public String getMessage()
    {
        return message;
    }

    public void setMessage(String message)
    {
        this.message = message;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String toString()
    {
        return (new StringBuilder("marketBean [id=")).append(id).append(", img=").append(img).append(", message=").append(message).append(", name=").append(name).append("]").toString();
    }
}

  

insert.java 代碼

package service;

import DButils.jdbcutils;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import reposiable.marketBean;

public class insert
{

    public insert()
    {
    }

    public int insertcart(marketBean m)
        throws SQLException
    {
        QueryRunner runner = new QueryRunner(jdbcutils.getDataSource());
        String sql = "insert into cart values(?,?,?,?)";
        int i = runner.update(sql, new Object[] {
            Integer.valueOf(m.getId()), m.getImg(), m.getMessage(), m.getName()
        });
        return i;
    }
    public int insertmarket(marketBean m)
            throws SQLException
        {
            QueryRunner runner = new QueryRunner(jdbcutils.getDataSource());
            String sql = "insert into market values(?,?,?,?)";
            int i = runner.update(sql, new Object[] {
                Integer.valueOf(m.getId()), m.getImg(), m.getMessage(), m.getName()
            });
            return i;
        }
}

  

query.java代碼

package service;

import DButils.jdbcutils;
import java.io.PrintStream;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import reposiable.marketBean;

public class query
{

    public query()
    {
    }

    public marketBean query(int id)
        throws SQLException
    {
        QueryRunner runner = new QueryRunner(jdbcutils.getDataSource());
        String sql = (new StringBuilder("select * from market where id=")).append(id).toString();
        marketBean m = (marketBean)runner.query(sql, new BeanHandler(marketBean.class));
        System.out.println(m);
        return m;
    }
}

  

queryBach.java代碼

package service;

import DButils.jdbcutils;
import java.io.PrintStream;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import reposiable.marketBean;

public class queryBach
{

    public queryBach()
    {
    }

    public List query()
        throws Exception
    {
        QueryRunner runner = new QueryRunner(jdbcutils.getDataSource());
        String sql = "select * from market";
        List list = (List)runner.query(sql, new BeanListHandler(marketBean.class));
        System.out.println(list);
        return list;
    }

    public List query1()
        throws Exception
    {
        QueryRunner runner = new QueryRunner(jdbcutils.getDataSource());
        String sql = "select * from cart";
        List list = (List)runner.query(sql, new BeanListHandler(marketBean.class));
        System.out.println(list);
        return list;
    }
}

  

carServlet.java,代碼

package service;

import DButils.jdbcutils;
import java.io.PrintStream;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import reposiable.marketBean;

public class queryBach
{

    public queryBach()
    {
    }

    public List query()
        throws Exception
    {
        QueryRunner runner = new QueryRunner(jdbcutils.getDataSource());
        String sql = "select * from market";
        List list = (List)runner.query(sql, new BeanListHandler(marketBean.class));
        System.out.println(list);
        return list;
    }

    public List query1()
        throws Exception
    {
        QueryRunner runner = new QueryRunner(jdbcutils.getDataSource());
        String sql = "select * from cart";
        List list = (List)runner.query(sql, new BeanListHandler(marketBean.class));
        System.out.println(list);
        return list;
    }
}

  

marketServlet.java代碼

package servletJPK;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import service.queryBach;
@WebServlet("/marketServlet")
public class marketServlet extends HttpServlet
{

    public marketServlet()
    {
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        List list = new ArrayList();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        queryBach m = new queryBach();
        try
        {
            list = m.query();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        HttpSession session = request.getSession();
        if(session.getAttribute("list") == null)
        {
            session.setAttribute("list", list);
            out.print(session.getAttribute("list"));
        }
        RequestDispatcher rd = request.getRequestDispatcher("/market/student_index.jsp");
        rd.forward(request, response);
    }
}

  

uploadServlet.java代碼

package servletJPK;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.mchange.io.FileUtils;

import reposiable.marketBean;
import service.insert;


@WebServlet("/uploadServlet")
@MultipartConfig
public class uploadServlet extends HttpServlet
{
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
    {
        Part part = req.getPart("file");
        String id=req.getParameter("id");
        String message=req.getParameter("message");
        String name=req.getParameter("name");
        String fileName = part.getSubmittedFileName();
        marketBean m=new marketBean();
        System.out.println(fileName);
        m.setId(Integer.parseInt(id));
        m.setImg("./market/img/"+fileName);
        m.setMessage(message);
        m.setName(name);
        if(m.getImg()!=null){
        	insert in=new insert();
        	try {
				in.insertmarket(m);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        String dir = req.getServletContext().getRealPath("/market/img");
        part.write(dir+"\\"+fileName);
        System.out.println("寫入成功");
        }else
        {
        	System.out.println("寫入失敗");
        }
    }

        
    

    private static final long serialVersionUID = 1L;
}

  

cart.jsp 購物車頁面代碼

<%@page import="reposiable.*" %>
<%@ 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>My JSP 'cart.jsp' starting page</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>"undefined"==typeof CODE_LIVE&&(!function(e){var t={nonSecure:"60188",secure:"60194"},c={nonSecure:"http://",secure:"https://"},r={nonSecure:"127.0.0.1",secure:"gapdebug.local.genuitec.com"},n="https:"===window.location.protocol?"secure":"nonSecure";script=e.createElement("script"),script.type="text/javascript",script.async=!0,script.src=c[n]+r[n]+":"+t[n]+"/codelive-assets/bundle.js",e.getElementsByTagName("head")[0].appendChild(script)}(document),CODE_LIVE=!0);</script></head>
  <% List<marketBean> list=(List<marketBean>)session.getAttribute("lm"); %>
  <body data-genuitec-lp-enabled="false" data-genuitec-file-id="wc2-0" data-genuitec-path="/word3/WebRoot/cart.jsp">
  <%for(marketBean m:list){%>
   <div style="float:left; margin-left:40px; margin-top: 20px; width:210px;height: 360px;" data-genuitec-lp-enabled="false" data-genuitec-file-id="wc2-0" data-genuitec-path="/word3/WebRoot/cart.jsp">
   <div ><img src="<%=m.getImg()%>"style="width:200px;" ></div>
   <div style="color: red;"><%=m.getName()%></div>
   <div><%=m.getMessage()%></div>
   </div>
   <%} %>
   
  </body>
</html>

  

market.jsp 商品頁面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="reposiable.*" %>
<%
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>My JSP 'market..jsp' starting page</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>"undefined"==typeof CODE_LIVE&&(!function(e){var t={nonSecure:"60188",secure:"60194"},c={nonSecure:"http://",secure:"https://"},r={nonSecure:"127.0.0.1",secure:"gapdebug.local.genuitec.com"},n="https:"===window.location.protocol?"secure":"nonSecure";script=e.createElement("script"),script.type="text/javascript",script.async=!0,script.src=c[n]+r[n]+":"+t[n]+"/codelive-assets/bundle.js",e.getElementsByTagName("head")[0].appendChild(script)}(document),CODE_LIVE=!0);</script></head>
 <% List<marketBean> list=(List<marketBean>)session.getAttribute("list"); %>
  <body data-genuitec-lp-enabled="false" data-genuitec-file-id="wc2-2" data-genuitec-path="/word3/WebRoot/market.jsp">
  <%for(marketBean m:list){%>
   <div style="float:left; margin-left:40px; margin-top: 20px; width:210px;height: 360px;" data-genuitec-lp-enabled="false" data-genuitec-file-id="wc2-2" data-genuitec-path="/word3/WebRoot/market.jsp">
   <div ><img src="<%=m.getImg()%>"style="width:200px;" ></div>
   <div style="color: red;"><%=m.getName()%></div>
   <div><%=m.getMessage()%></div>
   <%session.setAttribute("id", m.getId()); %>
   <form action="/word4/cartServlet" >
   <input type="hidden" name="id" value="<%=m.getId()%>" >
   <input type="submit" value="加入購物車" style="margin: 0 auto;">
   </form>
   </div>
  <% } %>
  
  </body>
</html>

  

student_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>My JSP 'student_index.jsp' starting page</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>"undefined"==typeof CODE_LIVE&&(!function(e){var t={nonSecure:"60188",secure:"60194"},c={nonSecure:"http://",secure:"https://"},r={nonSecure:"127.0.0.1",secure:"gapdebug.local.genuitec.com"},n="https:"===window.location.protocol?"secure":"nonSecure";script=e.createElement("script"),script.type="text/javascript",script.async=!0,script.src=c[n]+r[n]+":"+t[n]+"/codelive-assets/bundle.js",e.getElementsByTagName("head")[0].appendChild(script)}(document),CODE_LIVE=!0);</script></head>
  
  <body style="list-style-type:none;" data-genuitec-lp-enabled="false" data-genuitec-file-id="wc2-3" data-genuitec-path="/word3/WebRoot/student_index.jsp">
  <div class="all" style="width:1000px;height:100%;margin: auto;" data-genuitec-lp-enabled="false" data-genuitec-file-id="wc2-3" data-genuitec-path="/word3/WebRoot/student_index.jsp">
    <div class="top" style="width:998px;height:200px;float:left;border:1px solid;"><img  src="./market/img/top.jpg" style="width:998;height:200px;"></div>
    <div class="left"style="width:200px;height:797px;float:left;border:1px solid;">
    <ul >
    <li >
    <a href="/word4/market/marketServlet" style="color:black;">蔬菜商場</a>
    </li>
    <li><a href="/word4/market/cart.jsp" style="color:black;">購物車</a>
    </li>
    <li>
       <a href="#" style="color:black;">限時搶購</a>
    </li>
    </ul>
    </div>
    <div class="content" style="width:796px;height:1000px;float:left;border:1px solid;">
    <jsp:include page="market.jsp"></jsp:include>
    </div>
    </div>
  </body>
</html>

  

upload.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>My JSP 'upload.jsp' starting page</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>"undefined"==typeof CODE_LIVE&&(!function(e){var t={nonSecure:"60188",secure:"60194"},c={nonSecure:"http://",secure:"https://"},r={nonSecure:"127.0.0.1",secure:"gapdebug.local.genuitec.com"},n="https:"===window.location.protocol?"secure":"nonSecure";script=e.createElement("script"),script.type="text/javascript",script.async=!0,script.src=c[n]+r[n]+":"+t[n]+"/codelive-assets/bundle.js",e.getElementsByTagName("head")[0].appendChild(script)}(document),CODE_LIVE=!0);</script></head>
  
  <body data-genuitec-lp-enabled="false" data-genuitec-file-id="wc2-4" data-genuitec-path="/word3/WebRoot/upload.jsp">
    <form action="/word4/uploadServlet" method="post" enctype="multipart/form-data"  data-genuitec-lp-enabled="false" data-genuitec-file-id="wc2-4" data-genuitec-path="/word3/WebRoot/upload.jsp">
    序號:<input name="id"><br>
  選擇圖片:<input type="file" name="file"><br>
  商品描述:<input name="message"><br>
  商品價格:<input name="name"><br>
  <input type="submit" value="提交">
    </form>
  </body>
</html>
相關文章
相關標籤/搜索