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>
我的班级有会话字段:
@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。有什么问题?
答案 0 :(得分: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的Context中是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();
}
}