在jsp上使用java函数会导致错误

时间:2013-06-04 18:21:56

标签: java apache jsp tomcat server-side

我正在做一个学校项目,我可以使用这些代码的一些帮助:     我正在尝试在java页面上调用此方法:

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

package Test;
public class SendMail {

    public static void () {

        final String username = "";
        final String password = "";

        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
          });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("shov.rz@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("shov.rz@gmail.com"));
            message.setSubject("Testing Subject");
            message.setText("Dear Mail Crawler,"
                + "\n\n No spam to my email, please!");

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

我在jsp页面上调用此函数:

<%@ page language="java" contentType="text/html; charset=windows-1255"
    pageEncoding="windows-1255"%>
    <%@page import="Test.SendMail" 
       SendMail.test(); %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<title>Insert title here</title>
</head>
<body>

</body>
</html>

现在导入了java类,但是eclipse拒绝运行这个程序。 我必须补充一点,我正在使用带有apache tomcat的eclipse galileo。 我做错了什么?

3 个答案:

答案 0 :(得分:2)

我怀疑这是问题所在:

charset=windows-1255

我建议您改用UTF-8。它会更便携。

(没有明显的迹象表明你甚至 从页面调用该方法。)

顺便说一句,目前你有一个与你的同名同名的方法 - 我强烈强烈阻止你这样做。除了其他任何东西,Java约定都使用camelCase作为方法名称。

答案 1 :(得分:1)

成功编译代码后,将其放在web-inf / classes /文件夹下。 将您需要的所有jar文件放在web-inf / lib文件夹下。

在jsp页面中你应该有这个

......
&LT; %@ page import =“test.SendMail”%&gt;

&LT;% //在这里调用函数

SendMail.send();

%GT;
.....

答案 2 :(得分:1)

您似乎正在尝试调用名为test()的方法。您的类有一个名为send()的方法。

此外,由于它是一个静态方法,因此您不需要该类的实例来调用它。只需致电SendMail.send();