问题描述
我在使用Smartupload上传图片的时候,代码没问题,编译也没有报错,但是启动服务器,便出现了java.lang.NoClassDefFoundError:com/jspsmart/upload/SmartUploadException
这个错误表明找不到这个jar包,我明明已经将jar包导入到了项目中,却还是一直给我报错,我捣鼓了好久 终于发现了问题
可能出现该问题有两个原因,其一是没有将Smartupload的jar包构建到项目当中,其二是没有将Smartupload的jar包导入到Tomcat中。
解决办法
问题一的解决办法:将Smartupload的jar包构建到项目当中
1、点击项目的构建
2、添加相应的jar包,确定并且运用
问题二的解决办法:将Smartupload的jar包导入到Tomcat中(这个也是我的错误所在,找了好多文章都是说jar包没有导入到项目中,其实最后是jar包没有导入到Tomcat中)
找到Tomcat的文件目录,进入lib文件夹,将Smartupload的jar包复制进去,重新在项目中启动服务器就可以了
没想到这么简单,我还一直在怀疑自己用的是不是假的jar包
最后,附上Smartupload的使用代码
@WebServlet("/Manger/admin_doproductadd")
public class DoProductAdd extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置字符集
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=utf-8");
//完成数据的上传
SmartUpload su = new SmartUpload();
//初始化
su.initialize(this.getServletConfig(),request,response);
//上传
try {
su.upload();
} catch (SmartUploadException e) {
e.printStackTrace();
}
//获取上传的文件对象
Files files = su.getFiles();
//我们只上传了一个文件,所以是第一个
File file = files.getFile(0);
//获取文件名,并且存储
String fileName = file.getFileName();
String fileName1 = new String(fileName.getBytes(),"utf-8");
try {
su.save("/images/products");
} catch (SmartUploadException e) {
e.printStackTrace();
}
// System.out.println(fileName);
//获取上传的新的请求对象
Request request1 = su.getRequest();
String productName = request1.getParameter("productName");
String parentId = request1.getParameter("parentId");
String productPrice = request1.getParameter("productPrice");
String productDesc = request1.getParameter("productDesc");
String productStock = request1.getParameter("productStock");
//转码
String productName1 = new String(productName.getBytes(),"utf-8");
String parentId1 = new String(parentId.getBytes(),"utf-8");
String productPrice1 = new String(productPrice.getBytes(),"utf-8");
String productDesc1 = new String(productDesc.getBytes(),"utf-8");
String productStock1 = new String(productStock.getBytes(),"utf-8");
//System.out.println(productName1+":"+productDesc1);
//因为我们传递的id值是${CF.CATE_ID}-${CC.CATE_ID},那么我们需要用-分割
ShoppingProduct product = new ShoppingProduct(
0,
productName1,
productDesc1,
Integer.parseInt(productPrice1),
Integer.parseInt(productStock1),
Integer.parseInt(parentId1.split("-")[0]),
Integer.parseInt(parentId1.split("-")[1]),
fileName1);
int count = PRODUCTDao.insert(product);
PrintWriter out = response.getWriter();
if (count>0){
response.sendRedirect("/MyShoppingSystem/Manger/admin_productselect");
}else {
out.write("<script>");
out.write("alert('产品添加失败');");
out.write("location.href='Manger/admin_toproductadd.jsp';");
out.write("</script>");
}
}
}