在servlet中定义配置文件或库文件

时间:2012-09-05 06:12:22

标签: jsp servlets

首先,我是Servlets和JSP的新手。我正在学习这些我自己的。我有个疑问。 如何在Servlet中创建配置文件或库文件?这意味着我需要将数据库连接保存在一个Servlet中,并希望在整个项目中使用变量。此外,我需要在一个Servlet中创建一些常用函数,并希望在任何需要的地方调用这些函数。

我可以在Servlets中实现这些功能吗?它可能在PHP等其他环境中。但我不知道如何在Servlets中执行这些操作?我花了几天时间搞清楚了。但我无法做到。

请帮我解决这些问题..

3 个答案:

答案 0 :(得分:3)

查看这篇简单的文章 By Oracle

关于如何使用Servlet并配置Servlet!

答案 1 :(得分:2)

是的,你可以实现这一目标,但不能使用servlet。你需要的是定义一个Common类,它将包含所有常用的方法和变量,如下面的那个

public class Common {
  public static final String DEFAULT_LANGUAGE = "en"; //better to have private variables with public setters and getters
  ....
  public static String getDateFormatted(.....) {...}
  ....

}

最好创建一个单独的数据库类来控制数据库交互。让我们说:

public class DBConnection { 
  private Connection dbCon;
  //its more convenient to implement the connect on the no ArgumentCostructor
  ....
  public boolean connect() throws ClassNotFoundException, SQLException {...}
  public ResultSet execSQL(...)throws ClassNotFoundException,SQLException {...}
}

如果要在java类中使用全局参数,只需调用

即可
String formatedDate = Common.getDateFormatted(date);

或者对于db连接内容,您可以调用

DBConnection con = new new DBConnection ();
rs = con.execSQL(sql);

答案 2 :(得分:0)

您可以在web .xml init参数中配置数据库连接参数,例如

<init-param>
    <param-name>dburl</param-name>
    <param-value>jdbc:mysql:///MY_DB</param-value>
</init-param>

使用servlet获取值 String myDbUrl = getServletConfig()。getInitParameter(“dburl”);

您还可以使用tomcat Server.xml文件进行数据库连接。