gpt4 book ai didi

java - 读取属性文件的 RestFul Web 服务

转载 作者:行者123 更新时间:2023-12-02 04:35:11 25 4
gpt4 key购买 nike

我有几个 Jersey REST Web 服务,例如 SendPasswordResetPassword,其目的是发送电子邮件。

为了发送电子邮件,我在 tomcat 下配置了一个属性文件,所有这些都工作正常

代码SendPassword.java有点像这样

 @Path("/sendpassword")
public class SendPassword {
@GET
@Produces("application/json")
public String sendPasswordToEmail(@QueryParam("empid") String empid)
throws JSONException
{
try {

SendEmailUtility.sendmail("weqw","2312");

}
catch(Exception e)
{
}
}

SendEmailUtility.java

public class SendEmailUtility 
{
public static String sendmail(String sendemalto,String generatedpwd) throws IOException {
String result = "fail";
File configDir = new File(System.getProperty("catalina.base"), "conf");
File configFile = new File(configDir, "email.properties");
InputStream stream = new FileInputStream(configFile);
Properties props_load = new Properties();
props_load.load(stream);
final String username = props_load.getProperty("username");
final String password = props_load.getProperty("password");
Properties props_send = new Properties();
props_send.put("mail.smtp.auth","true");
props_send.put("mail.smtp.starttls.enable","true");
Transport.send(message);
// Some code to send email
result = "success";
} catch (MessagingException e) {
result = "fail";
e.printStackTrace();
}
return result;
}

}

如您所见,我正在读取网络服务每次调用的属性文件

(由于读取操作的成本有点高),有什么办法可以解决这个问题吗?

您能否让我知道处理此问题的最佳方法是什么?

提前致谢。

最佳答案

有几种方法可以做到这一点,其中一种方法是使 props_load 成为类的私有(private)静态成员并像这样调用它

    public class SendEmailUtility 
{
private static Properties props;

private static Properties getProperties() {
if (props == null) {
File configDir = new File(System.getProperty("catalina.base"), "conf");
File configFile = new File(configDir, "email.properties");
InputStream stream = new FileInputStream(configFile);
props = new Properties();
props.load(stream);
}
return props;
}
public static String sendmail(String sendemalto,String generatedpwd) throws IOException {
String result = "fail";
Properties props_load = getProperties();
final String username = props_load.getProperty("username");
final String password = props_load.getProperty("password");
Properties props_send = new Properties();
props_send.put("mail.smtp.auth","true");
props_send.put("mail.smtp.starttls.enable","true");
Transport.send(message);
// Some code to send email
result = "success";
} catch (MessagingException e) {
result = "fail";
e.printStackTrace();
}
return result;
}

}

我建议的另一种设计是制作一个电子邮件服务类,例如 EmailSender 或 EmailService,然后将其注入(inject) SendPassword 类

@Path("/sendpassword")
public class SendPassword {
@Autowired
EmailService emailService;
@GET
@Produces("application/json")
public String sendPasswordToEmail(@QueryParam("empid") String empid)
throws JSONException
{

关于java - 读取属性文件的 RestFul Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30920182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com