package servlet;
import java.io.File;
import java.util.List;
import java.util.Iterator;
import java.util.*;
import java.io.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.Security;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Random;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import database.DBAO;
import model.Login;
/**
* Servlet implementation class SignupServlet
*/
@MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
maxFileSize=1024*1024*10, // 10MB
maxRequestSize=1024*1024*50)
@WebServlet("/SignupServlet")
public class SignupServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
private static final String SAVE_DIR="images";
/**
* @see HttpServlet#HttpServlet()
*/
public SignupServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String savePath = "C:" + File.separator + SAVE_DIR;
File fileSaveDir=new File(savePath);
if(!fileSaveDir.exists()){
fileSaveDir.mkdir();
}
Random rand = new Random();
int num = rand.nextInt(900000) + 100000;
String Password = Integer.toString(num);
String Name = request.getParameter("name");
String Email = request.getParameter("email");
String UserType = request.getParameter("usertype");
String strDOB = request.getParameter("dob");
String Gender = request.getParameter("gender");
Part part = request.getPart("file");
String fileName = part.toString();
String filePath = savePath + File.separator + fileName;
part.write(savePath + File.separator + fileName);
java.sql.Date d;
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date d2 = null;
try{
d2 = sdf.parse(strDOB);
} catch (ParseException e1) {
e1.printStackTrace();
}
d = new java.sql.Date(d2.getTime());
DBAO dbao = null;
Login login = null;
try {
// configuration for mail
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = System.getProperties();
String host = "smtp.gmail.com";
String port = "465";
String fromEmail = "lookeverybodysg@gmail.com";
String username = "lookeverybodysg";
String password = "catdog1234";
props.put("mail.smtp.user", fromEmail);
props.put("mail.smtp.host", host);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.fallback", "false");
Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("lookeverybodysg", "catdog1234"); // username and password
}
});
mailSession.setDebug(true);
Message mailMessage = new MimeMessage(mailSession);
dbao = new DBAO();
if (dbao.emailExists(Email)){
request.setAttribute("Name", Name);
request.setAttribute("Email", Email);
request.setAttribute("UserType", UserType);
request.setAttribute("strDOB", strDOB);
request.setAttribute("Gender", Gender);
request.setAttribute("Pic", filePath);
response.setContentType("text/html");
out.println("<script type=\"text/javascript\">");
out.println("alert('The email you have used has already been regietered.');");
out.println("location='Login.jsp#signup';");
out.println("</script>");
return;
}else{
login = new Login();
login.setName(Name);
login.setEmail(Email);
login.setPassword(Password);
login.setUserType(UserType);
login.setDOB(d);
login.setGender(Gender);
login.setPic(filePath);
boolean isUserSaved = dbao.saveNewUser(login);
if (isUserSaved){
mailMessage.setFrom(new InternetAddress("lookeverybodysg@gmail.com"));
mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(Email));
mailMessage.setSubject("Thank You for signing up to LookEveryBody!");
mailMessage.setContent("Email :" + Email + "<br> Password :" + Password, "text/html");
Transport transport = mailSession.getTransport("smtps");
transport.connect (host, 465, username, password);
transport.send(mailMessage);
response.setContentType("text/html");
out.println("<script type=\"text/javascript\">");
out.println("alert('Your accout has been successfully created, please go to your email to get your password.');");
out.println("location='Login.jsp';");
out.println("</script>");
return;
}
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}
我可以将路径存储到MySQL中,但名称图像文件很奇怪,例如链接:SQL
我理解错误特别在行:
Part part = request.getPart("file");
String fileName = part.toString();
我非常感谢任何帮助,因为我现在正在进行最后一年的项目。
答案 0 :(得分:1)
由于toString()
类中的Part
方法,fileName很奇怪。此类使用Object
类的默认实现,该类打印特定于jvm的实例ID。
你的Part类实现可能有返回文件名的公共方法。试试这个:
String fileName = part.getSubmittedFileName(();
而不是:
String fileName = part.toString();
除此之外,你总是可以让人类可读fileName
将其他属性引入request
。
另外考虑自己生成文件名 - 例如,将UUID
作为fileName
。生成UUID文件名有助于防止文件系统中的名称冲突(如果用户提交两个名称相同的不同文件会怎么样?)
答案 1 :(得分:0)
我设法通过添加此代码来解决错误:
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
return "";
}
但是,如果我想托管这个web应用程序,我该如何更改路径,以便它存储在我的Web项目的web-content文件夹中。