0

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 SAVE_DIR="images";

// 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 + 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);


        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("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.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 image page code)

  <a class="image fit"><img src="<%=login.getPic() %>" alt="" /></a>

I was not able to view my image in any of the web browser(google chrome, etcc. However, it can be viewed in the java browser, any help would be great.

1 Answers1

1

Please check the value returned by the login.getPic(). It seems to me that it contains a value like D:\path-to-your-image.ext. The login.getPic() should contains a valid url for the image to make it show up in the browser.

If you store your image files outside your web application path, you can create a servlet that read the image file and stream it to the response output. And then use this servlet url as the source for your html image, like <img src="/picture/profile.jpg"/>. Use the <c:url> taglib to correctly apply the context path of your web application.

@WebServlet("/picture/*")
public class ProfilePictureServlet extends HttpServlet {
    private static final String PICTURE_PATH = "D:/Pictures/";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String picture = req.getPathInfo().substring(1); // profile.jpg
        BufferedImage bi = ImageIO.read(new File(PICTURE_PATH + picture));
        OutputStream out = resp.getOutputStream();

        resp.setContentType("image/jpg");
        ImageIO.write(bi, "jpg", out);
        out.close();
    }
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
W-S
  • 516
  • 5
  • 14
  • so how can i create a valid url in my servlet? I understand that a browser cannot access a local drive to retrieve and display the image in a browser. However, how should i modified my servlet so that it can display. – James_the_97 Mar 24 '16 at 15:37
  • I've update the my answer above. – W-S Mar 24 '16 at 16:28
  • so as for the tag i just put src = "profile/ tralala.jpg" ? – James_the_97 Mar 25 '16 at 05:11
  • Yes, if your servlet url-pattern is `/profile/*` then every request prefixed with that url-pattern will be handled by the `ProfilePictureServlet` servlet. The image filename `tralala.jpg` will be obtained from the `request.getPathInfo().substring(1)`. – W-S Mar 25 '16 at 05:16
  • however i still could not display my image, if possible take a look at the code I just upload a new set of code with ur code added into it. Thank you – James_the_97 Mar 25 '16 at 06:45
  • I didn't see any changing in your code. Btw, if you create the `ProfilePictureServlet` you can access it like `http://localhost:8080/picture/profile.jpg` it will show the image in your browser. Make sure you also have the `profile.jpg` under the `D:/Pictures` directory, where the servlet will look for the image file. – W-S Mar 25 '16 at 07:38
  • @BalusC I didn't use any `getRealPath()` method in the code above. Which line in the answer that indicate that? – W-S Mar 25 '16 at 22:53
  • Sorry, I misread that. – BalusC Mar 27 '16 at 15:34