From 4fc9728619571091b598a0f8807d14511938841f Mon Sep 17 00:00:00 2001 From: User_cyk <1020691186@qq.com> Date: Sat, 8 Jul 2023 17:51:11 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E9=A1=B9=E7=9B=AE=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hellogithub/dao/projectCategoryDao.java | 26 ++ src/com/hellogithub/dao/projectDao.java | 44 ++++ src/com/hellogithub/entity/projectEntity.java | 1 + .../hellogithub/service/projectService.java | 41 +++ .../servlet/commitProjectFileServlet.java | 249 ++++++++++++++++++ .../servlet/commitProjectServlet.java | 90 +++++++ 6 files changed, 451 insertions(+) create mode 100644 src/com/hellogithub/dao/projectCategoryDao.java create mode 100644 src/com/hellogithub/servlet/commitProjectFileServlet.java create mode 100644 src/com/hellogithub/servlet/commitProjectServlet.java diff --git a/src/com/hellogithub/dao/projectCategoryDao.java b/src/com/hellogithub/dao/projectCategoryDao.java new file mode 100644 index 0000000..652f135 --- /dev/null +++ b/src/com/hellogithub/dao/projectCategoryDao.java @@ -0,0 +1,26 @@ +package com.hellogithub.dao; + +import com.hellogithub.utils.JdbcUtils; +import org.apache.commons.dbutils.QueryRunner; + +import java.sql.Connection; +import java.sql.SQLException; + +public class projectCategoryDao { + + public int insertProject(int userId,int projectId) + { + int num ; + try { + Connection conn = JdbcUtils.getConnection(); + QueryRunner runner = new QueryRunner(); + String sql ="INSERT into project_category (userId,projectId) VALUES (?,?)"; + num = runner.update(conn, sql,userId,projectId); + conn.close(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + return num ; + } + +} diff --git a/src/com/hellogithub/dao/projectDao.java b/src/com/hellogithub/dao/projectDao.java index e7dbd9c..5a5c624 100644 --- a/src/com/hellogithub/dao/projectDao.java +++ b/src/com/hellogithub/dao/projectDao.java @@ -265,4 +265,48 @@ public class projectDao { } return num; } + + public int insertProject(int userId,String projectName,String projectUrl,String projectIco,String projectTitle,String projectDescription,String submitTime,int categoryId) + { + int num ; + try { + Connection conn = JdbcUtils.getConnection(); + QueryRunner runner = new QueryRunner(); + String sql ="INSERT into project (userId,projectName,projectUrl,projectIco,projectTitle,projectDescription,startNum,submitTime,categoryId,isValid,periodicals,lookCount) VALUES (?,?,?,?,?,?,0,?,?,1,0,0)"; + num = runner.update(conn, sql,userId,projectName,projectUrl,projectIco,projectTitle,projectDescription,submitTime,categoryId); + conn.close(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + return num ; + } + + public int updateProject(String projectName,String fileAddress) + { + int num ; + try { + Connection conn = JdbcUtils.getConnection(); + QueryRunner runner = new QueryRunner(); + String sql ="update project set fileAddress = ? where projectName = ? and isValid = 1"; + num = runner.update(conn, sql,projectName,fileAddress); + conn.close(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + return num ; + } + + public projectEntity selectProByProName(String projectName ) { + projectEntity projectEntity; + try { + Connection conn = JdbcUtils.getConnection(); + QueryRunner runner = new QueryRunner(); + String sql = "select * from project where isValid = 1 and projectName = ?"; + projectEntity = runner.query(conn, sql, new BeanHandler<>(projectEntity.class),projectName); + conn.close(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + return projectEntity; + } } diff --git a/src/com/hellogithub/entity/projectEntity.java b/src/com/hellogithub/entity/projectEntity.java index 22f5a1d..db00d92 100644 --- a/src/com/hellogithub/entity/projectEntity.java +++ b/src/com/hellogithub/entity/projectEntity.java @@ -180,4 +180,5 @@ public class projectEntity { public void setUserUri(String userUri) { this.userUri = userUri; } + } diff --git a/src/com/hellogithub/service/projectService.java b/src/com/hellogithub/service/projectService.java index 08f6f16..08a5ce1 100644 --- a/src/com/hellogithub/service/projectService.java +++ b/src/com/hellogithub/service/projectService.java @@ -7,6 +7,8 @@ import com.hellogithub.dao.*; import com.hellogithub.entity.*; import java.math.BigDecimal; +import java.text.DateFormat; +import java.text.SimpleDateFormat; import java.util.*; @@ -21,6 +23,8 @@ public class projectService { private commentDao commentDao = new commentDao(); private UserDao userDao = new UserDao(); + private projectCategoryDao projectCategoryDao = new projectCategoryDao(); + /** * 按照期刊号查询 */ @@ -234,5 +238,42 @@ public class projectService { } return JSONObject.toJSONString(projectEntityList); } + public int insertProject(String username,String projectName,String projectUrl,String projectIco,String projectTitle,String projectDescription,List categoryIdList){ + if(projectDao.selectProByProName(projectName) != null){ + return 0; + } + + String mes="success"; + int pnum; + int flag = 1 ; + DateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); + Date time = new Date(); + String submitTime = format.format(time).toString(); + int categoryId = categoryIdList.get(0); + int userId = userDao.selectIdByName(username); + for(int i=0;i集合,每一个FileItem对应一个Form表单的输入项 + + + List list = upload.parseRequest(request); + + for(FileItem item : list){ + + + //如果fileitem中封装的是普通输入项的数据 + if(item.isFormField()){ + String name = item.getFieldName(); + //解决普通输入项的数据的中文乱码问题 + String value = item.getString("UTF-8"); + //String value = new String(name.getBytes("iso8859-1"),"UTF-8"); + System.out.println(">>>>>>>>>>"+name + "=" + value); + + + }else{ + + //如果fileitem中封装的是上传文件 + //得到上传的文件名称, + String filename = item.getName(); + //filename = item.getString("UTF-8"); + //filename = new String(filename.getBytes("iso8859-1"),"UTF-8"); + System.out.println(filename); + if(filename==null || filename.trim().equals("")){ + continue; + } + //注意:不同的浏览器提交的文件名是不一样的,有些浏览器提交上来的文件名是带有路径的,如: c:\a\b\1.txt,而有些只是单纯的文件名,如:1.txt + //处理获取到的上传文件的文件名的路径部分,只保留文件名部分 + filename = filename.substring(filename.lastIndexOf(File.separator)+1); + //得到上传文件的扩展名 + String fileExtName = filename.substring(filename.lastIndexOf(".")+1); + //如果需要限制上传的文件类型,那么可以通过文件的扩展名来判断上传的文件类型是否合法 + System.out.println("上传的文件的扩展名是:"+fileExtName); + //获取item中的上传文件的输入流 + InputStream in = item.getInputStream(); + //得到文件保存的名称 + saveFilename = makeFileName(filename); + + //得到文件的保存目录 + String realSavePath = makePath(saveFilename, savePath); + System.out.print(realSavePath+"\\"+saveFilename); + //创建一个文件输出流 + FileOutputStream out = new FileOutputStream(realSavePath +File.separator+ saveFilename); + //创建一个缓冲区 + byte buffer[] = new byte[1024]; + //判断输入流中的数据是否已经读完的标识 + int len = 0; + //循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据 + while((len=in.read(buffer))>0){ + //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中 + out.write(buffer, 0, len); + } + //关闭输入流 + in.close(); + //关闭输出流 + out.close(); + //删除处理文件上传时生成的临时文件 + item.delete(); + message = "文件上传成功!"; + num = projectService.updateProject(projectName,realSavePath+"\\"+saveFilename); + + } + } + }catch (FileUploadBase.FileSizeLimitExceededException e) { + e.printStackTrace(); + setResultError("单个文件超出最大值",writer); + return; + }catch (FileUploadBase.SizeLimitExceededException e) { + e.printStackTrace(); + setResultError("上传文件的总的大小超出限制的最大值",writer); + return; + }catch (Exception e) { + message= "文件上传失败!"; + setResultError("文件上传失败",writer); + e.printStackTrace(); + } + if(num == 0) + { + setResultError("文件提交失败",writer); + } +// writer.println(saveFilename); +// setResultOK(message,writer); + } + + /** + * @Method: makeFileName + * @Description: 生成上传文件的文件名,文件名以:uuid+"_"+文件的原始名称 + * @Anthor: + * @param filename 文件的原始名称 + * @return uuid+"_"+文件的原始名称 + */ + private String makeFileName(String filename){ //2.jpg + //为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名 + return UUID.randomUUID().toString() + "_" + filename; +// return filename; + } + + /** + * 为防止一个目录下面出现太多文件,要使用hash算法打散存储 + * @Method: makePath + * @Description: + * @Anthor: + * + * @param filename 文件名,要根据文件名生成存储目录 + * @param savePath 文件存储路径 + * @return 新的存储目录 + */ + private String makePath(String filename,String savePath){ + String dir = savePath; + //File既可以代表文件也可以代表目录 + File file = new File(dir); + //如果目录不存在 + if(!file.exists()){ + //创建目录 + file.mkdirs(); + } + return dir; + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + + doGet(request, response); + } + + public void setResult(Integer code, String msg, PrintWriter writer) { + HashMap result = new HashMap<>(); + result.put("code", code); + result.put("msg", msg); + String jsonString = JSONObject.toJSONString(result); + writer.println(jsonString); + writer.close(); + } + + public void setResultError(String msg, PrintWriter writer) { + setResult(500, msg, writer); + } + + public void setResultOK(String msg, PrintWriter writer) { + setResult(200, msg, writer); + } +} diff --git a/src/com/hellogithub/servlet/commitProjectServlet.java b/src/com/hellogithub/servlet/commitProjectServlet.java new file mode 100644 index 0000000..6399ef5 --- /dev/null +++ b/src/com/hellogithub/servlet/commitProjectServlet.java @@ -0,0 +1,90 @@ +package com.hellogithub.servlet; + +import com.alibaba.fastjson.JSONObject; +import com.hellogithub.entity.userEntity; +import com.hellogithub.service.projectService; + +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 javax.servlet.http.HttpSession; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +@WebServlet("/commitProject") +public class commitProjectServlet extends HttpServlet { + private projectService projectService = new projectService(); + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + doPost(req, resp); + } + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + resp.setCharacterEncoding("UTF-8"); + resp.setContentType("text/html; charset=utf-8"); + // 设置响应头允许ajax跨域访问 + String curOrigin = req.getHeader("Origin"); + resp.setHeader("Access-Control-Allow-Origin", curOrigin == null ? "true" : curOrigin); + resp.setHeader("Access-Control-Allow-Credentials", "true"); + resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD"); + resp.setHeader("Access-Control-Max-Age", "3600"); + resp.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With"); + resp.setContentType("application/json;charset=UTF-8"); + + + HttpSession session = req.getSession(); + userEntity userEntity; + userEntity =(userEntity) session.getAttribute("user"); + PrintWriter writer = resp.getWriter(); + if(userEntity == null) + { + setResultError("用户未登录",writer); + }else{ + + String username = userEntity.getUserName(); + String projectName = req.getParameter("projectName"); + String projectIco = req.getParameter("projectIco"); + String projectUrl = req.getParameter("projectUrl"); + String projectTitle = req.getParameter("projectTitle"); + String projectDescription = req.getParameter("projectDescription"); + String [] categoryIdList = req.getParameterValues("projectDescription"); + List integers = new ArrayList<>(); + for (String s : categoryIdList) { + integers.add(Integer.parseInt(s)); + } + int flag = projectService.insertProject(username,projectName,projectUrl,projectIco,projectTitle,projectDescription,integers); + if(flag == 0) + { + setResultError("插入失败",writer); + } + else{ + setResultOK("插入成功",writer); + } + } + + + + } + + public void setResult(Integer code, String msg, PrintWriter writer) { + HashMap result = new HashMap<>(); + result.put("code", code); + result.put("msg", msg); + String jsonString = JSONObject.toJSONString(result); + writer.println(jsonString); + writer.close(); + } + + public void setResultError(String msg, PrintWriter writer) { + setResult(500, msg, writer); + } + + public void setResultOK(String msg, PrintWriter writer) { + setResult(200, msg, writer); + } +}