【问题标题】:Passing parameter to web.xml from .txt file从 .txt 文件将参数传递给 web.xml
【发布时间】:2017-01-25 06:31:55
【问题描述】:
如何从 Session.txt 中读取值并将该值传递给 web.xml?
我正在尝试通过将 Session.txt 文件放在项目文件夹之外并将值读取到 web.xml 来为 Java Web 应用程序设置会话超时。
<session-config>
<session-timeout>Value read from Session.txt</session-timeout>
</session-config>
Session.txt
60
【问题讨论】:
标签:
java
web.xml
session-timeout
【解决方案1】:
想象一下这是你的 web.xml 文件
<session-config>
<session-timeout>Value read from Session.txt</session-timeout>
</session-config>
这段java代码替换标签值
如果需要,您可以使用更高效的正则表达式或 XML 解析器
String str = "<session-config>this it to be replaced</session-config>";
System.out.println(str.replaceAll("(?<=<session-config>)(.*?)(?=</session-config>)", "replacement of value read from text file"));
这段代码可以帮助你阅读文本文件
String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
System.out.println(content);//replaceable content
【解决方案2】:
我认为您不能修改 web.xml 文件以在部署应用程序时替换某些配置。根据您的 web.xml 配置,首先创建一个 ServletContext,它允许 servlet 与托管您的应用程序的容器进行通信。我认为没有办法从您的 web.xml 文件中更改配置。为了解决您的问题,您可以配置侦听器以接收上下文生命周期事件并执行某些一次性初始化,例如从外部文件读取值等。
您可以做的一件事是以编程方式设置会话超时值。要从外部文件中读取值,您可以使用 servlet 上下文侦听器初始化参数从文件中读取值并将其存储在某个单例实例中 -
<listener>
<display-name>ContextLoader</display-name>
<listener-class>com.simple.web.app.ContextLoader</listener-class>
</listener>
<context-param>
<param-name>SessionTimeoutFile</param-name>
<param-value>file_location</param-value>
</context-param>
HttpSession session = request.getSession();
session.setMaxInactiveInterval(value_read_from_text_file);
public class ContextLoader implements ServletContextListener {
/**
* Default constructor.
*/
public ContextLoader() {
// TODO Auto-generated constructor stub
}
/**
* @see ServletContextListener#contextDestroyed(ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent arg0) {
}
/**
* @see ServletContextListener#contextInitialized(ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent arg0) {
ServletContext context = arg0.getServletContext();
System.out.println(context.getInitParameter("SessionTimeoutFile"));
WebProperties.INSTANCE.init(context.getInitParameter("SessionTimeoutFile"))
}
public enum WebProperties {
INSTANCE;
private static Properties PROPERTIES;
public void init(String filePath) {
InputStream inputStream;
try {
inputStream = new FileInputStream(filePath);
if(inputStream != null) {
PROPERTIES = new Properties();
try {
PROPERTIES.load(inputStream);
System.out.println(PROPERTIES.get("value"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public String getConfigurationValue(String key) {
return PROPERTIES.getProperty(key);
}
}
然后您可以通过 WebProperties 访问它在您的应用程序中使用它 -
long sessionValue = Long.parseLong(WebProperties.INSTANCE.getConfigurationValue("value"));
HttpSession session = request.getSession();
session.setMaxInactiveInterval(sessionValue);