2016-03-24 2 views
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 = "[email protected]"; 
       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("[email protected]")); 
        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

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

я не смог просмотреть мое изображение в любом веб-браузере (google chrome, etcc. Однако его можно просмотреть в браузере java, любая помощь будет отличной.

ответ

1

Пожалуйста, проверьте значение, возвращаемое login.getPic(). Мне кажется, что оно содержит значение, подобное D:\path-to-your-image.ext. login.getPic() должен содержать действительный URL-адрес для изображения, чтобы он отображался в браузере.

Если вы храните файлы изображений вне вашего пути к веб-приложению, вы можете создать сервлет, который считывает файл изображения и передает его на выход ответа. И затем используйте этот URL сервлета в качестве источника для вашего html-изображения, например <img src="/picture/profile.jpg"/>. Используйте taglib <c:url>, чтобы правильно применить путь контекста вашего веб-приложения.

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

так как я могу создать действительный url в моем сервлете? Я понимаю, что браузер не может получить доступ к локальному диску для извлечения и отображения изображения в браузере. Однако как я должен изменить свой сервлет так, чтобы он отображался. –

+0

Я обновил свой ответ выше. –

+0

для тега я просто положил src = "profile/tralala.jpg"? –

Смежные вопросы