pom.xml配置,導入文件上傳的相應jar包html
<dependencies> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> </dependencies>
index.jsp,設置表單enctype="multipart/form-data"前端
<%@page contentType="text/html;charset=UTF-8" language="java" %> <html> <body> <form action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data" method="post"> 上傳用戶:<input type="text" name="username"><br/> <p><input type="file" name="file1"></p> <p> <input type="file" name="file2"></p> <p><input type="submit" value="註冊"> <input type="reset"></p> </form> </body> </html>
文件上傳具體實現Servletjava
public class FileServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("doPost..."); //判斷是普通的表單仍是帶文件的表單 if (!ServletFileUpload.isMultipartContent(req)) { System.out.println("return"); return;//終止方法運行 } System.out.println("path"); //建立上傳文件的保存路徑,保存在WEB-INF下,用戶沒法直接訪問 String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload"); File uploadfile = new File(uploadPath); if (!uploadfile.exists()) { uploadfile.mkdir();//建立 } //緩存 臨時文件 System.out.println("tempPath"); String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp"); System.out.println(tempPath); File tempFile = new File(tempPath); if (!tempFile.exists()) { tempFile.mkdir();//建立臨時目錄 } try { System.out.println("start"); //處理文件的上傳路徑和大小 DiskFileItemFactory factory = getDiskFileItemFactory(tempFile); //獲取ServletFileUpload ServletFileUpload upload = getServletFileUpload(factory); //處理上傳的文件 String msg = uploadParseRequest(upload, req, uploadPath); req.setAttribute("msg",msg); req.getRequestDispatcher("info.jsp").forward(req,resp); } catch (FileUploadException e) { e.printStackTrace(); } } public static DiskFileItemFactory getDiskFileItemFactory(File file){ DiskFileItemFactory factory = new DiskFileItemFactory(); //設置緩衝區,上傳文件大於緩衝區的時候,放入臨時文件 factory.setSizeThreshold(1024*1024); factory.setRepository(file);//臨時目錄 System.out.println("factorty!!"); return factory; } public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory){ ServletFileUpload upload = new ServletFileUpload(factory); //監聽文件上傳進度 upload.setProgressListener(new ProgressListener() { @Override public void update(long pByteRead, long pContentLength, int pItems) { System.out.println("總大小"+pContentLength+"已上傳:"+pByteRead); } }); //處理亂碼問題 upload.setHeaderEncoding("UTF-8"); //設置單個文件的最大值 upload.setFileSizeMax(1024*1024*10); //設置總共可以上傳的文件的大小 upload.setSizeMax(1024*1024*10); return upload; } public static String uploadParseRequest(ServletFileUpload upload,HttpServletRequest req,String uploadPath) throws IOException, FileUploadException { String msg = ""; //處理上傳文件 //把前端的請求封裝成一個FileItems對象 List<FileItem> fileItems = upload.parseRequest(req); for (FileItem fileItem : fileItems) { //判斷是普通的表單仍是帶文件的表單 if (fileItem.isFormField()){ //getFieldName是前端表單控件的name String name = fileItem.getFieldName(); String value = fileItem.getString("UTF-8"); System.out.println(name+":"+value); }else { //處理上傳的文件 String uploadFileName = fileItem.getName(); System.out.println("上傳的文件名是「"+uploadFileName); if (uploadFileName.trim().equals("")||uploadFileName==null){ continue; } //得到上傳文件名 String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1); //得到文件的後綴名 String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf("." )+1); System.out.println(fileName+"文件"+fileExtName); //生成惟一識別的通用碼 String uuidPath = UUID.randomUUID().toString(); String realPath = uploadPath+"/"+uuidPath; File realPathFile = new File(realPath); if (!realPathFile.exists()){ realPathFile.mkdir(); } //存放的地址 //文件傳輸 InputStream inputStream = fileItem.getInputStream(); FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName); byte[] buffer = new byte[1024*1024]; int len = 0; while ((len=inputStream.read(buffer))>0){ fos.write(buffer,0,len); } fos.close(); inputStream.close(); msg = "上傳成功!"; fileItem.delete();//上傳成功,刪除臨時文件 } } return msg; } }
web.xmlgit
<servlet> <servlet-name>FileServlet</servlet-name> <servlet-class>com.zr.FileServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileServlet</servlet-name> <url-pattern>/upload.do</url-pattern> </servlet-mapping>
info.jsp上傳成功界面web
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> ${msg} </body> </html>
新建Java項目,在lib包中導入activation-1.1.1.jar和mail-1.4.7.jar,右擊lib,點擊add as library添加到項目依賴中。api
以qq郵箱爲例:設置中開啓SMTP和POP3服務獲取受權碼,如下例子中qjpgitodfatwbbfg爲個人qq郵箱受權碼。緩存
package com.zr; import com.sun.mail.util.MailSSLSocketFactory; import java.security.GeneralSecurityException; import java.util.Properties; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class MailTest { //簡單郵件 沒有圖片和附件 純文字 //複雜郵件 有圖片和附件 //發送郵件 需開啓smtp pop3服務 qjpgitodfatwbbfg public static void main(String[] args) throws Exception { Properties prop = new Properties(); prop.setProperty("mail.host","smtp.qq.com"); //設置qq郵件服務器 prop.setProperty("mail.transport.protocol","smtp"); //郵件發送協議 prop.setProperty("mail.smtp.auth","true"); //須要驗證用戶名和密碼 //qq郵箱 須要設置SSL加密(其它郵箱不須要) MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); prop.put("mail.smtp.ssl.enable","true"); prop.put("mail.smtp.ssl.socketFactory",sf); //建立定義整個應用程序所需環境信息的Session對象 Session session = Session.getDefaultInstance(prop, new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("813794474@qq.com","qjpgitodfatwbbfg"); } }); //開啓Session的Debug模式,看到程序發送Email運行狀態 session.setDebug(true); //經過Session獲得transport對象 Transport ts = session.getTransport(); //使用郵件的用戶名和受權碼連上郵件服務器 ts.connect("smtp.qq.com","813794474@qq.com","qjpgitodfatwbbfg"); //建立郵件 //建立郵件對象 MimeMessage message = new MimeMessage(session); //郵件的發件人 message.setFrom(new InternetAddress("813794474@qq.com")); //郵件的收件人 message.setRecipient(Message.RecipientType.TO,new InternetAddress("813794474@qq.com")); //郵件的標題 message.setSubject("簡單郵件"); //郵件內容 message.setContent("你好啊!","text/html;charset=UTF-8"); //發送 ts.sendMessage(message,message.getAllRecipients()); ts.close(); } }
package com.zr; import com.sun.mail.util.MailSSLSocketFactory; import java.security.GeneralSecurityException; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class MailTest2 { //簡單郵件 沒有圖片和附件 純文字 //複雜郵件 有圖片和附件 //發送郵件 需開啓smtp pop3服務 qjpgitodfatwbbfg public static void main(String[] args) throws Exception { Properties prop = new Properties(); prop.setProperty("mail.host","smtp.qq.com"); //設置qq郵件服務器 prop.setProperty("mail.transport.protocol","smtp"); //郵件發送協議 prop.setProperty("mail.smtp.auth","true"); //須要驗證用戶名和密碼 //qq郵箱 須要設置SSL加密(其它郵箱不須要) MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); prop.put("mail.smtp.ssl.enable","true"); prop.put("mail.smtp.ssl.socketFactory",sf); //建立定義整個應用程序所需環境信息的Session對象 Session session = Session.getDefaultInstance(prop, new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("813794474@qq.com","qjpgitodfatwbbfg"); } }); //開啓Session的Debug模式,看到程序發送Email運行狀態 session.setDebug(true); //經過Session獲得transport對象 Transport ts = session.getTransport(); //使用郵件的用戶名和受權碼連上郵件服務器 ts.connect("smtp.qq.com","813794474@qq.com","qjpgitodfatwbbfg"); //建立郵件 //建立郵件對象 MimeMessage message = new MimeMessage(session); //郵件的發件人 message.setFrom(new InternetAddress("813794474@qq.com")); //郵件的收件人 message.setRecipient(Message.RecipientType.TO,new InternetAddress("813794474@qq.com")); //郵件的標題 message.setSubject("帶圖片的郵件"); //準備圖片的數據 MimeBodyPart image = new MimeBodyPart(); DataHandler dh = new DataHandler(new FileDataSource("D:\\IDEACode\\file-and-mail\\mail-java\\src\\404.jpg")); image.setDataHandler(dh); image.setContentID("404.jpg"); //準備正文數據 MimeBodyPart text = new MimeBodyPart(); text.setContent("這是一個帶圖片<img src='cid:404.jpg'>的郵件","text/html;charset=UTF-8"); //描述數據關係 MimeMultipart mm = new MimeMultipart(); mm.addBodyPart(text); mm.addBodyPart(image); //附件用mixed mm.setSubType("related"); //設置到消息中 保存修改 message.setContent(mm); message.saveChanges(); //發送 ts.sendMessage(message,message.getAllRecipients()); ts.close(); } }
package com.zr; import com.sun.mail.util.MailSSLSocketFactory; import java.security.GeneralSecurityException; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class MailTest3 { //簡單郵件 沒有圖片和附件 純文字 //複雜郵件 有圖片和附件 //發送郵件 需開啓smtp pop3服務 qjpgitodfatwbbfg public static void main(String[] args) throws Exception { Properties prop = new Properties(); prop.setProperty("mail.host","smtp.qq.com"); //設置qq郵件服務器 prop.setProperty("mail.transport.protocol","smtp"); //郵件發送協議 prop.setProperty("mail.smtp.auth","true"); //須要驗證用戶名和密碼 //qq郵箱 須要設置SSL加密 MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); prop.put("mail.smtp.ssl.enable","true"); prop.put("mail.smtp.ssl.socketFactory",sf); //建立定義整個應用程序所需環境信息的Session對象 Session session = Session.getDefaultInstance(prop, new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("813794474@qq.com","qjpgitodfatwbbfg"); } }); //開啓Session的Debug模式,看到程序發送Email運行狀態 session.setDebug(true); //經過Session獲得transport對象 Transport ts = session.getTransport(); //使用郵件的用戶名和受權碼連上郵件服務器 ts.connect("smtp.qq.com","813794474@qq.com","qjpgitodfatwbbfg"); MimeMessage mimeMessage = imageMail(session); //發送 ts.sendMessage(mimeMessage,mimeMessage.getAllRecipients()); ts.close(); } public static MimeMessage imageMail(Session session) throws Exception{ //建立郵件 //建立郵件對象 MimeMessage message = new MimeMessage(session); //郵件的發件人 message.setFrom(new InternetAddress("813794474@qq.com")); //郵件的收件人 message.setRecipient(Message.RecipientType.TO,new InternetAddress("813794474@qq.com")); //郵件的標題 message.setSubject("帶圖片和附件的郵件"); //準備圖片的數據 MimeBodyPart image = new MimeBodyPart(); DataHandler dh = new DataHandler(new FileDataSource("D:\\IDEACode\\file-and-mail\\mail-java\\src\\404.jpg")); image.setDataHandler(dh); image.setContentID("404.jpg"); //準備正文數據 MimeBodyPart text = new MimeBodyPart(); text.setContent("這是一個帶圖片<img src='cid:404.jpg'>的郵件","text/html;charset=UTF-8"); //附件 MimeBodyPart body3 = new MimeBodyPart(); body3.setDataHandler(new DataHandler(new FileDataSource("D:\\IDEACode\\file-and-mail\\mail-java\\src\\ext.txt"))); body3.setFileName("e.txt"); //描述數據關係 MimeMultipart mm = new MimeMultipart(); mm.addBodyPart(text); mm.addBodyPart(image); //附件用mixed mm.setSubType("related"); //將圖片和文本設置爲主體 MimeBodyPart context = new MimeBodyPart(); context.setContent(mm); //拼接附件 MimeMultipart all = new MimeMultipart(); all.addBodyPart(body3); all.addBodyPart(context); all.setSubType("mixed"); //設置到消息中 保存修改 message.setContent(all); message.saveChanges(); return message; } }
新建Maven項目,在pom.xml中導入jsp,servlet,mail,activation相關的jar包依賴。服務器
index.jsp 註冊界面session
<body> <form action="${pageContext.request.contextPath}/registerServlet.do" method="post"> 用戶名:<input type="text" name="username"><br/> 密碼:<input type="password" name="password"><br/> 郵箱:<input type="text" name="email"><br/> <input type="submit" value="註冊"> </form> </body>
info.jsp 註冊後跳轉的界面多線程
<body> <h1>***網站舒適提示</h1> ${message} </body>
User 用戶的pojo類
package com.zr.pojo; public class User { private String username; private String password; private String email; public User() { } public User(String username, String password, String email) { this.username = username; this.password = password; this.email = email; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User{" + "username='" + username + '\'' + ", password='" + password + '\'' + ", email='" + email + '\'' + '}'; } }
郵件發送的工具類
package com.zr.util; import com.sun.mail.util.MailSSLSocketFactory; import com.zr.pojo.User; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; //多線程改善用戶體驗 異步 public class SendMail extends Thread{ private String from = "813794474@qq.com"; private String username = "813794474@qq.com"; private String password = "qjpgitodfatwbbfg"; private String host = "smtp.qq.com"; private User user; public SendMail(User user){ this.user = user; } @Override public void run() { try { Properties prop = new Properties(); prop.setProperty("mail.host", "smtp.qq.com"); //設置qq郵件服務器 prop.setProperty("mail.transport.protocol", "smtp"); //郵件發送協議 prop.setProperty("mail.smtp.auth", "true"); //須要驗證用戶名和密碼 //qq郵箱 須要設置SSL加密 MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); prop.put("mail.smtp.ssl.enable", "true"); prop.put("mail.smtp.ssl.socketFactory", sf); //建立定義整個應用程序所需環境信息的Session對象 Session session = Session.getDefaultInstance(prop, new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("813794474@qq.com", "qjpgitodfatwbbfg"); } }); //開啓Session的Debug模式,看到程序發送Email運行狀態 session.setDebug(true); //經過Session獲得transport對象 Transport ts = session.getTransport(); //使用郵件的用戶名和受權碼連上郵件服務器 ts.connect(host, username, password); //建立郵件 //建立郵件對象 MimeMessage message = new MimeMessage(session); //郵件的發件人 message.setFrom(new InternetAddress(from)); //郵件的收件人 message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); //郵件的標題 message.setSubject("註冊郵件"); String info = "恭喜你註冊成功!你的用戶名:"+user.getUsername()+",密碼:"+user.getPassword()+",請妥善保管!!"; //郵件內容 message.setContent(info, "text/html;charset=UTF-8"); message.saveChanges(); //發送 ts.sendMessage(message, message.getAllRecipients()); ts.close(); }catch (Exception e){ e.printStackTrace(); } } }
RegisterServlet編寫
public class RegisterServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //接收用戶的請求 封裝成對象 try { String username = req.getParameter("username"); String passeord = req.getParameter("passeord"); String email = req.getParameter("email"); User user = new User(username,passeord,email); //使用線程發送郵件,防止耗時,或註冊人數過多引發的問題 SendMail sendMail = new SendMail(user); sendMail.start(); //sendMail.run(); //用戶登陸註冊成功後 給用戶發一封郵件 //使用線程來發送郵件 防止出現耗時,和網站註冊人數過多的狀況 req.setAttribute("message","註冊成功!!郵件已經發送到你的郵箱!注意查收!"); req.getRequestDispatcher("info.jsp").forward(req,resp); } catch (Exception e) { e.printStackTrace(); req.setAttribute("message","註冊失敗!"); req.getRequestDispatcher("info.jsp").forward(req,resp); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }