各位web高手们,本人用struts做了一个文件上传,但是有些奇怪的问题,希望大家来交流下!!!!!
1、这是上传工具类
package com.nt.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Random;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.upload.FormFile;
public class FileUtil
{
/***************************************************************************
* 创建空白文件
*
* @param fileName
* 文件名
*
* @param dir
* 保存文件的目录
*
* @return
*/
private static File createNewFile(String fileName, String dir)
{
File dirs = new File(dir);
// 看文件夹是否存在,如果不存在新建目录
if (!dirs.exists())
dirs.mkdirs();
// 拼凑文件完成路径
File file = new File(dir + File.separator + fileName);
try {
// 判断是否有同名名字,如果有同名文件加随机数改变文件名
while (file.exists()) {
int ran = getRandomNumber();
String prefix = getFileNamePrefix(fileName);
String suffix = getFileNameSuffix(fileName);
String name = prefix + ran + "." + suffix;
file = new File(dir + File.separator + name);
}
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
/**
*
* 获得随机数
*
* @return
*/
private static int getRandomNumber() {
Random random = new Random(new Date().getTime());
return Math.abs(random.nextInt());
}
/**
*
* 分割文件名 如a.txt 返回 a
*
* @param fileName
*
* @return
*/
private static String getFileNamePrefix(String fileName) {
int dot = fileName.lastIndexOf(".");
return fileName.substring(0, dot);
}
/**
*
* 获得文件后缀
*
* @param fileName
*
* @return
*/
private static String getFileNameSuffix(String fileName) {
int dot = fileName.lastIndexOf(".");
return fileName.substring(dot + 1);
}
/**
*
* 上传文件
*
* @param file
*
* @param dir
*
* @return
*/
public static String uploadFile(FormFile file, String dir)
{
// 获得文件名
String fileName = file.getFileName();
InputStream in = null;
OutputStream out = null;
File f = null;
try
{
in = new BufferedInputStream(file.getInputStream());// 构造输入流
f = createNewFile(fileName, dir);
out = new BufferedOutputStream(new FileOutputStream(f));// 构造文件输出流
byte[] buffered = new byte[8192];// 读入缓存
int size = 0;// 一次读到的真实大小
while ((size = in.read(buffered, 0, 8192)) != -1)
{
out.write(buffered, 0, size);
}
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally
{
try {
if (in != null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (out != null)
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return f.getPath();
}
/** request对象 */
private HttpServletRequest request = null;
/** 上传文件的路径 */
private String uploadPath = null;
/**
* 每次读取得字节的大小
*
* @原值 1024 * 8
* @修改时间 2009-5-6
*
*/
private static int BUFSIZE = 1024 * 8 * 1024;
/** 存储参数的Hashtable */
private Hashtable paramHt = new Hashtable();
/** 存储上传的文件的文件名的ArrayList */
private ArrayList updFileArr = new ArrayList();
/**
* 设定request对象。
*
* @param request
* HttpServletRequest request对象
*/
public void setRequest(HttpServletRequest request) {
this.request = request;
}
/**
* 设定文件上传路径。
*
* @param path
* 用户指定的文件的上传路径。
*/
public void setUploadPath(String path) {
this.uploadPath = path;
}
/**
* 文件上传处理主程序。�������B
*
* @return int 操作结果 0 文件操作成功;1 request对象不存在。 2 没有设定文件保存路径或者文件保存路径不正确;3
* 没有设定正确的enctype;4 文件操作异常。
*/
public int process() {
int status = 0;
// 文件上传前,对request对象,上传路径以及enctype进行check。
status = preCheck();
// 出错的时候返回错误代码。
if (status != 0)
return status;
try {
// ��参数或者文件名�u��
String name = null;
// 参数的value
String value = null;
// 读取的流是否为文件的标志位
boolean fileFlag = false;
// 要存储的文件。
File tmpFile = null;
// 上传的文件的名字
String fName = null;
FileOutputStream baos = null;
BufferedOutputStream bos = null;
// ��存储参数的Hashtable
paramHt = new Hashtable();
updFileArr = new ArrayList();
int rtnPos = 0;
byte[] buffs = new byte[BUFSIZE * 8];
// �取得ContentType
String contentType = request.getContentType();
int index = contentType.indexOf("boundary=");
String boundary = "--" + contentType.substring(index + 9);
String endBoundary = boundary + "--";
// �从request对象中取得流。
ServletInputStream sis = request.getInputStream();
// 读取1行
while ((rtnPos = sis.readLine(buffs, 0, buffs.length)) != -1) {
String strBuff = new String(buffs, 0, rtnPos);
// 读取1行数据�n��
if (strBuff.startsWith(boundary)) {
if (name != null && name.trim().length() > 0) {
if (fileFlag) {
bos.flush();
baos.close();
bos.close();
baos = null;
bos = null;
updFileArr.add(fName);
} else {
Object obj = paramHt.get(name);
ArrayList al = new ArrayList();
if (obj != null) {
al = (ArrayList) obj;
}
al.add(value);
System.out.println(value);
paramHt.put(name, al);
}
}
name = new String();
value = new String();
fileFlag = false;
fName = new String();
rtnPos = sis.readLine(buffs, 0, buffs.length);
if (rtnPos != -1) {
strBuff = new String(buffs, 0, rtnPos);
if (strBuff.toLowerCase().startsWith(
"content-disposition: form-data; ")) {
int nIndex = strBuff.toLowerCase().indexOf(
"name=/"");
int nLastIndex = strBuff.toLowerCase().indexOf(
"/"", nIndex + 6);
name = strBuff.substring(nIndex + 6, nLastIndex);
}
int fIndex = strBuff.toLowerCase().indexOf(
"filename=/"");
if (fIndex != -1) {
fileFlag = true;
int fLastIndex = strBuff.toLowerCase().indexOf(
"/"", fIndex + 10);
fName = strBuff.substring(fIndex + 10, fLastIndex);
fName = getFileName(fName);
if (fName == null || fName.trim().length() == 0) {
fileFlag = false;
sis.readLine(buffs, 0, buffs.length);
sis.readLine(buffs, 0, buffs.length);
sis.readLine(buffs, 0, buffs.length);
continue;
} else {
fName = getFileNameByTime(fName);
sis.readLine(buffs, 0, buffs.length);
sis.readLine(buffs, 0, buffs.length);
}
}
}
} else if (strBuff.startsWith(endBoundary)) {
if (name != null && name.trim().length() > 0) {
if (fileFlag) {
bos.flush();
baos.close();
bos.close();
baos = null;
bos = null;
updFileArr.add(fName);
} else {
Object obj = paramHt.get(name);
ArrayList al = new ArrayList();
if (obj != null) {
al = (ArrayList) obj;
}
al.add(value);
paramHt.put(name, al);
}
}
} else {
if (fileFlag) {
if (baos == null && bos == null) {
tmpFile = new File(uploadPath + fName);
baos = new FileOutputStream(tmpFile);
bos = new BufferedOutputStream(baos);
}
bos.write(buffs, 0, rtnPos);
baos.flush();
} else {
System.out.println("test :" + value + "--" + strBuff);
value = value + strBuff;
}
}
}
} catch (IOException e) {
status = 4;
}
return status;
}
private int preCheck() {
int errCode = 0;
if (request == null)
return 1;
if (uploadPath == null || uploadPath.trim().length() == 0)
return 2;
else {
File tmpF = new File(uploadPath);
if (!tmpF.exists())
return 2;
}
String contentType = request.getContentType();
if (contentType.indexOf("multipart/form-data") == -1)
return 3;
return errCode;
}
public String getParameter(String name) {
String value = "";
if (name == null || name.trim().length() == 0)
return value;
value = (paramHt.get(name) == null) ? ""
: (String) ((ArrayList) paramHt.get(name)).get(0);
return value;
}
public String[] getParameters(String name) {
if (name == null || name.trim().length() == 0)
return null;
if (paramHt.get(name) == null)
return null;
ArrayList al = (ArrayList) paramHt.get(name);
String[] strArr = new String[al.size()];
for (int i = 0; i < al.size(); i++)
strArr[i] = (String) al.get(i);
return strArr;
}
public int getUpdFileSize() {
return updFileArr.size();
}
public String[] getUpdFileNames() {
String[] strArr = new String[updFileArr.size()];
for (int i = 0; i < updFileArr.size(); i++)
strArr[i] = (String) updFileArr.get(i);
return strArr;
}
private String getFileName(String input) {
int fIndex = input.lastIndexOf("//");
if (fIndex == -1) {
fIndex = input.lastIndexOf("/");
if (fIndex == -1) {
return input;
}
}
input = input.substring(fIndex + 1);
return input;
}
private String getFileNameByTime(String input) {
int index = input.indexOf(".");
Date dt = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
return input.substring(0, index) + sdf.format(dt)
+ input.substring(index);
}
}
2、发布商品的 ActionForm
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.nt.struts.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.upload.FormFile;
import org.apache.struts.upload.MultipartRequestHandler;
import org.apache.struts.validator.ValidatorForm;
import com.nt.biz.ICafeInfoBiz;
import com.nt.biz.impl.CafeInfoBizImpl;
import com.nt.entity.Goods;
/**
* MyEclipse Struts Creation date: 04-27-2009
*
* XDoclet definition:
*
* @struts.form name="goodsForm"
*/
public class GoodsForm extends ValidatorForm {
private Goods goods = new Goods();
private ICafeInfoBiz biz = new CafeInfoBizImpl();
private FormFile imageFile;
/*
* Generated Methods
*/
public FormFile getImageFile() {
return imageFile;
}
public void setImageFile(FormFile imageFile) {
this.imageFile = imageFile;
}
public Goods getGoods() {
return goods;
}
public void setGoods(Goods goods) {
this.goods = goods;
}
/**
* 验证文件名后缀是否合格
*
* @param fileName
* @return
*/
private boolean validateStuffix(String fileName) {
boolean flag = true;
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
suffix = suffix.toUpperCase();
System.out.println(suffix);
String[] sysSuffix = { "JPG", "BMP", "GIF", "PNG" };
int i = 0;
for (; i < sysSuffix.length; i++) {
if (suffix.trim().equals(sysSuffix[i])) {
break;
}
}
if (i == sysSuffix.length) {
flag = false;
}
return flag;
}
/**
* Method validate
*
* @param mapping
* @param request
* @return ActionErrors
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (this.goods.getGoods() == null || this.goods.getGoods().equals("")) {
errors.add("goodsNameNotNull", new ActionMessage(
"error.validate.goodsName"));
}
if (this.goods.getPrice() == null
|| this.goods.getPrice().floatValue() == 0) {
errors.add("goodsPriceNotNull", new ActionMessage(
"error.validate.goodsPrice"));
}
if (this.imageFile == null) {
errors.add("goodsPictureNotNull", new ActionMessage(
"error.validate.goodsPicture"));
} else {
String fileName = this.imageFile.getFileName();
if (!this.validateStuffix(fileName)) {
errors.add("goodsPictureError", new ActionMessage(
"error.validate.goodsPictureError"));
}
}
if (this.goods.getRate() == null
|| this.goods.getRate().intValue() == 0) {
errors.add("goodsRateNotNull", new ActionMessage(
"error.validate.goodsRate"));
}
if (this.goods.getGoodsMs() == null
|| this.goods.getGoodsMs().equals("")) {
errors.add("goodsMsNotNull", new ActionMessage(
"error.validate.goodsMs"));
}
if (errors.size() == 0) {
// System.out.println("GoodsForm中 文件是否满足最大值:"+maxLengthExceeded);
// // 初始化
// try {
// // this.goods.setCafeInfo(biz.searchByDomain(request
// // .getServerName()));
//
// /*
// * 测试时间 2009-5-6 设置文件大小 若无很可能造成上传失败
// */
//
// // this.getImageFile().setFileSize(200 * 1024 * 1024);
// FormFile ff = (FormFile) this.getImageFile();
// if (ff != null) {
// String filepath = "d://upload//";
// String fileName = FileUtil.uploadFile(ff, filepath);
// System.out.println(fileName);
// this.getGoods().setPic(fileName);
// this.getGoods().setGoodsTime(new java.util.Date());
// this.getGoods().setIp(request.getRemoteAddr());
// this.goods.setState(0);
// }
// } catch (Exception e) {
// }
}
return errors;
}
/**
* Method reset
*
* @param mapping
* @param request
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
// TODO Auto-generated method stub
}
}
3、发布商品的Action
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.nt.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;
import org.hibernate.Transaction;
import com.nt.biz.ICafeInfoBiz;
import com.nt.biz.IGoodsBiz;
import com.nt.biz.impl.CafeInfoBizImpl;
import com.nt.biz.impl.GoodsBizImpl;
import com.nt.dao.HibernateBaseDAO;
import com.nt.entity.CafeInfo;
import com.nt.struts.form.GoodsForm;
import com.nt.util.FileUtil;
import com.nt.util.Page;
/**
* MyEclipse Struts Creation date: 04-27-2009
*
* XDoclet definition:
*
* @struts.action path="/issueGoods" name="goodsForm"
* input="/goods/issue_goods.jsp" scope="request" validate="true"
*/
public class IssueGoodsAction extends Action {
private IGoodsBiz biz = new GoodsBizImpl();
private ICafeInfoBiz cafeBiz = new CafeInfoBizImpl();
/**
* Method execute
*
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
GoodsForm goodsForm = (GoodsForm) form;// TODO Auto-generated method
FormFile ff = (FormFile) goodsForm.getImageFile();
if (ff != null) {
String filepath = "d://upload//";
String fileName = FileUtil.uploadFile(ff, filepath);
System.out.println(fileName);
goodsForm.getGoods().setPic(fileName);
goodsForm.getGoods().setGoodsTime(new java.util.Date());
goodsForm.getGoods().setIp(request.getRemoteAddr());
goodsForm.getGoods().setState(0);
}
Transaction tx = null;
String strMapping = "goodsManage";
ActionMessages messages = new ActionMessages();
messages.add("uploadSucess", new ActionMessage("uploadSucess",
"uploadSucess"));
CafeInfo cafe = null;
Page page = null;
try {
if (request.getSession().getAttribute("cafe") == null) {
cafe = cafeBiz.searchByDomain(request.getServerName());
System.out
.println("IssueGoodsAction中测试 没有session 网吧门户商品数量:"
+ cafe.getGoodses().size());
} else {
cafe = (CafeInfo) request.getSession(false)
.getAttribute("cafe");
System.out
.println("IssueGoodsAction中测试 有session 网吧门户商品数量:"
+ cafe.getGoodses().size());
}
} catch (Exception e) {
System.out.println("IssueGoodsAction中测试 产生异常 : 网吧门户商品数量:"
+ cafe.getGoodses().size());
cafe = cafeBiz.searchByDomain(request.getServerName());
}
if (request.getSession().getAttribute("divPage") == null) {
page = new Page();
page.setRecordNum(10);
page.setThisPageNum(1);
page.setSet(cafe.getGoodses());
} else {
page = (Page) request.getSession(false).getAttribute("divPage");
}
goodsForm.getGoods().setCafeInfo(cafe);
try {
tx = new HibernateBaseDAO().getSession().beginTransaction();
System.out.println("在IssueGoodsAction中 事务开启成功");
biz.issueGoods(goodsForm.getGoods());
System.out.println("执行biz 插入成功");
page.getAllRecords().add(goodsForm.getGoods());
System.out.println("设置page成功");
cafe.setGoodses(page.getAllRecords());
System.out.println("设置网吧门户成功");
/*
* 成功提示
*/
// messages.add("saveSucess", new ActionMessage("saveSucess",
// "saveSucess"));
tx.commit();
System.out.println("事务提交成功");
} catch (Exception e) {
System.out.println("异常事务回滚");
System.out.println("域名" + request.getServerName());
tx.rollback();
}
request.getSession().setAttribute("divPage", page);
request.getSession().setAttribute("cafe", cafe);
this.saveMessages(request, messages);
return mapping.findForward(strMapping);
}
}
4、商品业务 GoodsBiz
package com.nt.biz.impl;
import java.util.HashSet;
import java.util.Set;
import com.nt.biz.IGoodsBiz;
import com.nt.dao.GoodsDAO;
import com.nt.entity.CafeInfo;
import com.nt.entity.Goods;
/**
* @业务类名 :com.nt.biz.GoodsBizImpl
* @author 成都南亭网络
* @version 1.0
* @作用:实现业务接口 IGoodsBiz(商品业务接口)
* @创建日期 2009-4-24
* @最终修改日期:2009-4-25
*/
public class GoodsBizImpl implements IGoodsBiz {
private GoodsDAO dao = new GoodsDAO();
/**
* 发布商品,即插入商品信息
*/
public void issueGoods(Goods goods) {
this.dao.save(goods);
}
/**
* 通过已经查到的网吧查询 商品
*/
@SuppressWarnings("unchecked")
public Set<Goods> searchByCafe(CafeInfo cafe) {
Set<Goods> goodsSet = cafe.getGoodses();
if (goodsSet == null) {
return new HashSet<Goods>();
} else {
return goodsSet;
}
}
public void update(Goods goods) {
this.dao.attachDirty(goods);
}
public void delete(Goods goods) {
this.dao.delete(goods);
}
}
5、商品数据库处理 GoodsDAO
package com.nt.dao;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import com.nt.entity.Goods;
/**
* A data access object (DAO) providing persistence and search support for Goods
* entities. Transaction control of the save(), update() and delete() operations
* can directly support Spring container-managed transactions or they can be
* augmented to handle user-managed Spring transactions. Each of these methods
* provides additional information for how to configure it for the desired type
* of transaction control.
*
* @类名: com.nt.dao.GoodsDAO
* @author 成都南亭网络
* @编写日期: 2009-4-24
* @最终修改日期 2009-4-24
*/
public class GoodsDAO extends HibernateBaseDAO {
private static final Log log = LogFactory.getLog(GoodsDAO.class);
// property constants
public static final String GOODS = "goods";
public static final String PRICE = "price";
public static final String GOODS_MS = "goodsMs";
public static final String PIC = "pic";
public static final String RATE = "rate";
public static final String STATE = "state";
public static final String IP = "ip";
public void save(Goods transientInstance) {
log.debug("saving Goods instance");
try {
Session session = super.getSession();
System.out.println("GoodsDAO 中session 打开状态" + session.isOpen());
session.save(transientInstance);
System.out.println("GoodsDAO中 数据插入成功");
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
System.out.println("GoodsDAO中 数据插入时 异常");
System.out.println(re.getLocalizedMessage());
throw re;
}
}
public void delete(Goods persistentInstance) {
log.debug("deleting Goods instance");
try {
getSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public Goods findById(java.lang.Long id) {
log.debug("getting Goods instance with id: " + id);
try {
Goods instance = (Goods) getSession()
.get("com.nt.entity.Goods", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findByExample(Goods instance) {
log.debug("finding Goods instance by example");
try {
List results = getSession().createCriteria("com.nt.entity.Goods")
.add(Example.create(instance)).list();
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
public List findByProperty(String propertyName, Object value) {
log.debug("finding Goods instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from Goods as model where model."
+ propertyName + "= ?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
public List findByGoods(Object goods) {
return findByProperty(GOODS, goods);
}
public List findByPrice(Object price) {
return findByProperty(PRICE, price);
}
public List findByGoodsMs(Object goodsMs) {
return findByProperty(GOODS_MS, goodsMs);
}
public List findByPic(Object pic) {
return findByProperty(PIC, pic);
}
public List findByRate(Object rate) {
return findByProperty(RATE, rate);
}
public List findByState(Object state) {
return findByProperty(STATE, state);
}
public List findByIp(Object ip) {
return findByProperty(IP, ip);
}
public List findAll() {
log.debug("finding all Goods instances");
try {
String queryString = "from Goods";
Query queryObject = getSession().createQuery(queryString);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public Goods merge(Goods detachedInstance) {
log.debug("merging Goods instance");
try {
Goods result = (Goods) getSession().merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(Goods instance) {
log.debug("attaching dirty Goods instance");
try {
getSession().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(Goods instance) {
log.debug("attaching clean Goods instance");
try {
getSession().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
}
6、 struts 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
<form-beans>
<form-bean name="goodsForm" type="com.nt.struts.form.GoodsForm" />
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings>
<action attribute="goodsForm" input="/goods/issue_goods.jsp"
name="goodsForm" path="/issueGoods" scope="request"
type="com.nt.struts.action.IssueGoodsAction">
<forward name="issueAgain" path="/goods/issue_goods.jsp" />
<forward name="issueError" path="/goods/issue_goods.jsp" />
<forward name="goodsManage"
path="/goodsManage.do?operate=toGoodsManageList" redirect="true" />
</action>
</action-mappings>
<controller maxFileSize="200*1024*1204" inputForward="true" />
<message-resources parameter="com.nt.struts.ApplicationResources" />
</struts-config>
7、web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet>
<servlet-name>ValidateToolServlet</servlet-name>
<servlet-class>
com.nt.servlet.ValidateToolServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ValidateToolServlet</servlet-name>
<url-pattern>/validate/image</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>com.nt.servlet.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
8、jsp页面 ---商品发布页面
<%@ page contentType="text/html; charset=gb2312" language="java"
import="java.sql.*" errorPage=""%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<html:form method="post" action="issueGoods"
enctype="multipart/form-data">
<table width="500" border="0" align="center" cellpadding="5"
cellspacing="1">
<tr>
<td width="130" align="center">
商品名称:
</td>
<td width="350">
<label>
<input type="text" name="goods.goods" id="textfield">
<html:errors property="goodsNameNotNull" />
</label>
</td>
</tr>
<tr>
<td align="center">
商品单价:
</td>
<td>
<input type="text" name="goods.price" id="textfield2">
元
<html:errors property="goodsPriceNotNull" />
</td>
</tr>
<tr>
<td align="center">
图片上传:
</td>
<td>
<html:file property="imageFile"></html:file>
<html:errors property="goodsPictureNotNull" />
<html:errors property="goodsPictureError" />
<html:messages id="message" message="true" property="saveSucess">
<bean:message key="saveSucess" />
</html:messages>
</td>
</tr>
<tr>
<td align="center">
商品等级:
</td>
<td>
<input type="text" name="goods.rate" id="textfield4">
<html:errors property="goodsRateNotNull" />
</td>
</tr>
<tr>
<td align="center">
商品描述:
</td>
<td>
<textarea name="goods.goodsMs" cols="50" rows="7" id="textfield5"></textarea>
<html:errors property="goodsMsNotNull" />
</td>
</tr>
</table>
<table width="500" border="0" align="center" cellpadding="5"
cellspacing="1">
<tr>
<td align="center">
<label>
<input type="submit" name="button" id="button" value="发布商品">
<input type="reset" name="button2" id="button2" value="重置信息">
<a href="goodsManage.do?operate=toGoodsManageList"> 商品管理</a>
</label>
</td>
</tr>
</table>
</html:form>
9 、我上传文件时可以成功实现,但是又出现了一个新问题:
(1、我的虚拟机要访问我的服务器时,只能上传两次图片,发布第三次就出错
(2、局域网访问时,只能上传一次图片,发布第二次就出错
(3、但在本地上传文件无数次,无比大都Ok,奇怪的是如果局域网访问产生异常后连带本机上传也会产生异常
请大家来看看很微妙的哦,一起交流java web 技术