Servlet配置参数返回空值

时间:2016-07-07 20:11:19

标签: java servlets

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class XmlServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter write = response.getWriter();
    HttpSession session = request.getSession();
    ServletContext context=request.getServletContext();

    String userName = request.getParameter("userName");
    if(userName!=""&&userName!=null){
    session.setAttribute("savedUserName",userName);
    context.setAttribute("savedUserName",userName);
    }
    write.println("Request parameter has username as "+userName);
    write.println("Session parameter has username as "+session.getAttribute("savedUserName"));
    write.println("Context parameter has username as "+context.getAttribute("savedUserName"));
    write.println("Init parameter has default username as "+ getServletConfig().getInitParameter("defaultName"));

这是我的java servlet代码,我试图打印通过以下web.xml文件传递的servlet配置参数值。

<display-name>SimpleServletProject</display-name>
<servlet><servlet-name>xmlServlet</servlet-name>
<servlet-class>myservletpackage.XmlServlet</servlet-class>
<init-param>
<param-name>defaultName</param-name>
<param-value>Chris Jordan</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>xmlServlet</servlet-name>
<url-pattern>/xmlServletPath</url-pattern>
</servlet-mapping>
</web-app>

但是在运行config参数时,值为null。任何人都可以告诉我做错了什么?

1 个答案:

答案 0 :(得分:0)

您是否在Web容器/服务器运行时添加了init参数 ?如果服务器已在运行,请重新启动它。

引自“Head First Servlets&amp; JSP”一书。

  

servlet init参数只读取 ONCE - 当Container时   初始化servlet。 ...当Container创建一个servlet时,它   读取DD并为ServletConfig创建名称/值对。   Container 从不再次读取init参数!一旦   参数在ServletConfig中,它们不会再被读取   直到/除非你重新部署 servlet。