当使用注释而不是 web.xml 文件时,您如何处理通常可以从 ServletConfig 中读取的 servlet init/config 参数?目的?即
@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");
}
}
最佳答案
@WebServlet(name = "TestServlet", urlPatterns = {"/test"},
initParams = {@WebInitParam(name="key", value="value")})
public class TestServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String key= getInitParameter("key");
}
}
编辑:
要回答您更新的问题,您有两个选择:
使用基于
web.xml
的初始化参数的旧模式只需在另一个项目中创建一个 servlet 的虚拟扩展(子类)并分配新的初始化参数。
关于java - 在 Servlet 规范 3.0 下传递 servlet 配置参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12907232/