[英]What am I doing wrong? Trying to use context-param in web.xml with ServletContextListener
I am trying to use init-param in my web-app, and use it together with ServletContextListener. 我正在尝试在Web应用程序中使用init-param,并将其与ServletContextListener一起使用。 This should later be picked up my the servlet and displayed to the user. 稍后应在servlet中拾取它并显示给用户。 I have done everything I can, but I am getting an error. 我已竭尽所能,但出现错误。 Something is wrong and I can't see it. 出了点问题,我看不到。
My web.xml 我的web.xml
<web-app>
<context-param>
<param-name>name</param-name>
<param-value>Abdi</param-value>
</context-param>
</web-app>
My class: 我的课:
@WebListener
public class Developer implements ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent e) {
System.out.println("Destroyed!");
}
@Override
public void contextInitialized(ServletContextEvent e) {
ServletContext cntxt = e.getServletContext();
String name = e.getServletContext().getInitParameter(name);
DevInfo student = new DevInfo(name);
cntxt.setAttribute("student", student);
}
}
Other class: 其他类:
public class DevInfo {
private String name;
public DevInfo (String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Servlet: Servlet:
DevInfo stu = (DevInfo)getServletContext().getAttribute("student");
System.out.println("Developers name is: " + stu.getName());
My error is in the contextInitialized method. 我的错误是在contextInitialized方法中。 "The local variable name may not have been initialized" at e.getServletContext().getInitParameter(name); e.getServletContext()。getInitParameter(name);中的“本地变量名称可能尚未初始化”;
The actual way to get the context-param
's param-value
is to pass the param-name
on the getInitParameter
method: 获取context-param
的param-value
的实际方法是在getInitParameter
方法上传递param-name
:
String name = e.getServletContext().getInitParameter("name");
You forgot to put name
in quotes. 您忘了在引号中加上name
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.