|
How to work with ServletContext initilization parameters |
|
|
This J2EE tip describes a method of handling servletcontext initialization
parameter. Context initialization parameters may be used as the basis of
data that is made available to all servlets and JSP pages. Each web application
consists of one ServletContext, which can be used as share resources (data
stored in ServletContext)
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class ContextInitParameters extends HttpServlet {
ServletConfig config ;
public void init(ServletConfig config)throws ServletException {
this.config = config;
super.init(config);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException , IOException {
try {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
ServletContext application = config.getServletContext();
String driverclass =
application.getInitParameter("driverclass");
String jdbcURL = application.getInitParameter("jdbcURL");
String user = application.getInitParameter("user");
String password = application.getInitParameter("pass");
Class.forName(driverclass);
Connection con = DriverManager.getConnection(jdbcURL);
String query = "insert into dept values(50,'Developing','India')";
Statement stmt = con.createStatement();
int i = stmt.executeUpdate(query);
if(i==0) {
out.println("Not Inserted");
} else {
out.println("Values Inserted");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
|
Here is the web.xml for the servlet. Here one context-param
can hold only one value:
<web-app>
</web-app>
<context-param>
<param-name>driverclass</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</context-param>
<context-param>
<param-name>jdbcURL</param-name>
<param-value>jdbc:oracle:thin:@myhost:1521</param-value>
</context-param>
<context-param>
<param-name>user</param-name>
<param-value>scott</param-value>
</context-param>
<context-param>
<param-name>pass</param-name>
<param-value>tiger</param-value>
</context-param>
<servlet/>
<servlet-mapping/>
</web-app>
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.