JavaWeb实现文件上传及邮件发送

文件上传

pom.xml配置,导入文件上传的相应jar包

<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>

文件上传具体实现Servlet

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.xml

<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上传成功界面

<%@ 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添加到项目依赖中。

以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 注册界面

  <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);
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值