我目前正在使用AServletContextListener
来设置Web应用程序中JSP的路径。路径作为上下文参数存储web.xml
在侦听器中,并由侦听器检索:
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
sc.setAttribute("urlOfThisPage", sc.getInitParameter("urlOfThisPage"));
sc.setAttribute("urlOfThatPage", sc.getInitParameter("urlOfThatPage"));
在应用程序servlet中,可以轻松地从中检索特定JSP的路径ServletContext
。
我的问题与以相同方式处理属性文件有关。我在其他StackOverflow页面(如2161045)上阅读了很多。
我是否假设应该由侦听器读取属性文件并将其存储在ServletContext
使用Property
对象中,这是正确的吗?但是如果是这种情况,我将如何从属性文件中检索特定属性?
目前,我正在servlet中使用这种代码来从中获取属性的值ServletContext
。
String url = (String) sc.getAttribute("urlOfThisPage"); // Use ServletContext to get JSP's URL.
但是我不确定如何将其扩展到访问属性文件。
我已经在中尝试了以下方法ServletContextListener
:
Properties properties = new Properties();
properties.setProperty("name", "Akechi Jinsai");
sc.setAttribute("properties", properties);
在servlet中,使用代码:
ServletContext sc = request.getSession().getServletContext();
Properties properties = (Properties) sc.getAttribute("properties");
System.out.println("Here: " + properties.getProperty("name"));
显示“此处:Akechi Jinsai”,但是有没有一种更好的方式来在servlet中获取单个属性而不用这种方式查找内容呢?
只需将属性文件加载到Servlet中,然后将值移入HashMap
并存储为应用程序属性即可。现在,使用JavaServer Pages标准标记库在JSP中对其进行访问。
在Servlet / JSP中阅读有关装入属性文件的更多信息。
样例代码:
JSP :(访问地图的不同方法)
<c:forEach items="${map}" var="entry">
Key="${entry.key}" Value=${entry.value}
</c:forEach>
URL Of This Page = ${map.urlOfThisPage }
URL Of That Page = ${map.urlOfThatPage }
URL Of This Page = ${map['urlOfThisPage'] }
URL Of That Page = ${map['urlOfThatPage'] }
ServletContextListener
public class MyServletContextListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent sc) {
}
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
// load the properties file if needed
// read the path from web.xml as init parameter
Map<String, String> map = new HashMap<String, String>();
map.put("urlOfThisPage", sc.getInitParameter("urlOfThisPage"));
map.put("urlOfThatPage", sc.getInitParameter("urlOfThatPage"));
sc.setAttribute("map", map);
}
}
web.xml:
<context-param>
<param-name>urlOfThisPage</param-name>
<param-value>url</param-value>
</context-param>
<context-param>
<param-name>urlOfThatPage</param-name>
<param-value>url</param-value>
</context-param>
<listener>
<listener-class>com.x.y.z.MyServletContextListener</listener-class>
</listener>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句