日期:2014-05-20  浏览次数:20925 次

很恼火,getInitParameter 总取不到值
java 代码
Java code

package com.nong;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CreateDBServlet extends HttpServlet{
    private String url;
    private String user;
    private String password;
    String driverClass;
    String s1;
    public void init() throws ServletException
    {
         
        s1=this.getInitParameter("servletParam");  
         
    }
    
    public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
    {  
         
        
          res.setContentType("text/html"); 
          PrintWriter out = res.getWriter(); 
         
          String s2 = getServletContext().getInitParameter("webParam");  
          out.println("s1"+s1);  
          out.println("<br>");
          out.println("s2"+s2); 
          out.flush(); 
          out.close();
        
    }
    
    public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
    {
        this.doGet(req,res);
        
    }
    
}




xml 代码
XML code

<?xml version="1.0" encoding="UTF-8"?>  
<web-app id="WebApp_ID" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  

<context-param>  
<param-name>webParam</param-name>  
<param-value>aaa</param-value>  
</context-param>  

<servlet>  
<servlet-name>test</servlet-name>  
<servlet-class>Test</servlet-class>  
</servlet>  

<init-param>  
<param-name>servletParam</param-name>  
 <param-value>bbb</param-value>  
</init-param>  


 <servlet-mapping>  
<servlet-name>test</servlet-name>  
 <url-pattern>/test</url-pattern>  
</servlet-mapping>  

  <servlet>
        <servlet-name>my</servlet-name>
        <servlet-class>com.nong.CreateDBServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>my</servlet-name>
        <url-pattern>/my</url-pattern>
    </servlet-mapping>

</web-app>  



结果:
s1null 
s2aaa 


谢谢

------解决方案--------------------
getServletContext()
------解决方案--------------------
你把<init-param>的定义放在所有<servlet>之前,
是不是servlet先加载,才到<init-param>啊。。
------解决方案--------------------
this = servlet in your programm

getInitParameter is method of context, not of a servlet.

clear?