Os exemplos deste artigo compartilham com você o método de fazer álbuns Java para sua referência. O conteúdo específico é o seguinte
Observação:
1) A imagem no HTML é especificada estaticamente. Quando novas imagens são atualizadas, elas devem ser atualizadas manualmente. Portanto, use o servlet para ler todas as imagens em imagens locais e exibi -las dinamicamente para o usuário.
2) Se houver uma imagem com um nome chinês, causará um erro porque o método GET não pode passar diretamente em chinês.
Página principal Index.jsp
<%@ Page Language = "java" import = "java.util.*" PageEncoding = "utf-8"%> <! http: // localhost: 8080/photosweb/ -> <h2> pequeno álbum </h2> <a href = "jsps/upload.jsp"> upload foto </a> <a href = "< %= request.getContextpath () %/servlet/showalliMg"> Browse </s Photos </sict.getContextpath () %>/servlet/showalliM> </srowse </s Photos> </silt.getContextpath () %>/servlet/showalliM> </srowse </s Photos>
Exibição da página:
Carregar a função da imagem:
<%@ Page Language = "java" import = "java.util.*" PageEncoding = "utf-8"%> <! action = "< %= request.getContextPath () %>/servlet/uploadServlet" Method = "post" Enctype = "Multipart/Form-Data"> Foto: <input type = "file" name = "file"/> <br/> Descrição: <input Type = "text" "/" descendente "/> <br/> <br/> </body> </html>
pacote cn.hncu.servlet; importar java.io.file; importar java.io.ioException; importar java.io.inputStream; importar java.io.printwriter; import java.util.List; import javax.serv.let.requestdispater; import javax.servletless; javax.servlet.http.httpServlet; importar javax.servlet.http.httpServletRequest; importar javax.servlet.http.httpServletResponse; importação org.apache.commons.fileUpload.fileItem; org.apache.commons.fileupload.fileUploadexception; importar org.apache.commons.fileupload.disk.diskfileitemfactory; importar org.apache.commons.fileupload.serv.servletfileUpload; importache; 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 transitório // en/">"); out.println ("<html>"); out.println ("<head> <title> um servlet </ititle> </ad Head>"); out.println ("<body>"); out.println ("<body>"); out.println ("<body>"); out.println ("<body>"); out.Close (); } public void DoPost (solicitação httpServletRequest, httpServletResponse Response) lança servletexception, ioexception {request.setcharacterencoding ("utf-8"); Response.setContentType ("Texto/html; charset = utf-8"); PrintWriter out = Response.getWriter (); out.println ("<! doctype html public/"-// w3c // dtd html 4.01 transitório // en/">"); out.println ("<html>"); out.println ("<head> <title> carregar a página fotográfica </ititle> </head>"); out.println ("<body>"); // Extrair informações do formulário de upload: 1. Encapsulá -las em um objeto de valor fotográfico, ligue para a camada DAO para armazená -lo no plano de fundo // 2. Armazene as fotos enviadas no disco rígido do servidor // banco de dados: Armazene as informações sobre o armazenamento das fotos ,,, o arquivo real é armazenado no disco rígido de disco rígido; Arquivo de arquivo = novo arquivo ("d:/a"); if (file.exists ()) {file.mkdirs (); } dfi.setRepository (arquivo); ServletfileUpload upload = new ServletFileUpload (DFI); upload.SetSizEMAX (1024*1024*8); upload.setheadeRencoding ("utf-8"); // ==> request.setcharacterencoding ("utf-8"); tente {list <FileItem> list = upload.parserequest (request); Fotomodel pm = new photomodel (); InputStream in = null; para (FileItem fi: list) {if (fi.isformfield ()) {// Isso não terá o arquivo temporário desc = fi.getString ("utf-8"); pm.setDesc (DEC); } else {in = fi.getInputStream (); // string filename = fi.getfieldName (); // System.out.println ("getFieldName:"+FileName); String filename = fi.getName (); // System.out.println ("getName:"+filename); // teste: c:/users/adl1/pictures/salvado pictures/111.jpg? // Condições padrão se (nome do arquivo == NULL || FILENAME.Trim (). Equals ("nenhum arquivo selecionado ,,,, deve selecionar um arquivo ... <br/>"); string strpath2 = request.getContextPath ()+"/jsps/upload.jsp"; out.println ("<agopath =/////" " } pm.setdt (myutils.getCurrentDataime ()); Realname.Length ()); pm.setdir (myutils.getdir (id)); path = "fotos/"+pm.getdir (); // system.out.println ("caminho:"+caminho); // teste: fotos/9/0 string filepath = getServletContext (). getRealPath (path); // system.out.println ("filepath:"+filepath); Teste: d: /apache-tomcat-7.0.30/webapps/photosweb/photos/9/0 Arquivo dir = novo arquivo (filepath); if (! Dir.Exists ()) {Dir.mkdirs (); } Fileutils.copyInputStreamTofile (in, novo arquivo (filepath+"/"+pm.getid ()+pm.getext ())); // // se o disco rígido for salvo com sucesso, pule para a página principal - Forward /// request Dispatcher 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 e Web.xml representam o diretório raiz do projeto // rd.forward (solicitação, resposta); // encaminhamento não pode ser usado aqui. A diferença específica entre redirecionamento e encaminhamento: http://blog.csdn.net/xanlv/article/details/52701085 // redirecione Response.sendDirect (getServletContext (). GetContextPath ()+"/index.jsp"); } else {// Salvamento de banco de dados falhou-o intervalo na página de upload RequestDispatcher rd = request.getRequestDispatcher ("/jsps/upload..jsp"); // "/photosweb/index.jsp" rd.forward (solicitação, resposta); }} catch (fileUploadexception e) {throw new RunTimeException ("Falha no upload", e); } finalmente {// limpe o arquivo temporário FILE F = novo arquivo ("D:/a"); Arquivo fs [] = f.listfiles (); para (arquivo ff: fs) {ff.delete (); }} out.println ("</body>"); out.println ("</html>"); out.flush (); out.Close (); }} Efeito de exibição da página:
Navegue pela função da imagem:
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; importar cn.hncu.dao.photodaoimpl; importar cn.hncu.domain.photomodel; classe pública ShowAllImgServLettLends, httpServlet {public Void Doget (HETERSTRETRETRETRETLETLETLETLETL, HTTPSVET {Public Void Doget (HETREVERTRETREstrestlestlet, httpslet {Public Void Doget (HETREVERTRETREMTRETRETLEstlet, httpSetlet {Public Void Doget (HETERSTRETREMTRETREMTENTLETLETL, IoException {Response.SetContentType ("text/html; charset = utf-8"); PrintWriter out = Response.getWriter (); out.println ("<! doctype html public/"-// w3c // dtd html 4.01 transitório // en/">"); out.println ("<html>"); out.println ("<head> <title> Álbum Browse </ititle> </head>"); out.println ("<body>"); String strpath = request.getContextPath ()+"/jsps/upload.jsp"; out.println ("<a href =/" "+strpath+"/"> retorna para fazer upload página </a>"); // string tabela = "<tabela borda = '1px' width = '100%' CellPacing = '0' align = 'Center'>"+// Este método não pode ser definido para centralização ''%string = " style = 'text-align: Center;'> "+" <tr> <th> Nome do arquivo </th> <th> Data e hora de upload </th> <th> foto </th> <th> descrição da foto </th> <th> operação </th> </tr> "; out.println (tabela); // Leia todas as informações da foto da camada DAO e envie-as para a lista de página front-end <Photomodel> list = new PhotodaoImpl (). Getallphotos (); para (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/e78e18352b42410F85DB/ Veja a imagem maior out.println ("<td width = 100> <a href = '"+caminho+"'> <iMg width = 100 altura = 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 ()+"'> Excluir a imagem </a> "); // out.println (" <a href = '<%= request.getContextPath ()%>/servlet/down? id = "+pm.getId ()+"'> baixar a imagem </a> </td> "); out.println ("<br/> <a href = '"+getServletContext (). getContextPath ()+"/servlet/down? id ="+pm.getId ()+"'> baixe a imagem </a> </td>"); out.println ("</tr>"); } out.println ("</ table>"); out.println ("</body>"); out.println ("</html>"); out.flush (); out.Close (); } public void DoPost (solicitação httpServletRequest, resposta httpSertletResponse) lança servletexception, ioexception {Response.setContentType ("text/html; charset = utf-8"); PrintWriter out = Response.getWriter (); out.println ("<! doctype html public/"-// w3c // dtd html 4.01 transitório // en/">"); out.println ("<html>"); out.println ("<head> <title> um servlet </ititle> </ad Head>"); out.println ("<body>"); out.print ("Não suportado método de postagem ..."); out.println ("</body>"); out.println ("</html>"); out.flush (); out.Close (); }} Efeito de exibição da página:
Excluir função:
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 transitório // en/">"); out.println ("<html>"); out.println ("<head> <title> Excluir página fotográfica </ititle> </head>"); out.println ("<body>"); String id = request.getParameter ("id"); String ip = request.getRemoTeaddr (); Fotodaoimpl Dao = new PhotodaoImpl (); Fotomodel pm = dao.getSingleById (id); if (pm! = null) {if (! String strpath = request.getContextPath ()+"/servlet/showAllImg"; out.println ("<br/> <a href =/" "+strpath+"/"> retornar para continuar navegando </a>"); retornar ; } // O exclusão contém duas partes do trabalho: Limpando as informações no banco de dados e excluindo os arquivos de imagem no disco rígido do servidor // 1 limpeza as informações no banco de dados boolean boo = dao.del (id); // 2 Excluindo os arquivos de imagem no disco rígido do servidor if (boo) {string path = "photos/"+pm.getdir ()+"/"+pm.getId ()+pm.getext (); String filepath = getServletContext (). GetRealPath (caminho); Arquivo f = novo arquivo (filepath); if (f.Exists ()) {f.Delete (); } String strpath = request.getContextPath ()+"/servlet/showAllImg"; // System.out.println (strpath); /// photosweb/servlet/showphotos out.println ("excluir com sucesso ... <br/> <a href =/" "+sloth+"/"> retornar ao BROW <BROTE ... } else {out.println ("excluir informações do banco de dados falhou"); }} else {out.println ("o arquivo não existe ..."); String strpath = request.getContextPath ()+"/servlet/showAllImg"; out.println ("<br/> <a href =/" "+strpath+"/"> retornar para continuar navegando </a>"); } out.println ("</body>"); out.println ("</html>"); out.flush (); out.Close (); } public void DoPost (solicitação httpServletRequest, httpServletResponse resposta) lança servletexception, ioexception {Response.setContentType ("text/html"); PrintWriter out = Response.getWriter (); out.println ("<! doctype html public/"-// w3c // dtd html 4.01 transitório // en/">"); out.println ("<html>"); out.println ("<head> <title> Excluir página fotográfica </ititle> </head>"); out.println ("<body>"); out.print ("Nenhum método post suportado ..."); out.println ("</body>"); out.println ("</html>"); out.flush (); out.Close (); }}Exibição da página:
Função de download:
1. Use a HyperConnection na página HTML para apontar para o arquivo a ser baixado (inseguro e facilmente roubado).
pergunta:
Como determinar os recursos locais?
ServletContext representa um projeto da web. Um projeto da web possui apenas um objeto ServletContext.
getRealPath ("/"); // d:/prm/tom/web/
Análise de requisitos:
No desenvolvimento real, qual arquivo de download é selecionado dinamicamente pelo usuário.
Por exemplo, em nosso diretório de imagens do projeto, existem muitos arquivos de imagem. O usuário exibe todas as imagens na página e o usuário pode clicar no link de download para baixar as imagens favoritas.
Design detalhado:
Use uma página da Web estática para exibir todas as imagens. Dê a cada imagem um hiperlink baixado.
Passe o ID da imagem para baixar após a hiperconnection.
Receba dinamicamente os nomes da imagem no serviço. Conclua o download.
pacote cn.hncu.servlet; importar java.io.file; importar java.io.fileInputStream; importar java.io.ioException; importar java.io.inputStream; import java.io.outputStream; import java.io.printwriter; import java.io.urlancer; javax.servlet.servletexception; importar javax.servlet.http.httpServlet; importar javax.servlet.http.httpServletReQuest; import javax.servlet.http.htpsletLeSponse; cn.hncu.dao.photodaoImpl; importar cn.hncu.domain.photomodel; a classe pública OffServlet estende httpServlet {public void Doget (httpServletReQuest Solicy, //trestertleSponse a resposta de que o servirá, download, o que é o servir de imagem. id = request.getParameter ("id"); Fotomodel pm = novo 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 transitório // en/">"); out.println ("<html>"); out.println ("<head> <title> um servlet </ititle> </ad Head>"); out.println ("<body>"); resposta.getWriter (). println ("alert ('Este texto não existe mais ...')"); out.println ("</body>"); out.println ("</html>"); out.flush (); out.Close (); // getServletContext (). getContextPath () requestDispatcher rd = request.getRequestDispatcher ("/servlet/down"); // "/photosweb/index.jsp" // o início do URL no código java e web.xml "/" representa o projeto ROOT Directory Rd. } else {// Download real: leia o arquivo de fotos do disco rígido do servidor e envie -o para o cliente (defina o cabeçalho da resposta) // Obtenha a sequência de arquivos real realname = pm.getRealName (); realname = urlencoder.encode (nome real, "utf-8"); // Se for um nome chinês, deve ser transcodificado para impedir que o nome do arquivo seja iluminado em chinês // inputStream em = downServlet.class.getclassloader (). getResourCeasstream (realname); // Defina o tipo de exibição para baixar a resposta.setContentType ("Application/Force-download"); // Defina a resposta do cabeçalho Response.setheader ("Content-Disposition", "Applement; FileName =/" "+Realname+"/"); // String Path = request.getContextPath ()+"/Photos/"+pm.getdir ()+"/"+pm.getid ()+pm.Getext (); Path = Photos/" O = Response.getOutputStrene (); IoException {Response.SetContentType ("Texto/HTML"); <head> <title> um servlet </title> </adingle> "); out.println (" <body> "); out.println (" </body> "); out.println (" </html> "); out.flush (); out.Close (); }} Efeito de exibição da página:
Arquivo de configuração 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-tattern>/servlet/Down </url-pattern> </servlet-mapping> <Servlet-mapping> <Verlet-Name> delphotoservlet </servlet-name> <url-tattern>/servlet/delphoto </erl-stattern> </servlet> welcome> <lorda-list> <l-wold-file> </-FIL)
Banco de dados: Photos.xml
<? xml versão = "1.0" coding = "utf-8"?> <hotos> <!-design de banco de dados <foto id = "uuid" realname = "names de arquivo real.jpg" dt = "2016-10-03 19:51:31" Ext = ". -> </fotos>
Objeto de valor: photomodel.java
pacote cn.hncu.Domain; public class Photomodel {// Valor da foto Objeto Private String ID; // uuid private string realname; // Foto Nome real Nome do arquivo Private String Ext; // Extensão Private String dir; // Diretório Director Storled após o arquivo string de string private string dt; } 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; } string pública Dreturn Desc; } public void setDesc (string desc) {this.desc = desc; }}DAO Camada: Aqui está a abreviação, apenas a classe de implementação photodaoimpl.java está escrita
pacote cn.hncu.dao; importar java.util.ArrayList; importar java.util.iterator; importar java.util.list; importar org.dom4j.document; importação org.dom4j.Element; import cn.hncu.domain.fotomodel; import cn.hnncuileme; sava (photomodel pm) {document dom = domactory.getDom (); Elemento root = dom.getrootelement (); Elemento e = root.addElement ("foto"); 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 ()); booleano b = domactory.save (); if (b) {return true; } retornar false; } Lista pública <Photomodel> getAllphotos () {list <Photomodel> li = new ArrayList <Photomodel> (); Documento dom = domactory.getDom (); Elemento e = dom.getrootelement (); Iterator <lement> it = e.ElementIterator (); while (it.hasNext ()) {elemento ie = it.Next (); Fotomodel 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 ("desct")); li.add (PM); } retornar li; } public photomodel getsingleById (string id) {list <Photomodel> li = getAllphotos (); Fotomodel pm = new photomodel (); for (photomodel p: li) {if (p.getId (). Equals (id)) {return p; }} retornar nulo; } public boolean del (string id) {document Dom = domactory.getDom (); Elemento E = (elemento) Dom.SelectSinglenode ("// foto [@id = '"+id+"']"); retornar e.getParent (). Remover (e); }}Ferramentas:
1.
pacote cn.hncu.utils; importar java.text.simpledateFormat; importar java.util.date; importar java.util.uuid; public class myutils {private myUtils () {} public static string getuUid () {return uuId.Randomuid (). } estática privada 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 () e 0xf); String dir2 = Integer.toHexString ((uuid.hashcode () & 0xf0) >> 4); retornar dir1+"/"+dir2; }}2.
pacote cn.hncu.utils; importar java.io.fileOutputStream; importar org.dom4j.document; importar org.dom4j.documentException; importar org.dom4j.io.saxReader; importação org.dom4j.io.xmlwriter; public class Fomactory; nome de string estático privado; estático {tente {saxReader r = new saxReader (); // obtenha o arquivo de recurso nome do arquivo = 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: obtenha o método do recurso sob o projeto atual no tomct no tomcat; } catch (documentException e) {e.printStackTrace (); }} documento estático público getDom () {return dom; } public static boolean save () {xmlwriter w; tente {w = new XMLWriter (new FileOutputStream (nome do arquivo)); W.Write (DOM); w.Close (); retornar true; } catch (Exceção e) {return false; }}}O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.