当前位置:网站首页>File uploading and email sending
File uploading and email sending
2022-07-03 13:14:00 【Tolerance speech】
1. File transfer
1.1 preparation
1. Project creation
Create an empty project : The first thing to do is to select JDK,
Then add moudle, To configure tomcat, Direct operation tomcat Make sure that the current empty project is OK .
2. For file upload , In the process of uploading, the browser submits the file to the server in the form of stream .
3. Two jar package
<dependencies>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
Cross platform :
1.2 Introduction to use class
File upload considerations :
- In order to ensure the security of the server , The uploaded file should be placed in a directory that cannot be directly accessed by the outside world , For example WEB-INF Under the table of contents
- In order to prevent file overwriting , To generate a unique filename for the uploaded file .1.txt - Time stamp -uuid Generate a random string of numbers that will not repeat -md5 - Bit arithmetic
- Limit the maximum number of uploaded files
- You can limit the type of files you upload , When you receive the uploaded file name , Determine whether the suffix is legal
Detailed explanation of the classes used :
ServletFileUpload Responsible for handling the uploaded file data , And encapsulate each input item in the form into a FileItem object , In the use of ServletFileUpload Object resolution request requires DiskFileItemFactory object .
therefore , We need to construct the DiskFileItemFactory object , adopt ServletFileUpload How objects are constructed or setFileItemFactory() Method setting ServletFileUpload Object's fileItemFactory attribute .
Front page :
stay HTML page input There has to be file type , If the form contains a file upload entry , Of this form enctype The attribute must be enctype=“multipart/form-data” .
If the type of browser form is multipart/form-data , If you want to get data on the server side, you have to go through the stream .
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<body>
<%--
get: Upload file size is limited
post: There is no limit on the size of uploaded files
--%>
<form enctype="multipart/form-data" method="post">
<p> Upload users :<input type="text" name="username"></p>
<p> Upload files 1:<input type="file" name="filename1"></p>
<p> Upload files 2:<input type="file" name="filename2"></p>
<p><input type="submit"> Submit | <input type="reset"> Reset </p>
</form>
</body>
</html>
【 Introduction to common methods 】
//isFormField Method for judgment FileItem The data encapsulated by class object is a plain text form , It's also a file form , If it is a normal form field, it returns true, Otherwise return to false
boolean isFormField();
//getFieldName Method to return the form label name The value of the property
String getFieldName();
//getString Method is used to FileItem The data stream content stored in the object is returned as a string
String getString();
//getName Method to get the file name in the file upload field
String getName();
// Return the data content of the uploaded file as a stream
InputStream getInputStream();
//delete Method to empty FileItem The main content stored in the class object , If the subject content is saved in a temporary file ,delete Method will delete the temporary file
viod delete();
1.3ServletFileUpload class
ServletFileUpload Responsible for handling the uploaded file data , And encapsulate each input item in the form as a Fileltem In the object . To use its parseRequest(HttpServletRequest) Method can be passed through each... In the form HTML The data submitted by the tag is encapsulated as a Fileltem object , And then to List The form of the list returns . This method is easy to use .
- Handle uploaded files , Generally, you need to get... Through streams , We can use request.getInputstream(), Original ecological file upload stream access , But it's very troublesome . We all recommend Apache File upload component to achieve ,common-fileupload, It needs to commons-io Components .
- UID( A unique universal code ), Make sure the file name is unique
UUID.randomUUID(), Generate a unique universal code at random
Things in network transmission , All need to be serialized
pojo Entity class , If you want to run on multiple computers , transmission —> You need to serialize all the objects
JNI=java Native Interface
implements Serializable : Tag interface ,JVM—>java Stack , Native Method Stack 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 {
// Determine whether the uploaded file is a normal form or a form with files
if (!ServletFileUpload.isMultipartContent(req)){
return;// Terminate method run , This is an ordinary form , Go straight back to
}
// Create a save path for the uploaded file , It is suggested that WEB-INF Under the path , Security , Users cannot directly access the files uploaded between ;
String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
File uploadFile = new File(uploadPath);
if (!uploadFile.exists()){
uploadFile.mkdir();// Create this directory
}
// cache , The temporary file
// Temporary path , If the file exceeds the expected size , Let's put it in a temporary file , Delete automatically in a few days , Or prompt the user to save as permanent
String tmpPath = this.getServletContext().getRealPath("/WEB-INF/upload");
File tmpFile = new File(tmpPath);
if (!tmpFile.exists()){
tmpFile.mkdir();// Create this directory
}
try {
// 1、 establish DiskFileItemFactory object , Handle file path or size restrictions
DiskFileItemFactory factory = getDiskFileItemFactory(tmpFile);
// 2、 obtain ServletFileUpload
ServletFileUpload upload = getServletFileUpload(factory);
// 3、 Handling upload files
// Parse the front-end request , Encapsulated into FileItem object , Need from ServletFileUpload Get in object
String msg = null;
msg = uploadParseRequest(upload, req, uploadPath);
// Servlet Request to forward message
System.out.println(msg);
// Servlet Request to forward message
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();
// Set a buffer through this factory , When the uploaded file is larger than this buffer , Put him in a temporary file ;
factory.setSizeThreshold(1024 * 1024);// The buffer size is 1M
factory.setRepository(file);// Save directory of temporary directory , Need one file
return factory;
}
public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
ServletFileUpload upload = new ServletFileUpload(factory);
// Monitor upload progress
upload.setProgressListener(new ProgressListener() {
// pBYtesRead: Read file size enctype="multipart/form-data"
// pContextLength: file size
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println(" Total size :" + pContentLength + " Uploaded :" + pBytesRead+", speed of progress :"+((double)pBytesRead/pContentLength)*100+"%");
}
});
// Deal with the mess
upload.setHeaderEncoding("UTF-8");
// Set the maximum value of a single file
upload.setFileSizeMax(1024 * 1024 * 10);
// Set the total size of files that can be uploaded
// 1024 = 1kb * 1024 = 1M * 10 = 10м
upload.setSizeMax(1024 * 1024 * 10);
return upload;
}
public static String uploadParseRequest(ServletFileUpload upload, HttpServletRequest request, String uploadPath) throws FileUploadException, IOException {
String msg = "";
// Parse the front-end request , Encapsulated into FileItem object
List<FileItem> fileItems = upload.parseRequest(request);
for (FileItem fileItem : fileItems) {
if (fileItem.isFormField()) {
// Determine whether the uploaded file is a normal form or a form with files , Here is the normal form
// getFieldName Refers to the front-end form control name;
String name = fileItem.getFieldName();
String value = fileItem.getString("UTF-8"); // Deal with the mess
System.out.println(name + ": " + value);
} else {
// Make sure it's an uploaded file
// ============ Processing documents =======================================================================
String uploadFileName = fileItem.getName();// Get the file name
System.out.println(" Uploaded file name : " + uploadFileName);
if (uploadFileName.trim().equals("") || uploadFileName == null) {
continue;
}
// Get the name of the uploaded file /images/girl/paojie.png
String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
// Get the suffix of the file
String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
// If the file suffix fileExtName It's not what we need Just press return Don't deal with , Tell the user that the file type is wrong .
System.out.println(" file information [ Piece name : " + fileName + " --- file type " + fileExtName + "]");
//UUID Unique communication code
String uuidPath = UUID.randomUUID().toString();
// ================ Finished processing documents ================================================================
// Where to deposit ? uploadPath, The path of the real existence of documents realPath
String realPath = uploadPath + "/" + uuidPath;
// Create a folder for each file
File realPathFile = new File(realPath);
if (!realPathFile.exists()) {
realPathFile.mkdir();
}
// ============== Storage address completed ===================================================================
// Get stream for file upload
InputStream inputStream = fileItem.getInputStream();
// Create a file output stream ,realPath = Real folders
FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);
// Create a buffer
byte[] buffer = new byte[1024 * 1024];
// Determine if the reading is complete
int len = 0;
// If it is greater than 0 It means that there are data ;
while ((len = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
// Closed flow
fos.close();
inputStream.close();
msg = " File upload succeeded !";
fileItem.delete(); // Upload successful , Clear temporary files
//============= File transfer complete ===================================================================
}
}
return msg;
}
}
2. Mail delivery
2.1 Schematic diagram
- To realize the mail function on the network , There must be a dedicated mail server . These mail servers are similar to post offices in real life , It's the main user who delivers it , And deliver it to the recipient's email address .
- SMTP Server address : It's usually smtp.xxx.com, such as 163 Email is smtp.163.com,qq Email is smtp.qq.com.
- email (E-Mail Address ) You need to apply on the mail server to get the .
MIME ( Multipurpose Internet mail extension type ): It's an Internet standard , Extended e-mail standards , To enable it to support :
- Not ASCII Character text
- Non text attachments ( Binary system 、 voice 、 Image, etc )
- By many parts (multiple parts) The body of the message
- Include non ASCII Character header information (Header information)
2.2 preparation
2.2.1jar package
JavaMail yes sun company ( Now it is acquired by Oracle ) For convenience Java A set of standard development packages provided by developers to realize the function of sending and receiving mails in applications . It supports some common mail protocols , As mentioned earlier SMTP,POP3,IMAP, also MIME etc. . We are using JavaMail API When writing a message , Don't worry about the underlying implementation details of email , Just call JavaMail The corresponding API Class is OK .
2.2.2 object
- Create contains Mail server Of Network connection information Of Session object .
- Create a representative Email content Of Message object
- establish Transport object , Connect to server , send out Message, Close the connection
2.2.3qq Get the corresponding permissions for mailbox
To send a file , Need agreement and support , Turn on POP3 and SMTP service :
2.3 Plain text mail
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");/// Set up QQ Mail server
prop.setProperty("mail.transport.protocol","smtp");/// Email protocol
prop.setProperty("mail.smtp.auth","true");// Need to verify user password
//QQ Mailbox needs to be set SSL encryption
MailSSLSocketFactory sf=new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable","true");
prop.put("mail.smtp.ssl.socketFactory",sf);
// Use javaMail Sent by 5 A step
//1. Create a that defines the environmental information needed for the entire application session object
Session session=Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]","klzptmndwkfdchbb");
}
});
// Turn on session Of debug Pattern , In this way, you can see that the program sends Email Operating state
session.setDebug(true);// Write but not write
//2. adopt session obtain transport object
Transport ts=session.getTransport();
//3. Use the username and authorization code of the mailbox to connect to the mail server
ts.connect("smtp.qq.com","[email protected]","klzptmndwkfdchbb");
//4. Create mail : Writing documents
// Note the need to pass session
MimeMessage message=new MimeMessage(session);
// Indicate the sender of the message
message.setFrom(new InternetAddress("[email protected]"));
// Indicate the recipient of the message
message.setRecipient(Message.RecipientType.TO,new InternetAddress("[email protected]"));
// Email title
message.setSubject("test");
// The text of the email
message.setContent("<h1 style='color: red'>111111</h1>","text/html;charset=UTF-8");
//5. Send E-mail
ts.sendMessage(message,message.getAllRecipients());
// Close the connection
ts.close();
}
private static class MailSSLSocketFactory {
public void setTrustAllHosts(boolean b) {
}
}
}
Running results : Successfully received mail
2.4 Complex mail sending
Two classes : Every text 、 picture 、 Attachments can be divided into one MimeBodyPart, from MimeMultipart Complete the assembly .
multipart Properties can all be set to mixed.
2.4.1 Including the sending of pictures
Compare it with plain text email , Only the fourth step has been changed
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");/// Set up QQ Mail server
prop.setProperty("mail.transport.protocol","smtp");/// Email protocol
prop.setProperty("mail.smtp.auth","true");// Need to verify user password
//QQ Mailbox needs to be set SSL encryption
MailSSLSocketFactory sf=new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable","true");
prop.put("mail.smtp.ssl.socketFactory",sf);
// Use javaMail Sent by 5 A step
//1. Create a that defines the environmental information needed for the entire application session object
Session session=Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]"," Authorization code ");
}
});
// Turn on session Of debug Pattern , In this way, you can see that the program sends Email Operating state
session.setDebug(true);
//2. adopt session obtain transport object
Transport ts=session.getTransport();
//3. Use the username and authorization code of the mailbox to connect to the mail server
ts.connect("smtp.qq.com","[email protected]","klzptmndwkfdchbb");
//4. Create mail : Writing documents
// Note the need to pass session
MimeMessage message=new MimeMessage(session);
// Indicate the sender of the message
message.setFrom(new InternetAddress("[email protected]"));
// Indicate the recipient of the message
message.setRecipient(Message.RecipientType.TO,new InternetAddress("[email protected]"));
// Email title
message.setSubject("java issue ");
// The text of the email
//================================= Prepare the image data ===========================
MimeBodyPart image=new MimeBodyPart();
// Pictures need to go through data processing
DataHandler dh=new DataHandler(new FileDataSource("D:\\c\\ picture \\wallhaven-28o276.jpg"));
// stay part Put the data of the processed picture in
image.setDataHandler(dh);
// Here it is part Set up a ID name
image.setContentID("girl.jpg");
// Prepare the data of the text
MimeBodyPart text=new MimeBodyPart();
text.setContent(" This is a text <img src='cid:girl.jpg'>","text/html;charset=UTF-8");
// Describe data relationship
MimeMultipart mm=new MimeMultipart();
mm.addBodyPart(text);
mm.addBodyPart(image);
mm.setSubType("related");
// Set to message , Save changes
message.setContent(mm);
message.saveChanges();
//5. Send E-mail
ts.sendMessage(message,message.getAllRecipients());
// Close the connection
ts.close();
}
}
The email was successfully sent :
2.4.2 Send with attachments
Only the fourth step of email content has been changed
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");/// Set up QQ Mail server
prop.setProperty("mail.transport.protocol","smtp");/// Email protocol
prop.setProperty("mail.smtp.auth","true");// Need to verify user password
//QQ Mailbox needs to be set SSL encryption
MailSSLSocketFactory sf=new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable","true");
prop.put("mail.smtp.ssl.socketFactory",sf);
// Use javaMail Sent by 5 A step
//1. Create a that defines the environmental information needed for the entire application session object
Session session=Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]","klzptmndwkfdchbb");
}
});
// Turn on session Of debug Pattern , In this way, you can see that the program sends Email Operating state
session.setDebug(true);
//2. adopt session obtain transport object
Transport ts=session.getTransport();
//3. Use the username and authorization code of the mailbox to connect to the mail server
ts.connect("smtp.qq.com","[email protected]","klzptmndwkfdchbb");
//4. Create mail : Writing documents
// Note the need to pass session
MimeMessage message=new MimeMessage(session);
// Indicate the sender of the message
message.setFrom(new InternetAddress("[email protected]"));
// Indicate the recipient of the message
message.setRecipient(Message.RecipientType.TO,new InternetAddress("[email protected]"));
// Email title
message.setSubject("test3");
// The text of the email
//================================= Prepare the image data ===========================
MimeBodyPart image=new MimeBodyPart();
// Pictures need to go through data processing
DataHandler dh=new DataHandler(new FileDataSource("D:\\c\\ picture \\wallhaven-28o276.jpg"));
// stay part Put the data of the processed picture in
image.setDataHandler(dh);
// Here it is part Set up a ID name
image.setContentID("girl.jpg");
//================================= Prepare text data ===========================
MimeBodyPart text=new MimeBodyPart();
text.setContent(" This is a text <img src='cid:girl.jpg'>","text/html;charset=UTF-8");
//================================= Prepare attachment data ===========================
MimeBodyPart body1= new MimeBodyPart();
body1.setDataHandler(new DataHandler(new FileDataSource("D:\\c\\ Function extension \\ Mail delivery \\11.txt")));
body1.setFileName("11.txt");
// Describe data relationship
MimeMultipart mm=new MimeMultipart();
mm.addBodyPart(body1);
mm.addBodyPart(text);
mm.addBodyPart(image);
mm.setSubType("mixed");
// Set to message , Save changes
message.setContent(mm);
message.saveChanges();
//5. Send E-mail
ts.sendMessage(message,message.getAllRecipients());
// Close the connection
ts.close();
}
}
Mail sent successfully :
3.javaweb Send E-mail
Now many websites provide user registration function , Usually we receive an email from the registration website after successful registration , This email may contain information such as our registered user name and password, as well as a hyperlink to the activated account . Today we will also implement such a function , Realize sending mail by JavaMail.
First create a maven project , To configure tomcat, Run , Make sure it's OK ; Then create the package structure .
3.1 Front page
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> register </title>
</head>
<body>
<form action="${pageContext.request.contextPath}/RegisterServlet.do" method="get">
user name :<input type="text" name="username">
password :<input type="text" name="pa's's">
mailbox :<input type="text" name="email">
<input type="submit" value=" register ">
</form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>1</title>
</head>
<body>
<h1>xxx Website tips </h1>
${message}
</body>
</html>
3.2 Entity class (Dao layer )
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 + '\'' + '}';
}
/*lombok package , Annotations can be directly generated get、set、 With or without parameters . import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data // There are parametric structures ; @AllArgsConstructor // No arguments structure ; @NoArgsConstructor public class User { private String name; private String password; private String email; }*/
}
3.3 Tool class ( The business layer )
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;
// User experience is very important , Multithreading improves user experience ( Asynchronous processing ), Prevent sending files for too long , The front-end response is too long .
public class Sendmail extends Thread{
// Mailbox used to send mail to users
private String from = "[email protected]";
// Email user name
private String username = "[email protected]";
// The password of the mailbox
private String password = "tvatktjyckcvciga";
// The server address where the mail is sent
private String host = "smtp.qq.com";
private User user;
public Sendmail(User user){
this.user = user;
}
// rewrite run Method implementation , stay run Method to send mail to the specified 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");
// About QQ mailbox , Also set SSL encryption , Add the following code
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
//1、 Create... That defines the environment information required for the entire application Session object
Session session = Session.getDefaultInstance(prop, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
// Sender email user name 、 Authorization code
return new PasswordAuthentication("[email protected]", "tvatktjyckcvciga");
}
});
// Turn on Session Of debug Pattern , So you can see the program sending Email Operating state
session.setDebug(true);
//2、 adopt session obtain transport object
Transport ts = session.getTransport();
//3、 Use the username and authorization code of the mailbox to connect to the mail server
ts.connect(host, username, password);
//4、 Create mail
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from)); // Sender
message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); // The recipient
message.setSubject(" User registration email "); // The title of the email
String info = " Congratulations on your successful registration , Your user name :" + user.getUsername() + ", Your password :" + user.getPassword() + ", Please take good care of , If you have any questions, please contact our customer service !!";
message.setContent(info, "text/html;charset=UTF-8");
message.saveChanges();
//5. Send E-mail
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
3.4servlet( Control layer )
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 {
// Receive user requests , Encapsulated as an object
String username = req.getParameter("username");
String password = req.getParameter("password");
String email = req.getParameter("email");
User user = new User(username,password,email);
// After successful user registration , Send an email to the user
// We use threads to send mail specifically , Prevent time consuming , And the number of people registered on the website is too large ;
Sendmail send = new Sendmail(user);
// Start thread , After the thread starts, it executes run Method to send mail
send.start();
// Registered users
req.setAttribute("message", " Registered successfully , We've sent an email with registration information , Enclosed please find ! If the network is unstable , Maybe we'll get it later !!");
req.getRequestDispatcher("info.jsp").forward(req, resp);
} catch (Exception e) {
e.printStackTrace();
req.setAttribute("message", " Registration failed !!");
req.getRequestDispatcher("info.jsp").forward(req, resp);
}
}
}
rely on :
<!-- Import dependence -->
<dependencies>
<!-- The use of plug-in -->
<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>
<!-- https://mvnrepository.com/artifact/javax.activation/activation -->
<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>
Finally, I received an email :
边栏推荐
- Understanding of CPU buffer line
- 这本数学书AI圈都在转,资深ML研究员历时7年之作,免费电子版可看
- Sword finger offer14 the easiest way to cut rope
- SLF4J 日志门面
- Loan calculator my pressure is high
- Sitescms v3.1.0 release, launch wechat applet
- Flick SQL knows why (10): everyone uses accumulate window to calculate cumulative indicators
- Fabric.js 更换图片的3种方法(包括更换分组内的图片,以及存在缓存的情况)
- [Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [Chapter III exercises]
- 剑指 Offer 17. 打印从1到最大的n位数
猜你喜欢
【历史上的今天】7 月 3 日:人体工程学标准法案;消费电子领域先驱诞生;育碧发布 Uplay
【数据库原理及应用教程(第4版|微课版)陈志泊】【第三章习题】
Dojo tutorials:getting started with deferrals source code and example execution summary
有限状态机FSM
sitesCMS v3.1.0发布,上线微信小程序
[data mining review questions]
OpenHarmony应用开发之ETS开发方式中的Image组件
[problem exploration and solution of one or more filters or listeners failing to start]
stm32和电机开发(从mcu到架构设计)
[colab] [7 methods of using external data]
随机推荐
解决 System has not been booted with systemd as init system (PID 1). Can‘t operate.
Flick SQL knows why (10): everyone uses accumulate window to calculate cumulative indicators
sitesCMS v3.0.2发布,升级JFinal等依赖
[exercice 7] [principe de la base de données]
C graphical tutorial (Fourth Edition)_ Chapter 13 entrustment: what is entrustment? P238
OpenHarmony应用开发之ETS开发方式中的Image组件
Harmonic current detection based on synchronous coordinate transformation
有限状态机FSM
2022-02-09 survey of incluxdb cluster
剑指 Offer 12. 矩阵中的路径
Analysis of the influence of voltage loop on PFC system performance
Flink SQL knows why (12): is it difficult to join streams? (top)
【習題七】【數據庫原理】
Glide question you cannot start a load for a destroyed activity
Create a dojo progress bar programmatically: Dojo ProgressBar
2022-01-27 use liquibase to manage MySQL execution version
Cache penetration and bloom filter
【数据挖掘复习题】
R语言gt包和gtExtras包优雅地、漂亮地显示表格数据:nflreadr包以及gtExtras包的gt_plt_winloss函数可视化多个分组的输赢值以及内联图(inline plot)
[combinatorics] permutation and combination (the combination number of multiple sets | the repetition of all elements is greater than the combination number | the derivation of the combination number