上传文件时表单enctype属性必须要更改为<enctype='multipart/form-data'>;采用post提交表单,元素需要有name属性;
利用第三方jar包(commons-fileupload-1.2.1.jar commons-io-1.3.2.jar )进行普通数据获取和文件上传;普通文本需要用getString("编码格式")方法获取,否则汉字会出现乱码,最开始我一直用的getString()获取,发现传到数据的数据全是乱码,查看流浪器的里面的请求和响应全是正常的,百度了半天也没找到真正的解决方法,无意间发现第三方包里面的FileItem还有一个重载的getString(String args)方法,但是不晓得参数传什么;后来发现这个getString(String args)方法会抛一个
UnsupportedEncodingException异常,英语也不好,百度单词的意思吧,什么不支持的编码异常,到此终于发现这个是设置编码的方法;
所以呢,写方法;写类;写变量;写参数时,能让人见文知意是多么重要;要是这个方法直接这样写的getString(String charset)一看就知道是设置编码格式的方法了把。
添加商品的Servlet:
package ni.jun.yang.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import ni.jun.yang.service.KindService; @WebServlet("/AddGoodsServlet") public class AddGoodsServlet extends HttpServlet { private static final long serialVersionUID = 1L; public AddGoodsServlet() { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //响应编码格式 response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); //遍历类型的集合,得到下拉框选项 List<String> list = new ArrayList<>(); String sql = "Select * from kind"; list = new KindService().select(sql); out.println("<html><head><meta charset='utf-8'><title>添加商品</title>"); out.println("</head>"); out.println("<body>"); //上传文件的提交方式 out.println("<form action='AddResultServlet' method='post' enctype='multipart/form-data'>"); out.println("<table>"); out.println("<tr>"); out.println("<td>名称:</td>"); out.println("<td><input type='text' name='mingzi'></td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td></td>"); out.println("<td><input type='file' name='filename'></td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>介绍:</td>"); out.println("<td><input type='text' name='jieshao'></td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>售价:</td>"); out.println("<td><input type='text' name='shoujia'></td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>分类:</td>"); out.println("<td>"); out.println("<select name='fenlei'>"); //遍历类型的集合,得到下拉框选项 for (int i = 0;i<list.size();i++) { out.println("<option value="+(i+1)+">"); out.println(list.get(i)); out.println("</option>"); } out.println("</select>"); out.println("</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td> </td>"); out.println("<td><input type='submit' value='添加'></td>"); out.println("</tr>"); out.println("</table>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
处理提交数据的Servlet:
package ni.jun.yang.servlet; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import ni.jun.yang.bean.Goods; import ni.jun.yang.service.GoodsService; @WebServlet("/AddResultServlet") public class AddResultServlet extends HttpServlet { private static final long serialVersionUID = 1L; public AddResultServlet() { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024*1024*5); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> fileItems = null; Goods goods = new Goods(); try { //请求数据返回FileItem类型的数组 fileItems = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } //上传的文件存放路径 String path = getServletContext().getRealPath("/image"); File f = new File(path); //没有此路径就创建 if(!f.exists()){ f.mkdirs(); } //遍历请求数据的集合进行数据的获取和文件的上传 for (FileItem x : fileItems) { try { uploading(x, goods, path); } catch (Exception e) { e.printStackTrace(); } } //普通数据存入数据库,页面跳转 if(new GoodsService().add(goods)){ request.getRequestDispatcher("success.html").forward(request, response); }else{ response.sendRedirect("lose.html"); } } /** * 数据的获取和文件上传 * @param fileItem * @param goods 待添加的商品 * @param path 上传的路径 * @throws Exception */ private void uploading (FileItem fileItem,Goods goods,String path) throws Exception{ //普通文本数据 //只能获取字符串,其他的数据需要通过包装类的方法转化得到 if(fileItem.isFormField()){ if(fileItem.getFieldName().equals("mingzi")){ //获取普通的文本数据利用getString("utf-8"),设置编码格式。否则会出现汉字乱码 goods.setName(fileItem.getString("utf-8")); }else if(fileItem.getFieldName().equals("jieshao")){ goods.setExplain(fileItem.getString("utf-8")); }else if(fileItem.getFieldName().equals("shoujia")){ //字符串转Double goods.setPrice(Double.parseDouble(fileItem.getString())); }else if(fileItem.getFieldName().equals("fenlei")){ String type = fileItem.getString(); goods.setType(Integer.parseInt(type)); } }else{ // 文件类型 String fileName = fileItem.getName(); // System.out.println(fileName); //设置上传的文件名字,利用时间返回毫秒数,保证上传的文件不重名 String path1 = new Date().getTime()+"_"+fileName; String fileName2= path+"\"+ path1; File file = new File(fileName2); //数据只存放文件名字 goods.setPhoto(path1); // System.out.println(fileName2); try { fileItem.write(file); } catch (Exception e) { e.printStackTrace(); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
效果图:
完整项目网盘地址:http://pan.baidu.com/s/1boWm05T 密码:blqh