Student management system (BS version) & file upload
1, Student management system (BS version)
1.1 environment construction
-
Create project, create package, add jar package
-
Four jsp pages
-
Home page( index.jsp)
Use the index.jsp Yes, provide a hyperlink to all student list pages
-
All students list page( list.jsp)
-
Add student page( add.jsp)
-
Modify student information page( edit.jsp)
-
1.2 query all functions
-
Process analysis
-
code implementation
index.jsp page <h2>Student management system</h2> <a href="${pageContext.request.contextPath}/findAllStudents">Query all students list</a> FindAllStudentsServlet.java @WebServlet(name = "FindAllStudentsServlet",urlPatterns = "/findAllStudents") public class FindAllStudentsServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response){ //0. Set the code of response body and request body response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); //Servlet s do four things: transfer from reference to storage //1. Get parameters (none) //2. Call service to get the information of all students StudentService service = new StudentService(); List<Student> students = service.findAllStudents(); //3. Save data to domain object request.setAttribute("students",students); //4. Forward to another jsp page request.getRequestDispatcher("/list.jsp").forward(request, response); } } StudentService.java public class StudentService { /** * How to query all students */ public List<Student> findAllStudents(){ //Call dao layer StudentDao dao = new StudentDao(); List<Student> students = dao.findAllStudents(); //return return students; } } StudentDao.java public class StudentDao { /** * How to query all students */ public List<Student> findAllStudents(){ //To actually query data from a file List<Student> students = DataUtil.readAll(); //return return students; } } DataUtil.java public class DataUtil { //Read all student information from file public static List<Student> readAll(){ //Save all student object information List<Student> stuList = new ArrayList<>(); try { //Get the real path of the file String realpath = DataUtil.class.getClassLoader().getResource("student.txt").getPath(); //Create character input stream Reader isr = new InputStreamReader(new FileInputStream(realpath), "UTF-8"); //Create character buffer stream BufferedReader br = new BufferedReader(isr); //Decorator mode //Read one line at a time String row = null; while ((row = br.readLine()) != null) {//row = "1, Zhang San, m,20" String[] arr = row.split(","); //[1, Zhang San, m,20] Student stu = new Student(); stu.setId(arr[0]); stu.setName(arr[1]); stu.setSex(arr[2]); stu.setAge(arr[3]); //Add Student objects to the collection stuList.add(stu); } br.close(); } catch (Exception e) { e.printStackTrace(); } return stuList; } } list.jsp Show all student information pages <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> <script> </script> </head> <body> <a href="">newly added</a> <table border="1" > <tr> <th>Student number</th> <th>full name</th> <th>Gender</th> <th>Age</th> <th>operation</th> </tr> <%--use jstl Of foreach Tag traversal set--%> <c:forEach items="${students}" var="s"> <tr> <td>${s.id}</td> <td>${s.name}</td> <td>${s.sex}</td> <td>${s.age}</td> <td> <a href="">modify</a>| <a href="">delete</a> </td> </tr> </c:forEach> </table> </body> </html>
1.3 new functions
-
Process analysis
-
code implementation
list.jsp page <a href="${pageContext.request.contextPath}/add.jsp">newly added</a> ${isOK} add.jsp page <body> <form action="${pageContext.request.contextPath}/addStudent" method="post"> //Student ID:<input type="text" name="id"/><br/> //full name:<input type="text" name="name"/><br/> //Gender:<input type="radio" name="sex" value="male" checked/>male <input type="radio" name="sex" value="female"/>female<br/> //Age:<input type="text" name="age"/><br/> <input type="submit" value="Submit"/> </form> </body> AddStudentServlet.java @WebServlet(name = "AllStudentServlet",urlPatterns = "/addStudent") public class AllStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response){ //0. Set the code of response body and request body response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); //Four functions of Servlet: reference, storage and transfer //1. Get request parameters Map<String, String[]> map = request.getParameterMap(); //Encapsulate to student object Student s = new Student(); //Using BeanUtils try { BeanUtils.populate(s,map); } catch (Exception e) { e.printStackTrace(); } //2. Call service StudentService service = new StudentService(); boolean b = service.addStudent(s); //3. The successful information can be saved to the domain object (or not) request.setAttribute("isOK", b?"Successfully added":"Add failed"); //4. Forward to findAllServlet request.getRequestDispatcher("/findAllStudents").forward(request, response); } } StudentService.java /** * How to add students */ public boolean addStudent(Student s){ //Call Dao StudentDao dao = new StudentDao(); boolean b = dao.addStudent(s); return b; } StudentDao.java /* * How to add students */ public boolean addStudent(Student s) { //Add new student information to the file //1. Get all students first (before adding) List<Student> students = DataUtil.readAll(); //2. Add new students to the collection students.add(s); //3. Write all students (after adding) to the file DataUtil.writeAll(students); //4. Return success return true; } DataUtil.java //Write all student information to file - overwrite public static void writeAll(List<Student> stuList) { try { //Get the real path of the file String realpath = DataUtil.class.getClassLoader().getResource("student.txt").getPath(); //Create character output stream Writer osw=new OutputStreamWriter(new FileOutputStream(realpath),"UTF-8"); //Create character buffer stream BufferedWriter out = new BufferedWriter(osw); //Loop text to file for (Student stu : stuList) { out.write(stu.getId() + "," + stu.getName() + "," + stu.getSex() + "," + stu.getAge()); out.newLine();//Create a new row } out.close(); } catch (Exception e) { e.printStackTrace(); } }
1.4 solve the whole station disorderly code
In order to solve the Chinese scrambling problem of all resources,We suggest to add a filter for the whole station's Chinese character scrambling @WebFilter(filterName = "EncodingFilter", urlPatterns = "/*") public class EncodingFilter implements Filter { /** * Destroy method: when the project is uninstalled or the server is shut down normally */ public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { //1. Turn ServletRequest and ServletResponse into HttpServletRequest and HttpServletResponse HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; //2. Scrambling of request body and response body if (request.getMethod().equalsIgnoreCase("POST")) { request.setCharacterEncoding("UTF-8"); } response.setContentType("text/html;charset=UTF-8"); //3. Release, access to target resources chain.doFilter(req, resp); } /** * Initialization method: initialize when the project is deployed to the server */ public void init(FilterConfig config) throws ServletException { } }
1.5 modification function
1.5.1 data echo
-
Process analysis
-
code implementation
list.jsp Modify button of <tr> <td>${s.id}</td> <td>${s.name}</td> <td>${s.sex}</td> <td>${s.age}</td> <td> <a href="${pageContext.request.contextPath}/findStudent?id=${s.id}">modify</a>| <a href="${pageContext.request.contextPath}/deleteStudent?id=${s.id}">delete</a> </td> </tr> FindStudentServlet.java protected void doGet(HttpServletRequest request, HttpServletResponse response){ //Four functions of Servlet: reference, storage and transfer //1. Get the parameters in the request String id = request.getParameter("id"); //2. Call Service StudentService service = new StudentService(); Student s = service.findStudent(id); //3. Save to domain object request.setAttribute("student",s); //4. Forward to edit.jsp request.getRequestDispatcher("/edit.jsp").forward(request, response); } StudentService.java /** * Query students by ID * @param id * @return */ public Student findStudent(String id) { //Call Dao StudentDao dao = new StudentDao(); Student s = dao.findStudent(id); //return return s; } StudentDao.java /** * Query students by id */ public Student findStudent(String id) { //Query the student information of the specified id from the file //1. Get all students List<Student> students = DataUtil.readAll(); //2. Query the students with the specified id for (Student student : students) { //3. Judgment if (student.getId().equals(id)) { return student; } } //3. If the loop in 2 is not found return null; } edit.jsp Data echo <form action="" method="post"> //Student ID:<input type="text" name="id" value="${student.id}" disabled/><br/> //full name:<input type="text" name="name" value="${student.name}"/><br/> //Gender:<input type="radio" name="gender" value="male" ${student.sex == "male" ? "checked":""}/>male <input type="radio" name="gender" value="female" ${student.sex == "female" ? "checked":""}/>female<br/> //Age:<input type="text" name="age" value="${student.age}"/><br/> <input type="submit" value="Submit"/> </form>
1.5.2 modification information
-
Process analysis
-
code implementation
edit.jsp Modify data page <form action="${pageContext.request.contextPath}/updateStudent" method="post"> //Student ID:<input type="hidden" name="id" value="${student.id}"/><br/> //full name:<input type="text" name="name" value="${student.name}"/><br/> //Gender:<input type="radio" name="sex" value="male" ${student.sex == "male" ? "checked":""}/>male <input type="radio" name="sex" value="female" ${student.sex == "female" ? "checked":""}/>female<br/> //Age:<input type="text" name="age" value="${student.age}"/><br/> <input type="submit" value="Submit"/> </form> UpdateStudentServlet.java protected void doGet(HttpServletRequest request, HttpServletResponse response) { //Transfer by reference //1. Get parameters Map<String, String[]> map = request.getParameterMap(); Student s = new Student(); try { BeanUtils.populate(s,map); } catch (Exception e) { e.printStackTrace(); } //2. Call service StudentService service = new StudentService(); boolean b = service.updateStudent(s); //3. Save results to domain object request.setAttribute("isOK",b?"Modification succeeded":"Modification failed"); //4. Forwarding request.getRequestDispatcher("/findAllStudents").forward(request, response); } StudentService.java /** * Revise students */ public boolean updateStudent(Student s) { //Call Dao StudentDao dao = new StudentDao(); boolean b = dao.updateStudent(s); //return return b; } StudentDao.java /** * Revise students */ public boolean updateStudent(Student s) { //Change the student information of the specified id in the file to the latest information //1. Get all students (before modification) List<Student> students = DataUtil.readAll(); //2. Modification for (Student student : students) { //judge if (student.getId().equals(s.getId())) { //modify student.setName(s.getName()); student.setAge(s.getAge()); student.setSex(s.getSex()); } } //3. Write all students (after revision) into the document DataUtil.writeAll(students); //4. Return results return true; }
1.6 delete function
-
Process analysis
-
code implementation
list.jsp <tr> <td>${s.id}</td> <td>${s.name}</td> <td>${s.sex}</td> <td>${s.age}</td> <td> <a href="">modify</a>| <a href="${pageContext.request.contextPath}/deleteStudent?id=${s.id}">delete</a> </td> </tr> DeleteStudentServlet.java protected void doGet(HttpServletRequest request, HttpServletResponse response){ //0. Set the code of response body and request body response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); //Four functions of Servlet: reference, storage and transfer //1. Get request parameters String id = request.getParameter("id"); //2. Call Service StudentService service = new StudentService(); boolean b = service.deleteStudent(id); //3. Save domain object request.setAttribute("isOK",b?"Delete function":"Delete failed"); //4. Request forwarding request.getRequestDispatcher("/findAllStudents").forward(request, response); } StudentService.java /** * Delete student by ID */ public boolean deleteStudent(String id) { //Call Dao StudentDao dao = new StudentDao(); boolean b = dao.delteStudent(id); return b; } StudentDao.java /** * How to delete students * @param id * @return */ public boolean deleteStudent(String id) { //Delete the student with the specified id in the file //1. Get all students first (before deleting) List<Student> students = DataUtil.readAll(); //2. Delete students from set students according to id for (Student student : students) { //judge if (student.getId().equals(id)) { students.remove(student); break; } } //3. Write all students (after deletion) to the file DataUtil.writeAll(students); //4. Return success return true; }
2, File upload (learn)
2.1 what is file upload
The user uploads the local files to the server through the client / browser, and saves them to the local disk of the server
2.2 three elements of file upload
Three elements of file upload with browser: a. Request method must be post b. The file label of the uploaded file must provide a name attribute c. The value of the enctype attribute of the form tag must be multipart / form data (indicating that the file upload function is required) If it is a normal form (no file needs to be uploaded), Its attribute value is enctype="application/x-www-form-urlencoded" (default) Example: <form action="..." method="post" enctype="multipart/form-data"> <input type="file" name=".."/> </form>
2.3 analysis of file upload process
-
Create a file upload page
<form action="#" method="post" enctype="multipart/form-data"> User name: < input type = "text" name = "username" > < br / > Password: < input type = "password" name = "password" > < br / > File: < input type = "file" name = "filename" > < br / > < input type = "submit" value = "submit data" > </form>
-
Click the button to upload the file (format of the uploaded data)
-
Write a Servlet to receive the data of the file upload form (with the help of Apache's commons file upload framework)
2.4 several methods of file upload
The first: Using a Commons provided by Apache- fileupload.jar Package implementation [today's presentation] [most disgusting] Second: Using the annotation method provided by servlet 3.0 to upload files is very simple Third: File upload implemented by spring MVC [the most abnormal and simple]
2.5 code implementation of file upload
First, you need to import the relevant jar package of Apache for file upload into the project: commons-fileupload-1.3.1.jar commons-io-2.6.jar
code implementation
/** * Servlet receiving file upload form */ @WebServlet(name = "FileUploadServlet",urlPatterns = "/upload") public class FileUploadServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // doPost(req,resp);//StackOverflowError doGet(req,resp); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //0. Set the code of response body and request body response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); //Using the Commons file provided by Apache- upload.jar Resolve common and file items //1. Create a factory object for a disk file item DiskFileItemFactory factory = new DiskFileItemFactory(); //2. Create the core analysis file to upload the data object ServletFileUpload servletFileUpload = new ServletFileUpload(factory); //3. Use the object of the core class to parse the data in the request try { List<FileItem> fileItems = servletFileUpload.parseRequest(request); //4. Traversal set for (FileItem fileItem : fileItems) { //5. Judge whether it is a common item or a document item if (fileItem.isFormField()) { //6. Represents common items String fieldName = fileItem.getFieldName(); String fieldValue = fileItem.getString(); System.out.println(fieldName + "=" + fieldValue); }else{ //7. Represents document items //a. Get the name of the file String fileName = fileItem.getName(); //b. Get the input stream of the file InputStream in = fileItem.getInputStream(); //8. Create a file with the same name as fileName //Note: if the uploads folder is empty, it will be deleted when it is deployed to Tomcat after compilation //Solution: //a. Put a file in the uploads folder (make sure it is not empty and will not be deleted) //b. Use the mkdir method of the File object to create the folder String realPath = getServletContext().getRealPath("/WEB-INF/uploads"); //Determine whether the folder exists File file = new File(realPath); if (!file.exists()) { file.mkdir(); } //9. Create the output stream of the file FileOutputStream fos = new FileOutputStream(realPath+"/"+fileName); //10. Copy //Copy byte by byte, byte by byte array, or use IOUtils IOUtils.copy(in, fos); //11. Release resources fos.close(); in.close(); } } } catch (FileUploadException e) { e.printStackTrace(); } } }