1.文件传输
1.1准备工作
1.项目创建
建立一个空项目:首先要选中JDK,
然后添加moudle,再配置tomcat,直接运行tomcat确保目前的空项目是没问题的。
2.对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器的。
3.两个jar包
<dependencies>
<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.4</version>
</dependency>
? 跨平台:
?
1.2使用类介绍
文件上传注意事项:
- 为了保证服务器安全,上传文件应该放在外界无法直接访问的目录下,比如放在WEB-INF目录下
- 为了防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名。1.txt -时间戳 -uuid生成一串随机的不会重复的数字 -md5 -位运算算法
- 要限制上传文件的最大值
- 可以限制上传文件的类型,有收到上传文件名时,判断后缀名是否合法
? 用到的类详解:
ServletFileUpload负责处理上传的文件数据,并将表单中的每个输入项封装成一个FileItem对象,在使用ServletFileUpload对象解析请求时需要DiskFileItemFactory对象。
所以,我们需要在进行解析工作前构造好DiskFileItemFactory对象,通过ServletFileUpload对象的构造方式或者setFileItemFactory()方法设置ServletFileUpload对象的fileItemFactory属性。
? 前端页面:
在HTML页面input必须有file类型,表单如果包含一个文件上传输入项的话,这个表单的enctype属性就必须为enctype=“multipart/form-data” 。
浏览器表单的类型如果为multipart/form-data ,在服务器端想获取数据就要通过流。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<body>
<%--
get:上传文件大小有限制
post:上传文件大小没有限制
--%>
<form enctype="multipart/form-data" method="post">
<p>上传用户:<input type="text" name="username"></p>
<p>上传文件1:<input type="file" name="filename1"></p>
<p>上传文件2:<input type="file" name="filename2"></p>
<p><input type="submit">提交 | <input type="reset">重置</p>
</form>
</body>
</html>
?
【常用方法介绍】
boolean isFormField();
String getFieldName();
String getString();
String getName();
InputStream getInputStream();
viod delete();
?
1.3ServletFileUpload类
ServletFileUpload负责处理上传的文件数据,并将表单中每个输入项封装成一个Fileltem对象中。使用其parseRequest(HttpServletRequest)方法可以将通过表单中每一个HTML标签提交的数据封装成一个Fileltem对象,然后以List列表的形式返回。使用该方法处理上传文件简单易用。
- 处理上传的文件,一般都需要通过流来获取,我们可以使用 request.getInputstream(),原生态的文件上传流获取,但十分麻烦。我们都建议使用Apache的文件上传组件来实现,common-fileupload,它需要commons-io组件。
- UID(唯一识别的通用码),保证文件名唯一
UUID.randomUUID(),随机生一个唯一识别的通用码 网络传输中的东西,都需要序列化 pojo实体类,如果想要在多个电脑运行,传输—>需要把对象都序列化了 JNI=java Native Interface implements Serializable :标记接口,JVM—>java栈,本地方法栈 native–>c++
package moli;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
public class FileServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (!ServletFileUpload.isMultipartContent(req)){
return;
}
String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
File uploadFile = new File(uploadPath);
if (!uploadFile.exists()){
uploadFile.mkdir();
}
String tmpPath = this.getServletContext().getRealPath("/WEB-INF/upload");
File tmpFile = new File(tmpPath);
if (!tmpFile.exists()){
tmpFile.mkdir();
}
try {
DiskFileItemFactory factory = getDiskFileItemFactory(tmpFile);
ServletFileUpload upload = getServletFileUpload(factory);
String msg = null;
msg = uploadParseRequest(upload, req, uploadPath);
System.out.println(msg);
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);
return factory;
}
public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setProgressListener(new ProgressListener() {
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("总大小:" + pContentLength + "已上传:" + pBytesRead+",进度:"+((double)pBytesRead/pContentLength)*100+"%");
}
});
upload.setHeaderEncoding("UTF-8");
upload.setFileSizeMax(1024 * 1024 * 10);
upload.setSizeMax(1024 * 1024 * 10);
return upload;
}
public static String uploadParseRequest(ServletFileUpload upload, HttpServletRequest request, String uploadPath) throws FileUploadException, IOException {
String msg = "";
List<FileItem> fileItems = upload.parseRequest(request);
for (FileItem fileItem : fileItems) {
if (fileItem.isFormField()) {
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;
}
}
? ?
2.邮件发送
2.1原理图
- 要在网络上实现邮件功能,必须要有专门的邮件服务器。这些邮件服务器类似于现实生活中的邮局,它主要负责接收用户投递过来的邮件,并把邮件投递到邮件接收者的电子邮箱中。
- SMTP服务器地址:一般是 smtp.xxx.com,比如163邮箱是smtp.163.com,qq邮箱是smtp.qq.com。
- 电子邮箱(E-Mail地址)的获得需要在邮件服务器上进行申请。
?
MIME (多用途互联网邮件扩展类型):它是一个互联网标准,扩展了电子邮件标准,使其能够支持:
- 非ASCII字符文本
- 非文本格式附件(二进制、声音、图像等)
- 由多部分(multiple parts)组成的消息体
- 包含非ASCII字符的头信息(Header information)
?
2.2准备工作
2.2.1jar包
JavaMail 是sun公司(现以被甲骨文收购)为方便Java开发人员在应用程序中实现邮件发送和接收功能而提供的一套标准开发包。它支持一些常用的邮件协议,如前面所讲的SMTP,POP3,IMAP,还有MIME等。我们在使用JavaMail API 编写邮件时,无须考虑邮件的底层实现细节,只要调用JavaMail 开发包中相应的API类就可以了。
?
2.2.2对象
- 创建包含邮件服务器的网络连接信息的Session对象。
- 创建代表邮件内容的Message对象
- 创建Transport对象,连接服务器,发送Message,关闭连接
?
2.2.3qq邮箱获取对应权限
要发送文件,需要获得协议和支持,开启POP3和SMTP服务:
?
2.3纯文本邮件
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class mail1 {
public static void main(String[] args) throws Exception {
Properties prop=new Properties();
prop.setProperty("mail.host","smtp.qq.com");
prop.setProperty("mail.transport.protocol","smtp");
prop.setProperty("mail.smtp.auth","true");
MailSSLSocketFactory sf=new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable","true");
prop.put("mail.smtp.ssl.socketFactory",sf);
Session session=Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("3521945255@qq.com","klzptmndwkfdchbb");
}
});
session.setDebug(true);
Transport ts=session.getTransport();
ts.connect("smtp.qq.com","3521945255@qq.com","klzptmndwkfdchbb");
MimeMessage message=new MimeMessage(session);
message.setFrom(new InternetAddress("3521945255@qq.com"));
message.setRecipient(Message.RecipientType.TO,new InternetAddress("3521945255@qq.com"));
message.setSubject("test");
message.setContent("<h1 style='color: red'>111111</h1>","text/html;charset=UTF-8");
ts.sendMessage(message,message.getAllRecipients());
ts.close();
}
private static class MailSSLSocketFactory {
public void setTrustAllHosts(boolean b) {
}
}
}
运行结果:成功收到邮件
?
2.4复杂邮件发送
两个类:每一个文本、图片、附件可以分为一个MimeBodyPart,由MimeMultipart完成组装。
multipart属性可以都设置为mixed。
?
2.4.1包含图片的发送
跟纯文本邮件做比较,只改动了第四步
import com.sun.mail.util.MailSSLSocketFactory;
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;
import java.util.Properties;
public class mail2 {
public static void main(String[] args) throws Exception {
Properties prop=new Properties();
prop.setProperty("mail.host","smtp.qq.com");
prop.setProperty("mail.transport.protocol","smtp");
prop.setProperty("mail.smtp.auth","true");
MailSSLSocketFactory sf=new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable","true");
prop.put("mail.smtp.ssl.socketFactory",sf);
Session session=Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("3521945255@qq.com","授权码");
}
});
session.setDebug(true);
Transport ts=session.getTransport();
ts.connect("smtp.qq.com","3521945255@qq.com","klzptmndwkfdchbb");
MimeMessage message=new MimeMessage(session);
message.setFrom(new InternetAddress("3521945255@qq.com"));
message.setRecipient(Message.RecipientType.TO,new InternetAddress("3521945255@qq.com"));
message.setSubject("java发出");
MimeBodyPart image=new MimeBodyPart();
DataHandler dh=new DataHandler(new FileDataSource("D:\\c\\图片\\wallhaven-28o276.jpg"));
image.setDataHandler(dh);
image.setContentID("girl.jpg");
MimeBodyPart text=new MimeBodyPart();
text.setContent("这是一张正文<img src='cid:girl.jpg'>","text/html;charset=UTF-8");
MimeMultipart mm=new MimeMultipart();
mm.addBodyPart(text);
mm.addBodyPart(image);
mm.setSubType("related");
message.setContent(mm);
message.saveChanges();
ts.sendMessage(message,message.getAllRecipients());
ts.close();
}
}
邮件成功发送:
?
2.4.2包含附件的发送
也是只有邮件内容第四步发生了改动
import com.sun.mail.util.MailSSLSocketFactory;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class mail3 {
public static void main(String[] args) throws Exception {
Properties prop=new Properties();
prop.setProperty("mail.host","smtp.qq.com");
prop.setProperty("mail.transport.protocol","smtp");
prop.setProperty("mail.smtp.auth","true");
MailSSLSocketFactory sf=new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable","true");
prop.put("mail.smtp.ssl.socketFactory",sf);
Session session=Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("3521945255@qq.com","klzptmndwkfdchbb");
}
});
session.setDebug(true);
Transport ts=session.getTransport();
ts.connect("smtp.qq.com","3521945255@qq.com","klzptmndwkfdchbb");
MimeMessage message=new MimeMessage(session);
message.setFrom(new InternetAddress("3521945255@qq.com"));
message.setRecipient(Message.RecipientType.TO,new InternetAddress("3521945255@qq.com"));
message.setSubject("test3");
MimeBodyPart image=new MimeBodyPart();
DataHandler dh=new DataHandler(new FileDataSource("D:\\c\\图片\\wallhaven-28o276.jpg"));
image.setDataHandler(dh);
image.setContentID("girl.jpg");
MimeBodyPart text=new MimeBodyPart();
text.setContent("这是一张正文<img src='cid:girl.jpg'>","text/html;charset=UTF-8");
MimeBodyPart body1= new MimeBodyPart();
body1.setDataHandler(new DataHandler(new FileDataSource("D:\\c\\功能扩展\\邮件发送\\11.txt")));
body1.setFileName("11.txt");
MimeMultipart mm=new MimeMultipart();
mm.addBodyPart(body1);
mm.addBodyPart(text);
mm.addBodyPart(image);
mm.setSubType("mixed");
message.setContent(mm);
message.saveChanges();
ts.sendMessage(message,message.getAllRecipients());
ts.close();
}
}
邮件发送成功:
? ? ?
3.javaweb发送邮件
现在很多网站都提供有用户注册功能,通常我们注册成功之后就会收到一封来自注册网站的邮件,这个邮件里可能包含了我们注册的用户名和密码以及一个激活账户的超链接等信息。今天我们也来实现这样的一个功能,实现发送邮件借助于JavaMail。
? 首先创建一个maven项目,配置tomcat,跑一下,确定没问题;然后创建包结构。
3.1前端页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/RegisterServlet.do" method="get">
用户名:<input type="text" name="username">
密码:<input type="text" name="pa's's">
邮箱:<input type="text" name="email">
<input type="submit" value="注册">
</form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>1</title>
</head>
<body>
<h1>xxx网站提示</h1>
${message}
</body>
</html>
?
3.2实体类(Dao层)
package moli.pojo;
import java.io.Serializable;
public class User implements Serializable {
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 + '\'' + '}';
}
}
?
3.3工具类(业务层)
package moli.utils;
import com.sun.mail.util.MailSSLSocketFactory;
import moli.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 = "3521945255@qq.com";
private String username = "3521945255@qq.com";
private String password = "tvatktjyckcvciga";
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", host);
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getDefaultInstance(prop, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("3521945255@qq.com", "tvatktjyckcvciga");
}
});
session.setDebug(true);
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) {
throw new RuntimeException(e);
}
}
}
?
3.4servlet(控制层)
package moli.servlet;
import moli.pojo.User;
import moli.utils.Sendmail;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
String username = req.getParameter("username");
String password = req.getParameter("password");
String email = req.getParameter("email");
User user = new User(username,password,email);
Sendmail send = new Sendmail(user);
send.start();
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);
}
}
}
依赖:
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
web.xml
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>moli.servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet.do</url-pattern>
</servlet-mapping>
? 最终收到邮件:
|