简易的java上传商品的程序

来源:互联网 发布:无人机付费软件 编辑:程序博客网 时间:2024/05/04 14:36

建表(在数据库中建一个存放用户数据的表)

create table goods(

            `id` int auto_increment primary key,

             `name`  varchar(50),

             `price` double,

             `count` int,

             `desc` varchar(1000)

       );

建包

•model

    •Goods

•dao

     •DAO(I)
•db
 •dao.impl
    •GoodsDAOImpl
•Service
     •GoodsService(I)
•service.impl
     •GoodsServiceImpl
•Servlet
    •GoodsServlet
•Filter
   •CharactorFilter
•listener
•util
 建类开始往里面填内容(根据所需要调用的方法写里面的内容)
Goods里面的内容

package com.phome.model;
/**
 * 商品实体类
 * @author Administrator
 *
 */
public class Goods {


private int id;
private String name;
private Double price;
private int count;
private String desc;
public Goods() {
super();
// TODO Auto-generated constructor stub
}
public Goods(int id, String name, Double price, int count, String desc) {
super();
this.id = id;
this.name = name;
this.price = price;
this.count = count;
this.desc = desc;
}
public Goods(String name, Double price, int count, String desc) {
super();
this.name = name;
this.price = price;
this.count = count;
this.desc = desc;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}

}

db里面的内容 
package com.phome.db;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


/**
 * 获取关闭连接
 * @author Administrator
 *
 */
public class ConnectionManager {


//加载驱动
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//获取连接
public static Connection getConn() throws SQLException{
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/pxhome","root","root");
return conn;
}
//关闭连接
public static void free(Connection conn){
try {
if(conn!=null&&!conn.isClosed()){
conn.close();
conn=null;
}
} catch (SQLException e) {
System.err.println("数据库关闭失败");
}
}
}


package com.phome.db;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


/**
 * 执行sql语句的类
 * @author Administrator
 *
 */
public class DBHelper {


private ResultSet rs;
private String sql;
private PreparedStatement pstat;

//私有的赋值方法
private void setParameters(Object...objects) throws SQLException{
if(objects!=null&&objects.length>0){
for (int i = 0; i < objects.length; i++) {
pstat.setObject(i+1, objects[i]);
}
}
}
//增、删、改的方法
public int executeSQL(Connection conn,String sql,Object...objects) throws SQLException{
//构建预编译对象
pstat=conn.prepareStatement(sql);
setParameters(objects);
int rows=pstat.executeUpdate();
return rows;
}
//查询的方法
public ResultSet executeQuery(Connection conn,String sql,Object...objects) throws SQLException{
pstat=conn.prepareStatement(sql);
setParameters(objects);
rs=pstat.executeQuery();
return rs;
}
//增 返回新增数据的id主键
public int executeInsertReturnId(Connection conn,String sql,Object...objects) throws SQLException{
pstat=conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
setParameters(objects);
int rows=pstat.executeUpdate();
//把数据库中
rs=pstat.getGeneratedKeys();
while(rs.next()){
return rs.getInt(1);
}
return -1;
}
}

超级接口DAO
package com.phome.dao;


import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;


import com.phome.util.FindType;


/**
 * 超级接口
 * @author Administrator
 *
 */
public interface DAO<T> {


int add(Connection conn,T t)throws SQLException;
int delete(Connection conn,int id)throws SQLException;
int update(Connection conn,T t)throws SQLException;
List<T> findAll(Connection conn)throws SQLException;
T findById(Connection conn,int id)throws SQLException;
List<T> findByCondition(Connection conn,FindType type,Object...objects);
}

dao实现类
package com.phome.dao.impl;


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


import com.phome.dao.DAO;
import com.phome.db.DBHelper;
import com.phome.mapper.impl.GoodsMapperImpl;
import com.phome.model.Goods;
import com.phome.util.FindType;


/**
 * 
 * @author Administrator
 *
 */
public class GoodsDAO implements DAO<Goods>{


private String sql;
private ResultSet rs;
private DBHelper dh=new DBHelper();
@Override
public int add(Connection conn, Goods goods) throws SQLException {
sql="insert into goods(name,price,count,`desc`) values(?,?,?,?)";
return dh.executeInsertReturnId(conn, sql, goods.getName(),goods.getPrice(),goods.getCount(),goods.getDesc());
}


@Override
public int delete(Connection conn, int id) throws SQLException {
// TODO Auto-generated method stub
return 0;
}


@Override
public int update(Connection conn, Goods t) throws SQLException {
// TODO Auto-generated method stub
return 0;
}


@Override
public List<Goods> findAll(Connection conn) throws SQLException {
// TODO Auto-generated method stub
return null;
}


@Override
public Goods findById(Connection conn, int id) throws SQLException {
sql="select * from goods where id=?";
rs=dh.executeQuery(conn, sql, id);
while(rs.next()){
return new GoodsMapperImpl().rowMapper(rs);
}
return null;
}


@Override
public List<Goods> findByCondition(Connection conn, FindType type,
Object... objects) {
// TODO Auto-generated method stub
return null;
}


}

业务层
package com.phome.service;


import com.phome.model.Goods;


/**
 * 商品服务类
 * @author Administrator
 *
 */
public interface GoodsService {


int addGoods(Goods goods);
Goods findGoodsById(int id);
}

业务层实现类
package com.phome.service.impl;


import java.sql.Connection;
import java.sql.SQLException;


import com.phome.dao.DAO;
import com.phome.dao.impl.GoodsDAO;
import com.phome.db.ConnectionManager;
import com.phome.model.Goods;
import com.phome.service.GoodsService;


public class GoodsServiceImpl implements GoodsService{


private DAO<Goods> gdao=new GoodsDAO();
private Connection conn;
@Override
public int addGoods(Goods goods) {
try {
//获取连接
conn=ConnectionManager.getConn();
return gdao.add(conn, goods);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//关闭连接
ConnectionManager.free(conn);
}
return -1;
}


@Override
public Goods findGoodsById(int id) {
try {
conn=ConnectionManager.getConn();
return gdao.findById(conn, id);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
ConnectionManager.free(conn);
}
return null;
}
}

处理数据库与java之间的映射

package com.phome.mapper;


import java.sql.ResultSet;
import java.sql.SQLException;


public interface RowMapper<T> {


T rowMapper(ResultSet rs)throws SQLException;
}

处理映射实体类

package com.phome.mapper.impl;


import java.sql.ResultSet;
import java.sql.SQLException;


import com.phome.mapper.RowMapper;
import com.phome.model.Goods;


public class GoodsMapperImpl implements RowMapper<Goods>{


@Override
public Goods rowMapper(ResultSet rs) throws SQLException {

Goods goods=new Goods();
goods.setId(rs.getInt("id"));
goods.setName(rs.getString("name"));
goods.setPrice(rs.getDouble("price"));
goods.setCount(rs.getInt("count"));
goods.setDesc(rs.getString("desc"));
return goods;
}



}

servlet页面数据的接收以及方法的掉用

package com.phome.servlet;


import java.io.IOException;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.phome.model.Goods;
import com.phome.service.GoodsService;
import com.phome.service.impl.GoodsServiceImpl;


public class GoodsServlet extends HttpServlet{


private GoodsService gs=new GoodsServiceImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {


this.doPost(req, resp);
}


@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//根据获取请求中的执行的不同功能进行分发
String method=req.getParameter("method");
System.out.println(method+"----------------------------");
if("add".equals(method)){
add(req,resp);
}else if("delete".equals(method)){
delete(req,resp);
}else if("update".equals(method)){
update(req,resp);
}else if("find".equals(method)){
find(req,resp);
}
}
//增加通道
public void add(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//获取页面数据
String name=req.getParameter("goodsname");
String price=req.getParameter("goodsprice");
String count=req.getParameter("goodscount");
String desc=req.getParameter("goodsdesc");
//创建一个商品对象
Goods goods=new Goods(name,Double.parseDouble(price),Integer.parseInt(count),desc);
//调用业务处理方法,上架商品
int id=gs.addGoods(goods);
if(id==-1){
resp.sendRedirect("failed.jsp");
}else{
//根据id获取数据库中的商品
goods=gs.findGoodsById(id);
//将其存放到request空间中
req.setAttribute("currentGoods", goods);
//请求转发
req.getRequestDispatcher("success.jsp").forward(req, resp);
}
}
//删除
public void delete(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

}
//修改
public void update(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

}
//查找
public void find(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

}
}

简易的三个页面

addgoods.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 '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">
-->
  </head>
  
  <body>
    <form method="post" action="${pageContext.request.contextPath}/goods.action?method=add">
        <h1>新增商品</h1>
    <h2>商品名称</h2><input type="text" name="goodsname" />
    <h2>商品单价</h2><input type="text" name="goodsprice" />
    <h2>商品总数</h2><input type="text" name="goodscount" />
    <h2>商品描述</h2><input type="text" name="goodsdesc" />
    <br />
    <input type="submit" value="增加商品"/>
    </form>
  </body>
</html>

添加成功跳转页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
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 'success.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">
-->


  </head>
  
  <body>
  <c:set var="goods" value="${requestScope.currentGoods}"></c:set>
  <h2>商品添加成功</h2>
   <h1>新增商品信息</h1>
    <h2>商品名称:${goods.name }</h2>
    <h2>商品单价:${goods.price }</h2>
    <h2>商品总数:${goods.count }</h2>
    <h2>商品描述:${goods.desc }</h2>
  </body>
</html>

添加失败跳转界面

<%@ 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 'fail.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">
-->


  </head>
  
  <body>
    <h1>上传商品失败</h1>
  </body>
</html>

filter过滤器------处理数库接收数据以及页面的乱码问题

package com.phome.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;


/**
 * 编码过滤器
 * @author Administrator
 *
 */
public class CharacterFilter implements Filter{


@Override
public void destroy() {
// TODO Auto-generated method stub

}


@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
req.setCharacterEncoding("UTF-8");
// resp.setCharacterEncoding("GB18030");
resp.setContentType("text/html;charset=utf-8");

chain.doFilter(req, resp);
}


@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub

}


}


filter和sevlet的配置

<!-- 编码过滤器 -->
  <filter>
    <filter-name>charestfilter</filter-name>
    <filter-class>com.phome.filter.CharacterFilter</filter-class>
  </filter>
  <filter-mapping>
     <filter-name>charestfilter</filter-name>
     <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!-- 商品控制器配置 -->
  <servlet>
     <servlet-name>addgoods</servlet-name>
     <servlet-class>com.phome.servlet.GoodsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
     <servlet-name>addgoods</servlet-name>
     <url-pattern>/goods.action</url-pattern>
  </servlet-mapping>

最后就是不要忘记到驱动哦

0 0
原创粉丝点击