0

SignupServlet

package servlet;

import database.DBAO;
import model.Login;

 @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 DIR = "Nanyang Polytechnic/FYPJ Project2/FYPJ/WebContent/profile";
//  private static final String DIR = "FYPJ PROJECT/FYPJ/WebContent/profile";
private static final String SAVE_DIR="images";




private static final int DEFAULT_BUFFER_SIZE = 10240;
// configuration to get Image file name
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 "";
}
/**
 * @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();


        //configuration for declaring file saving path  

        //String relativeWebPath = "/profile";
        //String savePath =   getServletContext().getRealPath(relativeWebPath);
        String savePath = "D:" + File.separator + SAVE_DIR ;
        String path = File.separator + SAVE_DIR;

        File fileSaveDir=new File(savePath);
        if(!fileSaveDir.exists()){
              fileSaveDir.mkdir();
          }



        // Configuration to generate Random passsword  
        Random rand = new Random();
        int num = rand.nextInt(900000) + 100000;
        String Password = Integer.toString(num);
        //End


        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");
        String address = request.getParameter("address");



        Part part = request.getPart("file");
        String fileName = extractFileName(part);

        String filePath = savePath + File.separator + fileName;
        part.write(savePath + File.separator + fileName);

        String imageName = fileName;



        String picture = request.getPathInfo().substring(1); // profile.jpg
        BufferedImage bi = ImageIO.read(new File(savePath + picture));
        OutputStream outs = response.getOutputStream();

        response.setContentType("image/jpg");
        ImageIO.write(bi, "jpg", outs);
        outs.close();




        /*FileInputStream fis = new FileInputStream(new File(filePath));                
        BufferedInputStream bis = new BufferedInputStream(fis);    
        response.setContentType("image/jpeg");
        BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream());
        for (int data; (data = bis.read()) > -1;) {
               output.write(data);
             }             */


        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;




        //configuration for url for image
        /*FileInputStream fis = new FileInputStream(filePath);
        BufferedInputStream bis = new BufferedInputStream(fis); 
        BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream());
        for (int data; (data = bis.read()) > -1;){
            output.write(data);
        }
         */


        try {      


            // configuration for email
            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);
                    request.setAttribute("PicName", imageName);
                    request.setAttribute("Address", address);


                    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);
                    login.setPicName(imageName);
                    login.setAddress(address);

                    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();
        }
}
}

HairstylistProfile.jsp (display page)

 <a class="image fit"><img src="/images/<%=login.getPicName()%>" alt=""   height="100%" /></a>  

I am getting this result: Image not being display(sample) enter image description here

Even though the path of the image is being stored in the folder and path being stored in mysql I still could not retrieve and display the image. Any help would be greatly appreciated!!! Emergency!!!

Prafulla Kumar Sahu
  • 9,321
  • 11
  • 68
  • 105

1 Answers1

0

If an image does not display most likely the path is not correct. I would assume your page "HairstylistProfile.jsp" is located within the WebContent folder and that within that folder you have a "images" folder.

Have you tried deleting the slash at the beginning of the src field in the img tag?

Angelo Oparah
  • 673
  • 1
  • 7
  • 18
  • yeah i have try deleting the slash but to no avail, it still could not display – James_the_97 Mar 25 '16 at 17:12
  • Are you using eclipse by any chance? Sometimes it does not update the content of folders automatically and you need to right click and hit refresh or restart the application. Other than that I wouldn't know what's going on – Angelo Oparah Mar 25 '16 at 17:20