这个是我做的商品照片上传与在前台页面显示
JSP页面
提交表单form表单里要添加一个属性
enctype=“multipart/form-data”
首先还是要先创建一个Product类,用来保存上传商品的一些属性
思路:
1、创建对象
2、进行上传的初始化
3、SmartUplaod su = new SmartUpload();
4、设定上传文件的限制
5、调用upload方法进行上传
6、取文件 getFiles()
Files files = su.getFiles();
7、遍历集合
8、File file = files.getFile(i);
逐一读取上传文件信息,同时可以保存文件
9、savaAs(“路径”, 有三个路径可选)保存到服务器
- 物理路径physical
- 操作系统根目录virtual
- auto会自动选择,如果你的项目下有该文件夹,会优先存储在项目下的文件夹
package com.shop.bean;
public class Product {
private int id;
private String code;
private String name;
private String type;
private String brand;
private String pic;
private int num;
private int price;
private int sale;
private int status;
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getSale() {
return sale;
}
public void setSale(int sale) {
this.sale = sale;
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>商品添加</title>
<%@include file="/Management/header.jsp" %>
</head>
<body>
<div class="panel admin-panel">
<div class="panel-head" id="add"><strong><span class="icon-pencil-square-o"></span>添加商品</strong></div>
<div class="body-content">
<form method="post" class="form-x" action="<%=ctxPath %>/Management/product?action=productSubmit" enctype="multipart/form-data" >
<div class="form-group">
<div class="label">
<label>编码:</label>
</div>
<div class="field">
<input type="text" class="input w50" value="" name="code" placeholder="请输入商品编码" data-validate="required:请输入商品编码" />
<div class="tips"></div>
</div>
</div>
<div class="form-group">
<div class="label">
<label>图片:</label>
</div>
<div class="field">
<input type="file" class="input w50" value="" name="filename" />
<div class="tips"></div>
</div>
</div>
<div class="form-group">
<div class="label">
<label>名称:</label>
</div>
<div class="field">
<input type="text" class="input w50" value="" name="productname" placeholder="请输入商品名称" data-validate="required:请输入商品名称" />
<div class="tips"></div>
</div>
</div>
<div class="form-group">
<div class="label">
<label>类型:</label>
</div>
<div class="field">
<select name="protype">
<c:forEach items="${requestScope.typelists }" var="l">
<option value="${l.id }">${l.type }</option>
</c:forEach>
</select>
<!-- <input type="text" class="input w50" value="" name="protype" placeholder="请输入商品类型" data-validate="required:请输入商品类型" /> -->
<div class="tips"></div>
</div>
</div>
<div class="form-group">
<div class="label">
<label>品牌:</label>
</div>
<div class="field">
<input type="text" class="input w50" value="" name="probrand" placeholder="请输入商品品牌" data-validate="required:请输入商品品牌" />
<div class="tips"></div>
</div>
</div>
<div class="form-group">
<div class="label">
<label>数量:</label>
</div>
<div class="field">
<input type="text" class="input w50" value="" name="productnum" placeholder="请输入商品数量" data-validate="required:请输入商品的数量" />
<div class="tips"></div>
</div>
</div>
<div class="form-group">
<div class="label">
<label>单价:</label>
</div>
<div class="field">
<input type="text" class="input w50" value="" name="proprice" placeholder="请输入商品原价" data-validate="required:请输入商品原价" />
<div class="tips"></div>
</div>
</div>
<div class="form-group">
<div class="label">
<label>促销减价:</label>
</div>
<div class="field">
<input type="text" class="input w50" value="" name="prosale" placeholder="请输入商品促销减价" data-validate="required:请输入商品促销减价" />
<div class="tips"></div>
</div>
</div>
<div class="form-group">
<div class="label">
<label>状态:</label>
</div>
<div class="field">
<input type="text" class="input w50" value="" name="prostatus" placeholder="请输入商品状态" data-validate="required:请输入商品状态" />
<div class="tips"></div>
</div>
</div>
<div class="form-group">
<div class="label">
<label></label>
</div>
<div class="field">
<button class="button bg-main icon-check-square-o" type="submit"> 提交</button>
</div>
</div>
</form>
</div>
</div>
</body></html>
servlet页面
// 新建一个SmartUpload对象
SmartUpload su = new SmartUpload();
// 初始化
su.initialize(getServletConfig(), req, resp);
//设置上传文件的格式
su.setAllowedFilesList("jpg,gif,jpeg,png,dox");
//定义一个filepath变量,用来保存文件的路径
String filepath = "";
try {
// 上传文件
su.upload();
//对上传的文件进行遍历
for (int i = 0; i < su.getFiles().getCount(); i++) {
//获取文件
com.jspsmart.upload.File file2 = su.getFiles().getFile(i);
//获取文件名
filepath = file2.getFileName();
//因为上传的文件很有可能会重名,所以要定义一个UUID用来产生一个唯一的id
UUID tuid = UUID.randomUUID();
String uid = tuid.toString();
//另存为,
file2.saveAs("/upload/" + uid + filepath,SmartUpload.SAVE_AUTO);
//保存路径
filepath ="/upload/" + uid +filepath;
}
} catch (SmartUploadException e) {
e.printStackTrace();
}
//创建一个自己的request,因为在提交表单的时候使用了enctype属性,直接使用request取值会导致所取的值为null,
Request myrequest = su.getRequest();
// 下面的req都换成myrequest
String code = FileUtils.getParameter(myrequest,"code");
/* String pic = req.getParameter("filename"); */
String productname = FileUtils.getParameter(myrequest,"productname");
String protype = FileUtils.getParameter(myrequest,"protype");
String probrand = FileUtils.getParameter(myrequest,"probrand");
int pronum = Integer.parseInt(FileUtils.getParameter(myrequest,"productnum"));
/* System.out.print(pronum); */
int proprice = Integer.parseInt(FileUtils.getParameter(myrequest,"proprice"));
int prosale = Integer.parseInt(FileUtils.getParameter(myrequest,"prosale"));
int prostatus = Integer.parseInt(FileUtils.getParameter(myrequest,"prostatus"));
Product pro = new Product();
pro.setCode(code);
pro.setPic(filepath);
pro.setName(productname);
pro.setType(protype);
pro.setBrand(probrand);
pro.setNum(pronum);
pro.setPrice(proprice);
pro.setSale(prosale);
pro.setStatus(prostatus);
//pdao.exists(pro)就是判断该商品是否添加
if(pdao.exists(pro)){
pdao.productadd(pro);
req.setAttribute("products", pro);
req.getRequestDispatcher("/Management/product?action=productlist").forward(req, resp); }
else {
req.setAttribute("message", "该商品已经添加!");
req.getRequestDispatcher("/Management/productadd.jsp").forward(req, resp);
}
Dao层,因为我在连接数据库的时候做了一些优化,所以使用起来会比较方便,我在下面会把连接数据库的代码放进来,下面是主要代码
/**
* 判断商品是否存在
* @param pro
* @return
*/
public boolean exists(Product pro) {
String sql = "select * from product_info where name=?";
ResultSet rs=null;
try {
rs=denglu.executeQuery(sql, pro.getName());
if(rs.next()) {
return false;
}else {
return true;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
denglu.closeAll(rs);
}
}
/**
* 添加商品
* @param pro
*/
public int proadd(Product pro) {
String sql="insert into product_info(code,name,type,brand,num,price,sale,status) values(?,?,?,?,?,?,?,?)";
try {
return denglu.executeInsert(sql, pro.getCode(),pro.getName(),pro.getType(),pro.getBrand(),pro.getNum(),pro.getPrice(),pro.getSale(),pro.getStatus());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void productadd(Product pro) {
String sql="insert into product_info(code,pic,name,type,brand,num,price,sale,status) values(?,?,?,?,?,?,?,?,?)";
try {
denglu.executeUpdate(sql,pro.getCode(),pro.getPic(),pro.getName(),pro.getType(),pro.getBrand(),pro.getNum(),pro.getPrice(),pro.getSale(),pro.getStatus() );
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
上传成功,将图片显示到页面,使用img标签,
getAttribute(),获取上传图片的路径
连接数据库的代码
package com.java.conn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcUtils
{
/**
* 连接数据库的基本参数。均声明为final类型,即变量只可被赋值一次,且为private私有的。
*/
private final static String dbdriver = "com.mysql.jdbc.Driver";
private final static String dburl = "jdbc:mysql://localhost:3306/javaweb?seUnicode=true&characterEncoding=UTF8&useSSL=false";
private final static String dbusername = "root";
private final static String dbpassword = "root";
/**
* 这种注释是文档注释
* 一般对于整个类整个方法做说明的时候,用此注释
* 静态代码块,在创建此类的实例时执行。
* @author lenovo
*/
//这种是注释是让别人能过看懂这段代码
static
{
try
{
Class.forName(dbdriver);//加载驱动
} catch (ClassNotFoundException e)
{
throw new ExceptionInInitializerError(e);
}
}
/**
* 创建连接
* @return
* @throws SQLException
*/
public static Connection createConnection() throws SQLException
{
return DriverManager.getConnection(dburl, dbusername, dbpassword);
}
/**
* 关闭ResultSet
* @param rs
*/
public static void close(ResultSet rs)
{
if (rs != null)
{
try
{
rs.close();
} catch (SQLException e)
{
}
}
}
/**
* 关闭statement
* @param stmt
*/
public static void close(Statement stmt)
{
if (stmt != null)
{
try
{
stmt.close();
} catch (SQLException e)
{
}
}
}
/**
* 关闭connection
* @param conn
*/
public static void close(Connection conn)
{
if (conn != null)
{
try
{
conn.close();
} catch (SQLException e)
{
}
}
}
/**
* 执行除查询以外的语句
* @param sql
* @param parameters为可变长度参数,相当于数组
* @return
* @throws SQLException
*/
public static int executeUpdate(String sql, Object... parameters)
throws SQLException
{
Connection conn = null;
try
{
conn = createConnection();
return executeUpdate(conn, sql, parameters);//调用。
} finally
{
close(conn);
}
}
public static int executeUpdate(Connection conn, String sql,
Object... parameters) throws SQLException
{
PreparedStatement ps = null;
try
{
ps = conn.prepareStatement(sql);
//开始遍历
for (int i = 0; i < parameters.length; i++)
{
ps.setObject(i + 1, parameters[i]);//setObject(parm1,parm2);其中parm1为占位符的位置,parm2为对应占位符的值
}
return ps.executeUpdate();//执行SQL
} finally
{
close(ps);
}
}
/**
* 执行查询语句
* @param sql
* @param parameters
* @return
* @throws SQLException
*/
public static ResultSet executeQuery(String sql, Object... parameters)
throws SQLException
{
Connection conn = null;
try
{
conn = createConnection();
return executeQuery(conn, sql, parameters);//调用
} catch (SQLException ex)
{
close(conn);
throw ex;
}
}
public static ResultSet executeQuery(Connection conn, String sql,
Object... parameters) throws SQLException
{
PreparedStatement ps = null;
ResultSet rs = null;
try
{
ps = conn.prepareStatement(sql);
//遍历
for (int i = 0; i < parameters.length; i++)
{
ps.setObject(i + 1, parameters[i]);//给占位符传参
}
rs = ps.executeQuery();//执行SQL
return rs;
} catch (SQLException ex)
{
close(ps);
throw ex;
}
}
/**
* 关闭所有资源
* @param rs
*/
public static void closeAll(ResultSet rs)
{
if (rs == null)
{
return;
}
try
{
close(rs);
close(rs.getStatement());
close(rs.getStatement().getConnection());
} catch (SQLException e)
{
}
}
}