2012-12-11 45 views
1

我必須根據環境設置初始化參數到一個servlet,而不是通過web.xml中,但通過代碼, 但我的Servlet版本設置初始化參數是不是3.0的,所以我不能使用這個 http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#setInitParameter%28java.lang.String,%20java.lang.String%29在Servlet

我沒有訪問servlet代碼,所以我正在寫一個新的servlet來擴展它,我想通過java代碼添加初始化參數..任何建議?

<servlet> 
<servlet-name>abc</servlet-name> 
<servlet-class>abc</servlet-class> 
<init-param> 
<param-name>abc</param-name> 
<param-value>localhost:2001</param-value> 
</init-param> 
<load-on-startup>1</load-on-startup> 
</servlet> 

有沒有辦法通過擴展的servlet ABC和設置屬性的servlet配置上面做的事情(添加的init-PARAMS)(覆蓋的init())?

+0

你能更具體?包裝Servlet的ServletFilter將是一個解決方案。 –

+0

編輯我的問題 – mjamal14

+0

@ mjamal14 - 你可以繼承或裝飾你不能編輯的servlet嗎? – McDowell

回答

3

我推翻GenericServlet類的方法調用getInitParameter,我能解決我的問題..

@Override 
public String getInitParameter(String name) { 

//Get initparams here 
    return "MyInitParams"; 
} 
1

看看下面的代碼可以幫助你

import java.io.IOException; 
import java.util.Properties; 

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

/** 
* Servlet implementation class HelloWorld 
*/ 
public class HelloWorld extends HttpServlet { 
    private static final long serialVersionUID = 1L; 

    ServletContext context; 

    /** 
    * @see HttpServlet#HttpServlet() 
    */ 
    public HelloWorld() { 
     super(); 
     // TODO Auto-generated constructor stub 
    } 

    public void init(ServletConfig config) throws ServletException { 
     // Do required initialization 
     Properties prop = new Properties(); 
     try { 
      prop.load(getServletContext().getResourceAsStream(
        "/WEB-INF/properties/sample.properties")); 
      context.setAttribute("abc", prop.getProperty("abc")); 
     } catch (Exception e) { 
      // TODO: handle exception 
      System.out.println(e); 
     } 
    } 

    /** 
    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse 
    *  response) 
    */ 
    protected void doGet(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException { 
     // TODO Auto-generated method stub 
    } 

    /** 
    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse 
    *  response) 
    */ 
    protected void doPost(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException { 
     // TODO Auto-generated method stub 
    } 

}