新增图书页封页显示
初始化监听器 package com.zhou.web.listener; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import com.zhou.web.domain.Books; import com.zhou.web.domain.Category; import com.zhou.web.domain.User; /** * InitServletContextListener 启动程序时,初始化数据 * @author 25677 * */ //使用注解的方式对监听器进行配置 @WebListener public class InitServletContextListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub } @Override public void contextInitialized(ServletContextEvent event) { //1.初始化账户列表参数 //创建一个list集合用来保存用户 List<User> userList = new ArrayList<User>(); /* * 假设管理员账号比较隐私 不允许别人创建等操作 我们现在web.xml中配置好管理员账号 * 然后再程序初始化的时候获取到保存到list集合中,根据用户登录时输入的数据进行比较 */ String account = event.getServletContext().getInitParameter("account"); String password = event.getServletContext().getInitParameter("password"); //创建User对象 并将获得的管理员输入填入其中 User user = new User(account,password); //将user对象填入userlist中 userList.add(user); //将userList存入ServletContext全局对象中 event.getServletContext().setAttribute("userList", userList); //2.初始化图书分类列表参数 //创建默认分类数据 Category category = new Category("ca0001","计算机类"); //创建集合 List<Category> categoryList = new ArrayList<Category>(); //往集合中添加数据分类 categoryList.add(category); //将集合对象categoryList存入ServletContext全局对象中 event.getServletContext().setAttribute("categoryList", categoryList); //3.初始化图书列表 Books books = new Books("book0001","Java基础","计算机类",29D,"img/g1.jpg","第一本"); //创建集合 List<Books> booksList= new ArrayList<Books>(); //往集合中添加数据分类 booksList.add(books); //将集合对象booksList存入ServletContext全局对象中 event.getServletContext().setAttribute("booksList", booksList); } }
package com.zhou.web.service; import java.util.List; import com.zhou.web.domain.Books; import com.zhou.web.domain.Category; import com.zhou.web.domain.User; /** * UserService 处理业务逻辑的接口类 * @author 25677 * */ public interface UserService { //处理登录的业务逻辑接口 public User login(List<User> listUser, User user); //处理添加分类逻辑的业务接口 public boolean JudgeCategory(List<Category> categoryList, Category category); //处理删除分类逻辑的业务接口 public void DeleteCategory(List<Category> categoryList, String categoryId); //处理添加图书逻辑的业务接口 public Boolean JudgeBooks(List<Books> booksList, Books books); }
package com.zhou.web.service.impl; import java.util.Iterator; import java.util.List; import com.zhou.web.domain.Books; import com.zhou.web.domain.Category; import com.zhou.web.domain.User; import com.zhou.web.service.UserService; /** * UserServiceImpl 处理业务逻辑接口的实现类 * @author 25677 * */ public class UserServiceImpl implements UserService { /** * 登入业务逻辑 */ @Override public User login(List<User> listUser, User user) { for(User users: listUser) { if(users.getUser().equals(user.getUser()) && users.getPassword().equals(user.getPassword())) { return users; } } return null; } /** * 处理添加分类的业务逻辑 * true 表示添加成功 */ @Override public boolean JudgeCategory(List<Category> categoryList, Category category) { //如果分类名或者分类id存在一样相同我们都认为添加失败 for(Category c: categoryList) { if(c.getId().equals(category.getId()) || c.getCategoryName().equals(category.getCategoryName())) { return false; } } //不存在相同的 则将新的分类添加到集合 categoryList.add(category); return true; } /** * 处理删除图书分类的业务逻辑 */ @Override public void DeleteCategory(List<Category> categoryList, String categoryId) { /* * for(Category category: categoryList) { * if(category.getId().equals(categoryId)) { categoryList.remove(category); } } */ Iterator<Category> iterator = categoryList.iterator(); while(iterator.hasNext()) { Category c = iterator.next(); if(c.getId().equals(categoryId)) { iterator.remove(); return; } } } /** * 处理添加图书的业务逻辑 * Boolean ture 添加成功 false 添加失败 */ @Override public Boolean JudgeBooks(List<Books> booksList, Books books) { for(Books book : booksList) { //存在相同id的图书 if(book.getBookId().equals(books.getBookId())) { return false; } } //不存在相同的图书 则添加 booksList.add(books); return true; } }
package com.zhou.web.servlet; import java.io.IOException; 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 com.zhou.web.domain.Books; import com.zhou.web.service.UserService; import com.zhou.web.service.impl.UserServiceImpl; import com.zhou.web.util.UploadBookImgUtil; /** * AddBooksServlet 添加图书的控制器 */ @WebServlet("/AddBooksServlet") public class AddBooksServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //接收数据 String bookId = request.getParameter("bookId");//图书编号 String bookName = request.getParameter("bookName");//图书名 String categoryId = request.getParameter("categoryId");//图书分类 //Double bookPrice = Double.valueOf(request.getParameter("bookPrice"));//图书价格 Double bookPrice = Double.parseDouble(request.getParameter("bookPrice"));//图书价格 //String bookPic = request.getParameter("bookPic");//图书封面路径 String remarks = request.getParameter("remarks");//图书备注 System.out.println("bookID" + bookId + " bookNmae:" + bookName + " categoryID:" + categoryId + " bookPrice: " + bookPrice + " remarks:" + remarks); //将图书封面存入到服务其中 并获取到服务器中的地址 String url = UploadBookImgUtil.uploadImg(request,response); System.out.println(url); //封装数据 Books books = new Books(bookId,bookName,categoryId,bookPrice,url,remarks); //处理数据 UserService userService = new UserServiceImpl(); //获取在初始化时存入在servletContext全局上下文中存在booksList集合 List<Books> booksList = (List<Books>) request.getServletContext().getAttribute("booksList"); //调用方法判断新添加的图书是否已经在图书集合中存在: 判断条件为图书编号不同即可 Boolean addFlag = userService.JudgeBooks(booksList,books); //显示数据 if(addFlag) { //添加成功 重定向到图书信息管理页 response.sendRedirect(request.getContextPath() + "/page/bookList.jsp"); }else{ //添加失败 //请求转发到增加图书addBook.jsp 并设置flag 提示失败 request.getRequestDispatcher("page/addBook.jsp?flag=0").forward(request,response); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.zhou.web.servlet; import java.io.IOException; 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 com.zhou.web.domain.Category; import com.zhou.web.service.UserService; import com.zhou.web.service.impl.UserServiceImpl; /** * AddCategoryServlet 添加分类的控制器 */ @WebServlet("/AddCategoryServlet") public class AddCategoryServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //接收数据 String categoryId = request.getParameter("categoryId");//图书分类ID String categoryName = request.getParameter("categoryName");//分类名称 //封装数据 Category category = new Category(categoryId,categoryName); //处理结果 UserService userService = new UserServiceImpl(); //获取当前图书分类集合categoryList List<Category> categoryList =(List<Category>) request.getServletContext().getAttribute("categoryList"); //调用方法判断是否已经有相同的分类或者分类名称 boolean flagAdd = userService.JudgeCategory(categoryList,category); //显示数据 if(flagAdd) { //添加成功 重定向到图书分类管理页面 response.sendRedirect(request.getContextPath() + "/page/categoryList.jsp"); }else { //添加失败 //设置失败标识 request.setAttribute("flag", "0"); System.out.println("失败 重复"); request.getRequestDispatcher("/page/addCategory.jsp").forward(request, response); //response.sendRedirect(request.getContextPath() + "/page/addCategory.jsp"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.zhou.web.servlet; import java.io.IOException; 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 com.zhou.web.domain.Category; import com.zhou.web.service.UserService; import com.zhou.web.service.impl.UserServiceImpl; /** * DeleteCategoryServlet 删除图书分类的控制 */ @WebServlet("/DeleteCategoryServlet") public class DeleteCategoryServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //接收数据 String categoryId = request.getParameter("categoryId"); //处理数据 UserService userService = new UserServiceImpl(); //获取图书分类列表 List<Category> categoryList = (List<Category>) request.getServletContext().getAttribute("categoryList"); //删除图书 userService.DeleteCategory(categoryList,categoryId); //显示结果 //重定向到图书分类管理页面 response.sendRedirect(request.getContextPath() + "/page/categoryList.jsp"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.zhou.web.servlet; import java.io.IOException; 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 com.zhou.web.domain.User; import com.zhou.web.service.UserService; import com.zhou.web.service.impl.UserServiceImpl; /** * LonginServlet 登入注册的判断的控制器 */ @WebServlet("/LonginServlet") public class LonginServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //接收验证码并进行校验 String verifyCode = request.getParameter("verifyCode"); //先获取session中保存的验证码的信息 String code =(String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); //equalsIgnoreCase 忽略大小写比较 if(verifyCode==null || !verifyCode.equalsIgnoreCase(code)) { request.setAttribute("msg", "验证码输入不正确!"); request.getRequestDispatcher("/login.jsp").forward(request, response); //response.sendRedirect(request.getContextPath()+"/login.jsp"); return;//结束下面的代码 } //接收用户名与密码并判断 String username = request.getParameter("username"); String password = request.getParameter("password"); //封装数据 User user = new User(username,password); //处理数据 UserService userService = new UserServiceImpl(); //.获取全局域ServletContext中用户集合 并调用业务逻辑处理接口中的方法进行判断 List<User> listUser =(List<User>) request.getServletContext().getAttribute("userList"); User existUser = userService.login(listUser, user); if(existUser == null) { request.setAttribute("msg", "用户名或密码错误!"); request.getRequestDispatcher("/login.jsp").forward(request, response); }else { //登录成功 再session设置一个标志表明用户已经登录 request.getSession().setAttribute("loginName", existUser); //重定向到首页 response.sendRedirect(request.getContextPath()+"/page/categoryList.jsp"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
47
收起
正在回答
8回答
同学你好,检查同学代码,发现同学搞混了一个知识点:
url是上传文件的具体地址,在FileOutputStream中使用,而urlPath是上传成功后的服务器图片地址,将这个urlPath地址赋值给book中的地址属性。
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
jia_蛙
2019-12-12 15:02:25
package com.zhou.web.util; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; 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 com.zhou.web.domain.Books; /** * UploadBookImg 将图片存入服务器的工具类 * @author 25677 * */ public class UploadBookImgUtil { public static Books uploadImg(HttpServletRequest request, HttpServletResponse response) throws IOException { String urlPath = "";//图片地址 Books books = new Books(); //1.创建磁盘文件项工厂 (如果我们使用空构造的话,缓存区和临时文件存放的位置都会有一个默认值) DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); //2.创建核心解析类 (构造方法需要传入一个磁盘文件项工厂) ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory); //3.解析请求对象,将请求分成几个部分FileItem文件项:其中包括普通项、文件上传项 try { List<FileItem> list = fileUpload.parseRequest(request); //4.遍历集合获得每个部分的对象 for(FileItem fileItem:list) { String name = "";//普通项的名称 String value = "";//普通项的值 //判断时普通项还是文件上传项 if(fileItem.isFormField()) { //普通项目 //获取普通项的名称 name = fileItem.getFieldName(); //获取普通项的值 value = fileItem.getString("UTF-8"); if(name.equals("bookId")) { books.setBookId(value); }else if(name.equals("bookName")) { books.setBookName(value); }else if(name.equals("categoryId")) { books.setBookCategory(value); }else if(name.equals("bookPrice")) { books.setBookPrice(Double.parseDouble(value)); }else if(name.equals("remarks")) { books.setBookNotes(value); }else if(name.equals("bookPic")) { books.setBookPath(value); } }else{ //文件上传项目 //获得文件的名称 String fileName = fileItem.getName(); //适用工具类生成唯一的文件名 String uuidFileName = UploadUtils.getUuidFileName(fileName); //获得文件的输入流 相当于获取文件具体的内容 InputStream is = fileItem.getInputStream(); //设置需要将文件写入到服务器的某个路径 //服务器内图片的地址 urlPath = request.getContextPath() + "/uploadImg/" + uuidFileName; //创建输出流与输出流进行对接: OutputStream os = new FileOutputStream(urlPath); int len = 0; byte[] b = new byte[1024]; while((len = is.read(b)) != -1) { os.write(b,0,len); } is.close(); os.close(); } } } catch (FileUploadException e) { e.printStackTrace(); } //将服务器中的图片地址重新设置 books.setBookPath(urlPath); //将图片地址返回回去 return books; } }
系统找不到指定的路径。 现在图片也上传不到服务器的这个uploadImg这个文件中了
jia_蛙
2019-12-12 12:12:51
package com.zhou.web.servlet; import java.io.IOException; 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 com.zhou.web.domain.Books; import com.zhou.web.service.UserService; import com.zhou.web.service.impl.UserServiceImpl; import com.zhou.web.util.UploadBookImgUtil; /** * AddBooksServlet 添加图书的控制器 */ @WebServlet("/AddBooksServlet") public class AddBooksServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //使用工具类接收并封装数据 Books books = UploadBookImgUtil.uploadImg(request,response); //处理数据 UserService userService = new UserServiceImpl(); //获取在初始化时存入在servletContext全局上下文中存在booksList集合 List<Books> booksList = (List<Books>) request.getServletContext().getAttribute("booksList"); //调用方法判断新添加的图书是否已经在图书集合中存在: 判断条件为图书编号不同即可 Boolean addFlag = userService.JudgeBooks(booksList,books); //显示数据 if(addFlag) { //添加成功 重定向到图书信息管理页 response.sendRedirect(request.getContextPath() + "/page/bookList.jsp"); }else{ //添加失败 //请求转发到增加图书addBook.jsp 并设置flag 提示失败 request.getRequestDispatcher("page/addBook.jsp?flag=0").forward(request,response); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.zhou.web.util; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; 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 com.zhou.web.domain.Books; /** * UploadBookImg 将图片存入服务器的工具类 * @author 25677 * */ public class UploadBookImgUtil { public static Books uploadImg(HttpServletRequest request, HttpServletResponse response) throws IOException { String url = "";//需要返回的图片地址 Books books = new Books(); //1.创建磁盘文件项工厂 (如果我们使用空构造的话,缓存区和临时文件存放的位置都会有一个默认值) DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); //2.创建核心解析类 (构造方法需要传入一个磁盘文件项工厂) ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory); //3.解析请求对象,将请求分成几个部分FileItem文件项:其中包括普通项、文件上传项 try { List<FileItem> list = fileUpload.parseRequest(request); //4.遍历集合获得每个部分的对象 for(FileItem fileItem:list) { String name = "";//普通项的名称 String value = "";//普通项的值 //判断时普通项还是文件上传项 if(fileItem.isFormField()) { //普通项目 //获取普通项的名称 name = fileItem.getFieldName(); //获取普通项的值 value = fileItem.getString("UTF-8"); if(name.equals("bookId")) { books.setBookId(value); }else if(name.equals("bookName")) { books.setBookName(value); }else if(name.equals("categoryId")) { books.setBookCategory(value); }else if(name.equals("bookPrice")) { books.setBookPrice(Double.parseDouble(value)); }else if(name.equals("remarks")) { books.setBookNotes(value); }else if(name.equals("bookPic")) { books.setBookPath(value); } }else{ //文件上传项目 //获得文件的名称 String fileName = fileItem.getName(); //适用工具类生成唯一的文件名 String uuidFileName = UploadUtils.getUuidFileName(fileName); //获得文件的输入流 相当于获取文件具体的内容 InputStream is = fileItem.getInputStream(); //设置需要将文件写入到服务器的某个路径 //表示获取到web目录下的uploadImg文件的绝对路径 String path = request.getServletContext().getRealPath("/uploadImg"); //图片地址 url = path + "\\" + uuidFileName; //创建输出流与输出流进行对接: OutputStream os = new FileOutputStream(url); int len = 0; byte[] b = new byte[1024]; while((len = is.read(b)) != -1) { os.write(b,0,len); } is.close(); os.close(); } } } catch (FileUploadException e) { e.printStackTrace(); } //将服务器中的图片地址重新设置 books.setBookPath(url); //将图片地址返回回去 return books; } }
package com.zhou.web.listener; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import com.zhou.web.domain.Books; import com.zhou.web.domain.Category; import com.zhou.web.domain.User; /** * InitServletContextListener 启动程序时,初始化数据 * @author 25677 * */ //使用注解的方式对监听器进行配置 @WebListener public class InitServletContextListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub } @Override public void contextInitialized(ServletContextEvent event) { //1.初始化账户列表参数 //创建一个list集合用来保存用户 List<User> userList = new ArrayList<User>(); /* * 假设管理员账号比较隐私 不允许别人创建等操作 我们现在web.xml中配置好管理员账号 * 然后再程序初始化的时候获取到保存到list集合中,根据用户登录时输入的数据进行比较 */ String account = event.getServletContext().getInitParameter("account"); String password = event.getServletContext().getInitParameter("password"); //创建User对象 并将获得的管理员输入填入其中 User user = new User(account,password); //将user对象填入userlist中 userList.add(user); //将userList存入ServletContext全局对象中 event.getServletContext().setAttribute("userList", userList); //2.初始化图书分类列表参数 //创建默认分类数据 Category category = new Category("ca0001","计算机类"); //创建集合 List<Category> categoryList = new ArrayList<Category>(); //往集合中添加数据分类 categoryList.add(category); //将集合对象categoryList存入ServletContext全局对象中 event.getServletContext().setAttribute("categoryList", categoryList); //3.初始化图书列表 Books books = new Books("book0001","Java基础","计算机类",29D,"img/g1.jpg","第一本"); //创建集合 List<Books> booksList= new ArrayList<Books>(); //往集合中添加数据分类 booksList.add(books); //将集合对象booksList存入ServletContext全局对象中 event.getServletContext().setAttribute("booksList", booksList); } }
老师 我修改了一下工具类,让其直接返回一books对象,boo是对象中的图片地址是tomcat中存储 图片的地址,现在tomcat的图片地址中也能显示上传的图片,但是我遇到一个问题:因为我在监听器 初始化的时候是这样初始化的: Books books = new Books("book0001","Java基础","计算机类",29D,"img/g1.jpg","第一本"); 然后再显示的bookList.jsp中是这样显示的: <img src="${pageContext.request.contextPath}/${c.bookPath}"> 但是如果我使用服务器的地址的话,我新添加的图片就显示不出来,地址会报错,我试了很久,无论 是修改监听器中的图片初始化中books中的地址的格式,还是jsp中拼接,我都失败了,麻烦老师帮 我看一下,我只修改了sevlet和工具类,我都贴出来了,其他都没修改,和之前贴出来的一样,麻烦 您了
jia_蛙
2019-12-11 18:46:44
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>登录</title> <link rel="stylesheet" href="${pageContext.request.contextPath}/css/login.css"> <script type="text/javascript"> function data_Judge(){ // 获得用户名的值 var username = document.getElementById("name").value; if(username == null || username==""){ alert("用户名不能为空"); return false; } // 获得密码的值 var password = document.getElementById("pwd").value; if(password == null || password==""){ alert("密码不能为空"); return false; } //获得验证码的值 var code = document.getElementById("code").value; var length = code.length; if(length != "5"){ alert("验证码格式有误"); return false; } } //点击更换图片函数 function changeImg(){ var codeImg = document.getElementById("codeImg"); /* 使用第三方直接获取验证码 */ codeImg.src="${pageContext.request.contextPath}/KaptchaServlet?time=" + new Date().getTime(); } </script> </head> <body> <div class="login"> <div class="header"> <h1> <a href="/login.do">登录</a> <!-- 如果登入失败 msg就会被赋值并提示错误信息 --> <p style="color:red"> ${ msg }</p> </h1> <button></button> </div> <form action="${pageContext.request.contextPath}/LonginServlet" method="post" onsubmit="return data_Judge()"> <div class="name"> <input type="text" id="name" name="username"> <p></p> </div> <div class="pwd"> <input type="password" id="pwd" name="password"> <p></p> </div> <div class="code"> <input type="text" id="code" name="verifyCode" style="width: 150px"> <img id="codeImg" onclick="changeImg()" src="${pageContext.request.contextPath}/KaptchaServlet" style="width: 150px; height: 42px; vertical-align: middle;"> <p></p> </div> <div class="btn-red"> <input type="submit" value="登录" id="login-btn"> </div> </form> </div> </body> </html>
老师 ,我在添加图书的AddBooksServlet中 把前端数据接收过来,然后再用工具类根据地址 前端穿过来的图片存入到服务器中,让后再返回一个图片再服务器的地址,然后将再sevlet中获得 的其他前端数据和其返回过来的服务器中的图片地址封装成user,当我完成这一步时,只要一点击 前端页面的添加,它就报空指针异常,我看了一下报错的信息 ,看不懂,但是只出现了一个类是我 写的AddBooksServlet.java:30)AddBooksServlet.java:63),AddBooksServlet第三十行我是我 根据前端获取的值转成double的值,我之前设置的时候都没问题。不知道问题出在哪里。麻烦老师 帮我看看
jia_蛙
2019-12-11 18:45:58
package com.zhou.web.util; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; 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; /** * UploadBookImg 将图片存入服务器的工具类 * @author 25677 * */ public class UploadBookImgUtil { public static String uploadImg(HttpServletRequest request, HttpServletResponse response) throws IOException { String url = "";//需要返回的图片地址 //1.创建磁盘文件项工厂 (如果我们使用空构造的话,缓存区和临时文件存放的位置都会有一个默认值) DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); //2.创建核心解析类 (构造方法需要传入一个磁盘文件项工厂) ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory); //3.解析请求对象,将请求分成几个部分FileItem文件项:其中包括普通项、文件上传项 try { List<FileItem> list = fileUpload.parseRequest(request); //4.遍历集合获得每个部分的对象 for(FileItem fileItem:list) { //判断时普通项还是文件上传项 if(!fileItem.isFormField()) { //文件上传项目 //获得文件的名称 String fileName = fileItem.getName(); //适用工具类生成唯一的文件名 String uuidFileName = UploadUtils.getUuidFileName(fileName); //获得文件的输入流 相当于获取文件具体的内容 InputStream is = fileItem.getInputStream(); //设置需要将文件写入到服务器的某个路径 //表示获取到web目录下的uploadImg文件的绝对路径 String path = request.getServletContext().getRealPath("/uploadImg"); //图片地址 url = path + "\\" + uuidFileName; //创建输出流与输出流进行对接: OutputStream os = new FileOutputStream(url); int len = 0; byte[] b = new byte[1024]; while((len = is.read(b)) != -1) { os.write(b,0,len); } is.close(); os.close(); } } } catch (FileUploadException e) { e.printStackTrace(); } //将图片地址返回回去 return url; } }
package com.zhou.web.util; import java.util.UUID; /** * UploadUtils 解决文件名重名的方法 * @author 25677 * */ public class UploadUtils { /** * 解决多个用户选择头像文件名重名覆盖的问题 * @param fileName 原来的文件名 * @return 新的不重名的文件名 */ public static String getUuidFileName(String fileName) { //解决文件重名的问题: //a.jpg --> 获得后缀名.jpg --> 生成一段随机字符串将a替换掉 xxfsaf.jpg //对原来文件名进行替换 //1.首先使用lastIndexOf找到 点 出现的位置 (lastIndexOf:是从右向左查某个指定的字符串在字符串中最后一次出现的位置) int ind = fileName.lastIndexOf("."); //2.根据点出现的位置开始截取 (substring() 方法用于提取字符串中介于两个指定下标之间的字符。) String exName = fileName.substring(ind); //3.生成随机字符串 //UUID 是 通用唯一识别码,作用是让每一个元素都有一个唯一辨识的信息。因为UUID会有-,如果你去掉可以使用replace替换 String uuidFileName = UUID.randomUUID().toString().replace("-", "") + exName; //4返回新生成的文件名 return uuidFileName; } //测试 /* * public static void main(String[] args) { * System.out.println(UploadUtils.getUuidFileName("a.jpg")); } */ }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!--引入JSTL标签库 prefix表示为这个JSTL核心库声明一个前缀 --> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>新建图书信息</title> <link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.min.css"> <link rel="stylesheet" href="${pageContext.request.contextPath}/css/add.css"> <% String flag = request.getParameter("flag"); %> <script type="text/javaScript"> /* 根据响应回来的flag判断图书是否已经存在 判断标志位:图书ID是否相同 */ var flag = '<%=flag%>'; if("0"==flag){ alert("该图书已存在,请更改图书ID"); } /* 表单提交的校验方法 */ function validate_form(){ /* 对图书编号进行校验 */ var bookId = document.getElementById("bookId").value; var regex1 = /^book[0-9]{4}$/; if(bookId == ""){ alert("图书编号不能为空"); return false; }else if(!regex1.test(bookId)){ alert("图书编号请满足:bookxxxx xxxx为4为数字"); return false; } /* 对书名进行校验 */ var bookName = document.getElementById("bookName").value; console.log("bookName: " + bookName); if(bookName == ""){ alert("图书名不能为空"); return false; } /* 对分类进行校验 */ var categoryId = document.getElementById("categoryId").value; if(categoryId == ""){ alert("图书分类未选中"); return false; } /* 对价格进行校验 */ var bookPrice = document.getElementById("bookPrice").value; var regex2 = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/; if(bookPrice == ""){ alert("请输入价格!"); return false; }else if(!regex2.test(bookPrice)){ alert("价格格式错误!"); return false; } /* 对图书封面进行校验 */ var bookPic = document.getElementById("bookPic").value; if(bookPic == ""){ alert("请选择图书封面"); return false; } /* 对备注进行校验 */ var remarks = document.getElementById("remarks").value; if(remarks == ""){ alert("请填写备注"); return false; } } </script> </head> <body> <nav class="navbar navbar-default"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="/dept/list.do"> 图书信息管理 </a> </div> </div> </nav> <div class="container"> <div class="jumbotron"> <h1>Hello, XXX!</h1> <p>请小心地新增图书信息,要是建了一个错误的就不好了。。。</p> </div> <div class="page-header"> <h3><small>新建</small></h3> </div> <form enctype="multipart/form-data" class="form-horizontal" onsubmit="return validate_form()" action="${pageContext.request.contextPath}/AddBooksServlet" method="post" > <div class="form-group"> <label for="name" class="col-sm-2 control-label">图书编号 :</label> <div class="col-sm-8"> <input name="bookId" class="form-control" id="bookId"> </div> </div> <div class="form-group"> <label for="name" class="col-sm-2 control-label">图书名称 :</label> <div class="col-sm-8"> <input name="bookName" class="form-control" id="bookName"> </div> </div> <div class="form-group"> <label for="categoryId" class="col-sm-2 control-label">分类 :</label> <select id="categoryId" name="categoryId" class="col-sm-2 form-control" style="width: auto;margin-left: 15px"> <c:forEach items="${applicationScope.categoryList}" var="c" varStatus="idx"> <option value='${c.categoryName}'>${c.categoryName}</option> </c:forEach> </select> </div> <div class="form-group"> <label for="name" class="col-sm-2 control-label">价格 :</label> <div class="col-sm-8"> <input name="bookPrice" class="form-control" id="bookPrice"> </div> </div> <div class="form-group" > <label for="name" class="col-sm-2 control-label">图书封面 :</label> <input type="file" id="bookPic" name="bookPic" style="padding-left: 15px"> </div> <div class="form-group"> <label for="name" class="col-sm-2 control-label">备注 :</label> <div class="col-sm-8"> <input name="remarks" class="form-control" id="remarks"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-primary">保存</button> </div> </div> </form> </div> <footer class="text-center" > copy@imooc </footer> </body> </html>
相似问题
登录后可查看更多问答,登录/注册
2. 从网页搭建入门JavaWeb
- 参与学习 人
- 提交作业 676 份
- 解答问题 9666 个
本阶段将从前端网页搭建入手,到Java Web基础,前后端结合助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星