1.首先自己创建一个xml文件,例如:SendMail.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
***** UsersAction配置SendMail相关信息 *****
-->
<SendMail>
<HostName>smtp.exmail.qq.com</HostName>
<SendMailAddress>邮箱的账号</SendMailAddress>
<MailPassword>邮箱的密码</MailPassword>
</SendMail>
2.在工具类SendMail.java中把所用到的变量设置为全局变量
public static String hostName;//设置smtp服务器
public static String sendMailAddress;//设置发送地址
public static String mailPassword;//设置密码
3.让程序自动加载相关配置文件,并且获得xml文件的信息,采用dom4j解析xml文件
private static void initConfig(){
try {
// 开始读取配置文件,并将其中的参数值向默认环境表中进行覆盖
File file = new File(SendMail.class.getClassLoader().getResource("SendMail.xml").getPath());
if (file.exists()) { // 如果可以成功加载配置文件
SAXReader sr = new SAXReader();
Document doc = sr.read(file);
Element root = doc.getRootElement(); // 获得根节点
Element HostName = root.element("HostName");
hostName=HostName.getTextTrim();
Element SendMailAddress = root.element("SendMailAddress");
sendMailAddress=SendMailAddress.getTextTrim();
Element MailPassword = root.element("MailPassword");
mailPassword=MailPassword.getTextTrim();
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static {
initConfig();
}
4.在UsersAction.java类里面直接调用全局变量
sendemail.setHostName(SendMail.hostName);
sendemail.setSendMailAddress(SendMail.sendMailAddress);
sendemail.setMailPassword(SendMail.mailPassword);