0

Jboss 无法将 smtp 服务器配置注入 Session 字段。

我编辑了standalone.xml 文件:

<mail-session jndi-name="java:jboss/mail/MyMail">
        <smtp-server outbound-socket-binding-ref="mail-smtp-my-mail">
               <login name="login" password="passwd"/>
        </smtp-server>
</mail-session>
...
<socket-binding-group ...>
    <outbound-socket-binding name="mail-smtp-my-mail">
        <remote-destination host="my-stmp-server" port="2587"/>
    </outbound-socket-binding>

我的课程有 Session 字段:

@Stateless
public class MailHelper {

    @Resource(mappedName = "java:jboss/mail/MyMail")
    private Session mailSession;

    public String send() {
        MimeMessage m = new MimeMessage(mailSession);
        try {
            m.setRecipients(Message.RecipientType.TO, "g@gmail.com");
            Transport.send(m);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return "...";
    }
}

邮件助手用于jsp页面:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <h1>Hello World!</h1>
    <jsp:useBean id="mailHelper" class="com.MailHelper" scope="session"/>
    <%= mailHelper.send()%>
</body>

每次我在 mailSession 字段中有 null 时。怎么了?

4

1 回答 1

1

MailSession 和出站套接字配置正确。在 SLSB MailHandler 中,java:global/YourProj/MailHelper!youpackage.MailHelper 等下可用,必须有一个注入会话。server.log 中应该有类似的内容:

java:global/TestJSP/MailHelper!example.MailHelper
java:app/TestJSP/MailHelper!example.MailHelper
java:module/MailHelper!example.MailHelper
java:global/TestJSP/MailHelper
java:app/TestJSP/MailHelper
java:module/MailHelper

否则您的项目将不会被部署。但是 mailHelper 在 org.apache.jasper.servlet.JspServlet 的上下文中是一个 JavaBean 而不是 SLSB。你那里没有DI​​。但是您可以通过这种方式手动查找 javax.mail.Session

 public String send(){
    try {
        Context c = new InitialContext();
        session = (Session)c.lookup("java:jboss/mail/MyMail");
        System.out.println();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

或者在标准构造函数中实例化它:

  public MailHelper() {
   ini();
}

void ini(){
    try {
        Context c = new InitialContext();
        session = (Session)c.lookup("java:jboss/mail/MyMail");          
    } catch (Exception e) {
        e.printStackTrace();
    }
}
于 2013-08-09T10:15:29.023 回答