每分钟读取.properties文件

时间:2014-07-31 07:12:34

标签: java servlets properties

我做了一个小任务。我的任务是从servlet中的.properties文件中读取消息,然后将其传递给jsp。我做的。 现在我需要每分钟阅读.properties个文件。 我不知道该怎么做。 有人能帮助我吗?

这是我的课程: MessageController

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MessageController extends HttpServlet {
    private Messenger messenger;

    @Override
    public void init() throws ServletException {
        messenger = new Messenger();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("message", messenger.getMessage("POST", request.getParameter("username"), getServletContext()));
        request.getRequestDispatcher("/result.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        getServletContext().getAttribute("abc");
        request.setAttribute("message", messenger.getMessage("GET", request.getParameter("username"), getServletContext()));
        request.getRequestDispatcher("/result.jsp").forward(request, response);
    }
}

Messeger(读取属性文件和表单消息):

import java.io.IOException;
import java.text.MessageFormat;
import java.util.Properties;

public class Messenger{
    private static final String MESSAGE_PATH = "/WEB-INF/properties/message.properties";

    public String getMessage(String requestType, String username, javax.servlet.ServletContext context) {
        Properties properties = readPropertiesFile(context);
        String message = formMessage(username, requestType, properties);
        return message;
    }

    private Properties readPropertiesFile(javax.servlet.ServletContext context){
        Properties properties = new Properties();
        try {
            properties.load(context.getResourceAsStream(MESSAGE_PATH));
        } catch (IOException exception) {
        }
        return properties;
    }

    private String formMessage(String username, String requestType, Properties properties){
        if(requestType == null) requestType = "Unknown";
        if(username == null || username.isEmpty()) username = "Unnamed";
        String message = MessageFormat.format(properties.getProperty("text"), username, requestType);
        return message;
    }
}

3 个答案:

答案 0 :(得分:1)

如果您的用例是从属性文件返回最新的值,您可以考虑使用Apache Commons Configuration及其FileChangedReloadingStrategy。

使用FileChangedReloadingStrategy,一旦访问配置(基于属性文件的修改日期),就会检查属性文件的修改。如果检测到更改,则会将属性文件加载到配置中。

请参阅http://commons.apache.org/proper/commons-configuration/userguide/howto_filebased.html

这将确保属性始终反映文件中给出的值。无需定义计时器或使用计划框架。

答案 1 :(得分:0)

您可以使用ServletContextListener和Timer来实现此目的。 只需创建Listener:

public class PropertiesListener implements ServletContextListener {

        @Override
        public void contextInitialized(ServletContextEvent sce) {
            Timer time = new Timer();
            TimerTask readPropertiesTask = new TimerTask() {
                @Override
                public void run() {
                    //read from properties
                }
            };
            time.schedule(readPropertiesTask, 0, 60000); 
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce) {}
}

并在web.xml中注册

<listener>
    <listener-class>PropertiesListener</listener-class>
</listener>

答案 2 :(得分:0)

如果你使用spring,你可以使用一个简单的触发器bean,它可以调用一个处理读取porperties文件的方法。如果您愿意,可以使用java中的org.apache.commons.configuration.PropertiesConfiguration来管理为您加载属性文件。

<!-- Class that handles file reading -->
<bean id="propertyFileReader" class="org.myCompany.PropertyFileReader">
</bean>

<!-- Quartz job beans -->
<bean id="propertyFileReaderJobDetail"
    class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
    <property name="targetObject" ref="propertyFileReader" />
    <property name="targetMethod" value="runLoadPropertiesFile" /> <!-- Method in your class you want to run -->
    <property name="concurrent" value="false" />
</bean>
<bean id="propertyFileReaderJobDetailSimpleTrigger"
    class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
    <property name="jobDetail" ref="propertyFileReaderJobDetail" />
    <property name="startDelay" value="60000" />
    <property name="repeatInterval" value="60000" /><!-- every minute -->
</bean>

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="triggers">
        <list>
            <ref bean="propertyFileReaderJobDetailSimpleTrigger" />
        </list>
    </property>
</bean>

现在你的java代码

public class PropertyFileReader
{
    private PropertiesConfiguration configuration;

    public PropertyFileReader() 
    {
        configuration = new PropertiesConfiguration("my property file location");
        configuration.addConfigurationListener(new ConfigurationListener()
        {
            @Override
            public void configurationChanged(ConfigurationEvent event)
            {
                 // Do what needs to be done here
            }
        });
    }

    /**
    * Method called by quartz timer for reloading properties file
    */
    public void runLoadPropertiesFileg()
    {
        // Check if properties have changed.
        // In this example I am using apache PropertiesConfiguration.
        // Performs a reload operation if necessary. Events will be passed to 
        //configuration listeners.
        configuration.reload();
    }
}