The examples in this article share with you the method of making Java albums for your reference. The specific content is as follows
Note:
1) The image on html is specified statically. When new images are updated, they must be updated manually. So use Servlet to read all images in local images and display them dynamically to the user.
2) If there is a picture with a Chinese name, it will cause an error because the get method cannot directly pass on Chinese.
Main page index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>Little Album</title> </head> <body> <!-- http://localhost:8080/photosWeb/ --> <h2>Little Album</h2> <a href="jsps/upload.jsp">Upload Photo</a> <a href="<%=request.getContextPath() %>/servlet/showAllImg">Browse photos</a> </body></html>
Page display:
Upload image function:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>Little Album</title> </head> <body> <h2>Little Album</h2> <form action="<%=request.getContextPath() %>/servlet/uploadServlet" method="post" enctype="multipart/form-data"> Photo: <input type="file" name="file"/><br/> Description:<input type="text" name="desc"/><br/> <input type="submit" value="upload"/> </form> </body></html>
package cn.hncu.servlet;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.util.List;import javax.servlet.RequestDispatcher;import javax.servlet.Servlet.ServletException;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 org.apache.commons.io.FileUtils;import cn.hncu.dao.PhotoDaoImpl;import cn.hncu.domain.PhotoModel;import cn.hncu.utils.MyUtils;public class UploadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.println(" <BODY>"); out.println(" <BODY>"); out.println(" <BODY>"); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>Upload photo page</TITLE></HEAD>"); out.println(" <BODY>"); //Extract information from the upload form: 1. Encapsulate it into a photo value object, call the dao layer to store it in the background// 2. Store the uploaded photos to the server hard disk// Database: store the information about the storage of the photos,,, the real file is stored to the hard disk DiskFileItemFactory dfi=new DiskFileItemFactory(); File file=new File("d:/a"); if(file.exists()){ file.mkdirs(); } dfi.setRepository(file); ServletFileUpload upload=new ServletFileUpload(dfi); upload.setSizeMax(1024*1024*8); upload.setHeaderEncoding("utf-8");//==>request.setCharacterEncoding("utf-8"); try { List<FileItem> list=upload.parseRequest(request); PhotoModel pm=new PhotoModel(); InputStream in=null; for(FileItem fI:list){ if(fI.isFormField()){//This will not have temporary file String desc=fI.getString("utf-8"); pm.setDesc(desc); }else{ in=fI.getInputStream();// String filename=fI.getFieldName();// System.out.println("getFieldName:"+filename); String fileName=fI.getName();// System.out.println("getName:"+fileName);// Test: C:/Users/adl1/Pictures/Saved Pictures/111.jpg? //Default conditions if(fileName==null||fileName.trim().equals("No file selected,,,,, must select a file...<br/>"); String strPath2=request.getContextPath()+"/jsps/upload.jsp"; out.println("<a href=/""+strPath2+"/">Return to upload page</a>"); return; } pm.setDt(MyUtils.getCurrentDataime()); String realName=fileName.substring(fileName.lastIndexOf("//"));//"/112.jpg" System.out.println(realName.substring(1, realName.length())); pm.setRealName(realName.substring(1, realName.length()));// Remove the "/" of realName//ext extension String ext=fileName.substring(fileName.lastIndexOf(".")); pm.setExt(ext); String id=MyUtils.getUUID(); pm.setId(id); pm.setIp(request.getRemoteAddr()); pm.setDir(MyUtils.getDir(id)); } } // Complete the encapsulation of the photo value object, call dao for storage boolean boo=new PhotoDaoImpl().sava(pm); if(boo){ // Complete the storage of the database, next is the storage of the server hard disk// Store the photos in the photos folder in the root directory of the project (stored in a broken way) String path="photos/"+pm.getDir();// System.out.println("path:"+path);// Test:photos/9/0 String filePath=getServletContext().getRealPath(path);// System.out.println("filePath:"+filePath);// Test:D:/apache-tomcat-7.0.30/webapps/photosWeb/photos/9/0 File dir=new File(filePath); if(!dir.exists()){ dir.mkdirs(); } FileUtils.copyInputStreamToFile(in, new File(filePath+"/"+pm.getId()+pm.getExt()));// //If the hard disk is saved successfully, jump to the main page - Forward /// RequestDispatcher rd=request.getRequestDispatcher(getServletContext().getContextPath()+"/index.jsp");//"/photosWeb/photosWeb/index.jsp"// RequestDispatcher rd=request.getRequestDispatcher("/index.jsp");//"/photosWeb/index.jsp"g// // The start of the url in the java code block and web.xml represents the project root directory // rd.forward(request, response); //Forwarding cannot be used here. The specific difference between redirection and forwarding: http://blog.csdn.net/xanlv/article/details/52701085 //Redirect response.sendRedirect(getServletContext().getContextPath()+"/index.jsp"); }else{ //Database saving failed--stay on the upload page RequestDispatcher rd=request.getRequestDispatcher("/jsps/upload..jsp");//"/photosWeb/index.jsp" rd.forward(request, response); } } catch (FileUploadException e) { throw new RuntimeException("Upload failed", e); } finally{//Clear temporary file File f=new File("d:/a"); File fs[]=f.listFiles(); for(File ff:fs){ ff.delete(); } } out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); }} Page display effect:
Browse image function:
package cn.hncu.servlet;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import cn.hncu.dao.PhotoDaoImpl;import cn.hncu.domain.PhotoModel;public class ShowAllImgServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>Album Browse</TITLE></HEAD>"); out.println(" <BODY>"); String strPath=request.getContextPath()+"/jsps/upload.jsp"; out.println("<a href=/""+strPath+"/">Return to upload page</a>");//String table="<table border='1px' width='100%' cellpacing='0' align='center'>"+//This method cannot be set to center horizontally String table="<table border='1px' width='100%' cellpacing='0' style='text-align: center;'>"+ "<tr><th>File name</th><th>Upload date and time</th><th>Photo</th><th>Photo description</th><th>Operation</th></tr>"; out.println(table); //Read all photo information from the dao layer and send it to the front-end page List<PhotoModel> list=new PhotoDaoImpl().getAllPhotos(); for(PhotoModel pm:list){ out.println("<tr>"); out.println("<td width=80>"+pm.getRealName()); out.println("</td>"); out.println("<td width=120>"+pm.getDt()); out.println("</td>"); String path=request.getContextPath()+"/photos/"+pm.getDir()+"/"+pm.getId()+pm.getExt();//System.out.println(path);//"/photosWeb/photos/d/7/e78e18352b42410f85dbd8df834bd718.jpg" //Click on the image to view the larger image out.println("<td width=100><a href='"+path+"'><img width=100 height=100 src='"+path+"'//"); out.println("</td>"); out.println("<td width=200>"+pm.getDesc()); out.println("</td>"); out.println("<td width=80><a href='"+getServletContext().getContextPath()+"/servlet/delPhoto?id="+pm.getId()+"'>Delete the picture</a>");//out.println("<a href='<%=request.getContextPath()%>/servlet/down?id="+pm.getId()+"'>Download the picture</a></td>"); out.println("<br/><a href='"+getServletContext().getContextPath()+"/servlet/down?id="+pm.getId()+"'>Download the picture</a></td>"); out.println("</tr>"); } out.println("</table>"); out.println("</BODY>"); out.println("</HTML>"); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print("Not supported Post method. . . "); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); }} Page display effect:
Delete function:
package cn.hncu.servlet;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import cn.hncu.dao.PhotoDaoImpl;import cn.hncu.domain.PhotoModel;public class DelPhotoServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>Delete photo page</TITLE></HEAD>"); out.println(" <BODY>"); String id=request.getParameter("id"); String ip=request.getRemoteAddr(); PhotoDaoImpl dao=new PhotoDaoImpl(); PhotoModel pm=dao.getSingleById(id); if(pm!=null){ if(!pm.getIp().equals(ip)){ out.println("You do not have permission to delete the image..."); String strPath=request.getContextPath()+"/servlet/showAllImg"; out.println("<br/><a href=/""+strPath+"/">Return to continue browsing</a>"); return ; } //Delete contains two parts of work: clearing the information in the database and deleting the image files in the server hard disk//1 Clearing the information in the database boolean boo = dao.del(id); //2 Deleting the image files in the server hard disk if(boo){ String path="photos/"+pm.getDir()+"/"+pm.getId()+pm.getExt(); String filePath=getServletContext().getRealPath(path); File f=new File(filePath); if(f.exists()){ f.delete(); } String strPath=request.getContextPath()+"/servlet/showAllImg";// System.out.println(strPath);///photosWeb/servlet/showPhotos out.println("Delete Successfully...<br/><a href=/""+strPath+"/">Return to browse</a>"); }else{ out.println("Delete Database Information Failed"); } }else{ out.println("File does not exist..."); String strPath=request.getContextPath()+"/servlet/showAllImg"; out.println("<br/><a href=/""+strPath+"/">Return to continue browsing</a>"); } out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>Delete photo page</TITLE></HEAD>"); out.println(" <BODY>"); out.print("No POST method supported..."); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); }}Page display:
Download function:
1. Use hyperconnection on the HTML page to point to the file to be downloaded (unsafe and easily stolen).
question:
How to determine local resources?
ServletContext represents a web project. A web project has only one ServletContext object.
getRealPath("/"); //d:/prm/tom/web/
Requirements Analysis:
In actual development, which file to download is dynamically selected by the user.
For example, in our project images directory, there are many image files. The user displays all pictures on the page, and the user can click the download link to download the favorite pictures.
Detailed design:
Use a static web page to display all images. Give each image a downloaded hyperlink.
Pass the image id to download after the hyperconnection.
Dynamically receive image names in the service. Complete the download.
package cn.hncu.servlet;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintWriter;import java.net.URLEncoder;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.io.FileUtils;import cn.hncu.dao.PhotoDaoImpl;import cn.hncu.domain.PhotoModel;public class DownServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get the information of the downloaded image Tring id=request.getParameter("id"); PhotoModel pm=new PhotoDaoImpl().getSingleById(id); if(pm==null){ response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); response.getWriter().println("alert('This text no longer exists...')"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); //getServletContext().getContextPath() RequestDispatcher rd=request.getRequestDispatcher("/servlet/down");//"/photosWeb/index.jsp" //The start of url in java code block and web.xml "/" represents the project root directory rd.forward(request, response); }else{ //Real download: Read the photo file of the server hard disk and send it to the client (set the response header) //Get the real file String realName=pm.getRealName(); realName=URLEncoder.encode(realName, "utf-8");//If it is a Chinese name, it must be transcoded to prevent the file name from being garbled in Chinese // InputStream in=DownServlet.class.getClassLoader().getResourceAsStream(realName); //Set the display type to download response.setContentType("application/force-download"); //Set the response header response.setHeader("content-Disposition", "attachment;filename=/""+realName+"/"); // String path=request.getContextPath()+"/photos/"+pm.getDir()+"/"+pm.getId()+pm.getExt(); String path="photos/"+pm.getDir()+"/"+pm.getId()+pm.getExt(); String filePath=getServletContext().getRealPath(path); FileUtils.copyInputStreamToFile(request.getInputStream(), new File(filePath)); InputStream in=new FileInputStream(filePath); OutputStream o=response.getOutputStream(); byte b[]=new byte[1024]; int len=0; while((len=in.read(b))!=-1){ o.write(b, 0, len); } o.close(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); }} Page display effect:
Configuration file web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>cn.hncu.servlet.UploadServlet</servlet-class> </servlet> <servlet> <servlet-name>ShowAllImgServlet</servlet-name> <servlet-class>cn.hncu.servlet.ShowAllImgServlet</servlet-class> </servlet> <servlet> <servlet-name>DownServlet</servlet-name> <servlet-class>cn.hncu.servlet.DownServlet</servlet-class> </servlet> <servlet> <servlet-name>DelPhotoServlet</servlet-name> <servlet-class>cn.hncu.servlet.DelPhotoServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/servlet/uploadServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ShowAllImgServlet</servlet-name> <url-pattern>/servlet/showAllImg</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-mapping> <servlet-name>DownServlet</servlet-name> <url-pattern>/servlet/down</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>DelPhotoServlet</servlet-name> <url-pattern>/servlet/delPhoto</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
Database:photos.xml
<?xml version="1.0" encoding="UTF-8"?><photos> <!-- Database Design<photo id="uuid" realName="real file name.jpg" dT="2016-10-03 19:51:31" ext=".jpg" dir="a/5" ip="192.168.12.12"> <desc>Photo description information</desc> </photo> --></photos>
Value Object: PhotoModel.java
package cn.hncu.domain;public class PhotoModel { //photo value object private String id;//UUID private String realName;//Photo real file name private String ext;//Extension private String dir;//Direct directory stored after file spread private String dt;//Upload date and time private String ip;//Upload client's ip address private String desc;//Photo description public String getId() { return id; } public void setId(String id) { this.id = id; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getExt() { return ext; } public void setExt(String ext) { this.ext = ext; } public String getDir() { return dir; } public void setDir(String dir) { this.dir = dir; } public String getDt() { return dt; } public void setDt(String dt) { this.dt = dt; } public String getDt() { return dt; } public void setDt(String dt) { this.dt = dt; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String Dreturn desc; } public void setDesc(String desc) { this.desc = desc; }}dao layer: Here is abbreviation, only the implementation class PhotoDaoImpl.java is written
package cn.hncu.dao;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import org.dom4j.Document;import org.dom4j.Element;import cn.hncu.domain.PhotoModel;import cn.hncu.utils.DomFactory;public class PhotoDaoImpl { public boolean sava(PhotoModel pm){ Document dom=DomFactory.getDom(); Element root=dom.getRootElement(); Element e=root.addElement("photo"); e.addAttribute("id", pm.getId()); e.addAttribute("dir", pm.getDir()); e.addAttribute("dt", pm.getDt()); e.addAttribute("ext", pm.getExt()); e.addAttribute("ip", pm.getIp()); e.addAttribute("realName", pm.getRealName()); e.addElement("desc").setText(pm.getDesc()); boolean b=DomFactory.save(); if(b){ return true; } return false; } public List<PhotoModel> getAllPhotos(){ List<PhotoModel> li=new ArrayList<PhotoModel>(); Document dom=DomFactory.getDom(); Element e=dom.getRootElement(); Iterator<Element> it=e.elementIterator(); while(it.hasNext()){ Element ie=it.next(); PhotoModel pm=new PhotoModel(); pm.setId(ie.attributeValue("id")); pm.setDir(ie.attributeValue("dir")); pm.setDt(ie.attributeValue("dt")); pm.setExt(ie.attributeValue("ext")); pm.setIp(ie.attributeValue("ip")); pm.setRealName(ie.attributeValue("realName")); pm.setDesc(ie.elementText("desc")); li.add(pm); } return li; } public PhotoModel getSingleById(String id){ List<PhotoModel> li=getAllPhotos(); PhotoModel pm=new PhotoModel(); for(PhotoModel p:li){ if(p.getId().equals(id)){ return p; } } return null; } public boolean del(String id) { Document dom=DomFactory.getDom(); Element e=(Element) dom.selectSingleNode("//photo[@id='"+id+"']"); return e.getParent().remove(e); }}Tools:
1.
package cn.hncu.utils;import java.text.SimpleDateFormat;import java.util.Date;import java.util.UUID;public class MyUtils { private MyUtils() { } public static String getUUID(){ return UUID.randomUUID().toString().replace("-", ""); } private static SimpleDateFormat sdf=new SimpleDateFormat("yy-MM-dd HH:mm:ss"); public static String getCurrentDataime(){ return sdf.format(new Date()); } public static String getDir(String uuid){ String dir1=Integer.toHexString(uuid.hashCode()&0xf); String dir2=Integer.toHexString((uuid.hashCode()&0xf0)>>4); return dir1+"/"+dir2; }}2.
package cn.hncu.utils;import java.io.FileOutputStream;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;public class DomFactory { private static Document dom; private static String fileName; static{ try { SAXReader r=new SAXReader(); //Get the resource file fileName=DomFactory.class.getClassLoader().getResource("photos.xml").getPath(); System.out.println("users.xml path:"+fileName);//"/D:/apache-tomcat-7.0.30/webapps/photosWeb/WEB-INF/classes/photos.xml" //Note: Get the resource method under the current project classpath in tomcat dom=r.read(fileName); } catch (DocumentException e) { e.printStackTrace(); } } public static Document getDom(){ return dom; } public static boolean save(){ XMLWriter w; try { w = new XMLWriter(new FileOutputStream(fileName)); w.write(dom); w.close(); return true; } catch (Exception e) { return false; } }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.