【问题标题】:Submitting jsp form to servlet generates blank output向servlet提交jsp表单生成空白输出
【发布时间】:2014-11-09 11:59:49
【问题描述】:

我正在尝试从包含文本框和提交按钮的 jsp 表单发送邮件。当用户在文本框中输入电子邮件 ID 并单击提交按钮时,将调用 servlet 页面。这里的 url 被更改为 servlet url 并且它生成空白页面并且邮件不会被发送。

这是我的 demo1.jsp

    <%-- 
    Document   : demo1
    Created on : 14 Sep, 2014, 10:08:26 AM
    Author     : KuNaL-IT
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%--<%@page import="java.io.*,java.util.*,javax.mail.*,java.util.Properties"  %>
<%@page import="javax.mail.internet.*,javax.activation.*" %>
<%@page import="javax.servlet.http.*,javax.servlet.*" %>--%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <div>
            <form method="post" action="/BloodDirectory/mail_servlet">
                Mail id: <input type="text" name="txtmail">
                <input type="submit" value="Submit">
            </form>
        </div>
    </body>
</html>

我的 Servlet 文件 mail_servlet.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package test;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.lang.System.out;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author KuNaL-IT
 */
public class mail_servlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, Exception {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {

            mail.sendMail(request.getParameter("txtmail"));
            out.println(request.getParameter("txtmail"));
            response.sendRedirect("demo1.jsp");
//out.close();
        }
        catch(Exception e)
        {
            out.println("error in mail"+e);
        }
        finally
        {
            out.close();
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (Exception ex) {
            Logger.getLogger(mail_servlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);            
        } catch (Exception ex) {
            Logger.getLogger(mail_servlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

And sendmail method is defined in <b>mail.java</b>
<code>
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package test;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author KuNaL-IT
 */
public class mail {

    public static void sendMail(String e_mail) throws Exception {
        String sender = "kunal.k.kakkad@gmail.com";
        String pass = "abcdefghijkl";
        String rec = e_mail;
        String msg = "Hello This is sample test mail...";
        String sub = "Test Subject";
        // System.out.println(rec);
        Properties props = new Properties();

        props.put("mail.transport.protocol", "smtps");
        props.put("mail.smtps.host", "smtp.gmail.com");
        props.put("mail.smtps.auth", "true");
        // props.put("mail.smtps.quitwait", "false");
        Session mailSession = Session.getDefaultInstance(props);
        mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();
        MimeMessage message = new MimeMessage(mailSession);
        message.setSubject(sub);
        message.setContent(msg, "text/plain");
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(rec));
        transport.connect("smtp.gmail.com", 465, sender, pass);
        transport.sendMessage(message,
                message.getRecipients(Message.RecipientType.TO));
        System.out.println(" message send");
        transport.close();
    }

}

我已经导入了 mail.jar、activation.jar 库。 现在请指导我在哪里犯错? 请帮我通过它发送邮件。

【问题讨论】:

    标签: java jsp servlets


    【解决方案1】:

    使用 gmail 服务器尝试此代码

    public static void sendMail(String uEmail) 抛出异常 { 属性properties=new Properties();

        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.socketFactory.port", "465");
        properties.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.port", "587");
    
        Session session = Session.getDefaultInstance(properties,  
                   new javax.mail.Authenticator() {  
                   protected PasswordAuthentication getPasswordAuthentication() {  
                   return new PasswordAuthentication("yourEmail","yourpassword");//change accordingly  
                   }  
                  });
    
        MimeMessage message=new MimeMessage(session);
        try {
            InternetAddress headers=new InternetAddress();
            message.setFrom(new InternetAddress("youremail"));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(uEmail));
            message.setSubject("Welcome \n your email:"+uEmail);
    
    
            message.setText(html, "UTF-8", "html");
    
            Transport.send(message);
    System.out.println("msg success ");
        } catch (AddressException e) {
    
            e.printStackTrace();
        } catch (MessagingException e) {
    
            e.printStackTrace();
        }
    
    
    }
    

    【讨论】:

    • 使用gmail服务器是指使用gmail账号吗?
    • yes ,yourEmail and password > return new PasswordAuthentication("yourEmail","yourpassword");//这里也相应更改 message.setFrom(new InternetAddress("youremail"));
    • 我得换三个地方对吧? 1) 你的邮箱 2) 你的密码 3) 你的邮箱
    【解决方案2】:

    决定是要写入 servlet 中的响应还是重定向到 jsp...你不能同时做。

    即只有在发送邮件失败的情况下才进行标头设置和写入。

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, Exception
    {
        try
        {
            mail.sendMail(request.getParameter("txtmail"));
            response.sendRedirect("demo1.jsp");
        }
        catch(Exception e)
        {   
            try 
            {
              PrintWriter out = response.getWriter();
              response.setContentType("text/html;charset=UTF-8");
               out.println(request.getParameter("txtmail"));
               out.println("error in mail"+e);
            }
            catch(Exception ew) { /* error writing to out */ }
        }
    }
    

    【讨论】:

    • 实际上我正在尝试其中任何一个,只是忘记删除或评论一个代码。我的主要关注点是发送邮件,无论它是重定向还是显示一些消息。
    • @kunalkakkad,我看到您尝试了两种方式,但是一旦您开始写入响应和设置标题等,您就无法重定向。查看我对答案的更新。
    • 好的,那么是否按照您所做的更改代码可以解决我的问题?
    • @kunalkakkad,它可能无法解决发送邮件的任何问题,但你不应该再看到空白页了。
    • @kunalkakkad,您编译、重新启动应用程序(或 Tomcat 服务器)?也许你还需要清除缓存。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    相关资源
    最近更新 更多