将jsp表单提交给servlet会生成空白输出

时间:2014-09-15 21:03:17

标签: java jsp servlets

我正在尝试从包含文本框和提交按钮的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>

<%-- 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>

}

/*
 * 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>

}

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

2 个答案:

答案 0 :(得分:0)

决定是否要写入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 */ }
    }
}

答案 1 :(得分:0)

使用gmail服务器

尝试此代码

public static void sendMail(String uEmail)throws Exception {         属性property = 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();
    }


}