當使用註釋而不是web.xml文件時,如何處理通常可從ServletConfig對象讀取的Servlet init/config參數?即在Servlet規範3.0下傳遞servlet配置參數
@WebFilter("/sample")
public class MyServlet {
public void init() throws ServletException {
String value = getServletConfig().getInitParameter("key");
// or
value = getServletContext().getInitParameter("key");
}
}
或在濾波器的情況下:
public class MyFilter implements Filter {
public void init (FilterConfig filterConfig) throws ServletException {
filterConfig.getInitParameter("key");
}
}
更新:我知道你可以在註釋硬編碼的配置參數,但我不想硬編碼的配置設置到代碼。例如,這個servlet不能被兩個應用程序之間共享:
@WebFilter("/sample", initParams = {@InitParam(name = "database_host", value = "blah.com")})
public class MyServlet {
public void init() throws ServletException {
String value = getServletConfig().getInitParameter("database_host");
}
}
我不認爲這裏有任何中間立場,無論是使用web.xml還是註釋。 – Hiro2k