servlet实现商品商场项目

1.1

1.创建四个包DButils reposiable service servletJPK

DButils包中的类jdbcutils.java 用于获取工具类DButils工具类的DataSource

Reposiable包中的类marketBean.java 用于封装产品的信息

Service包中的类 insert.java  query.java  queryBach.java分别是对数据进行处理

servletJPK包中的类 carServlet.java marketServlet.java uploadServlet.java

2.在WebRoot下创建market文件夹 market中有img文件夹 cart.jsp,market,jsp student_index.jsp,upload.jsp

Img文件夹,存储图片

cart.jsp 购物车页面

market.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>

  

posted @ 2019-04-23 13:04  Upower  阅读(755)  评论(0编辑  收藏  举报