File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Servlets and the fly likes  NullPointerException on getServletContext Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark " NullPointerException on getServletContext" Watch " NullPointerException on getServletContext" New topic
Author

NullPointerException on getServletContext

mark reusen
Greenhorn

Joined: Oct 20, 2010
Posts: 22
Hi,


statement:
public void establishConnection () throws ServletException, IOException {
ServletContext context = getServletContext();

which I call from a different servlet:
connect.establishConnection();

returns a NullPointerException
java.lang.NullPointerException
at javax.servlet.GenericServlet.getServletContext(GenericServlet.java:160)
at database.ConnectPostcode.establishConnection(ConnectPostcode.java:30)

can anybody tell me why this occurs?
this is all the source which makes the connection to the databse....

public class ConnectPostcode extends HttpServlet{
private Connection con = null;
private String driverName;
private String databaseName;
private String userName;
private String passWord;
/**
* establishConnection()
*/
public void establishConnection () throws ServletException, IOException {
ServletContext context = getServletContext();
Properties properties = (Properties) context.getAttribute("properties");
driverName = properties.getProperty("driver_name");
databaseName = properties.getProperty("database_postcode");
userName = properties.getProperty("user_postcode");
passWord = properties.getProperty("password_postcode");
try {
// Load the database driver for jdbc
Class.forName(driverName).newInstance();
// Get a connection to the database
con = DriverManager.getConnection(databaseName, userName, passWord);
if(!con.isClosed())
System.out.println("Successfully connected to " + databaseName);
context.setAttribute("postcodeconnection", con);
} catch (Exception e) {
System.out.println("connection to " + databaseName + " unsuccesfull");
System.out.println("SQLException: " + e.getMessage());
e.printStackTrace();
throw new ServletException(e);
}
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
ServletContext context = getServletContext();

Properties properties = (Properties) context.getAttribute("properties");
String driverName = properties.getProperty("driver_name");
String databaseName = properties.getProperty("database_postcode");

out.write("\nThe driverName is " + driverName);
out.write("\nThe databasePostcode is " + databaseName);
try {
con = (Connection) context.getAttribute("postcodeconnection");
if(!con.isClosed())
out.write("\nDatabase still open");
if(con.isClosed())
out.write("\nDatabase closed");
} catch (SQLException e) {
/*log exception */
System.out.println("Database " + databaseName + " connection unsuccesfull");
System.out.println("SQLException: " + e.getMessage());
e.printStackTrace();
}
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init() throws ServletException {
ServletContext context = getServletContext();
String location = context.getInitParameter("propsFileLocation");
String host = context.getRealPath(location);

Properties properties = new Properties();
Pattern p = Pattern.compile("kumpgoed.nl");
Matcher m = p.matcher(host);
String name;
if(m.find()){
name = context.getInitParameter("propsFileName");
} else {
name = context.getInitParameter("propsFileNameLocalhost");
}

String path = context.getRealPath(location + "/" + name);
System.out.println("About to load properties file " + path);
try {
FileInputStream fis = new FileInputStream(path);
properties.load(fis);
} catch (IOException ioe) {
ioe.printStackTrace();
throw new ServletException(ioe);
}
context.setAttribute("properties", properties);

// ServletContext context = getServletContext();
// Testing for string "kumpgoed.nl" to determine which server
// is running the servlet; localhost or www.kumpgoed.nl
try {
establishConnection ();
con.close();
if(con.isClosed())
System.out.println("Successfully close " + databaseName);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

What do you mean by "I call from a different servlet" ? In that case, you'd better move the method in a utility class and pass it the ServletContext.


[My Blog]
All roads lead to JavaRanch
mark reusen
Greenhorn

Joined: Oct 20, 2010
Posts: 22
can you tell me how to fix the problem in the excisting source?
something goes wrong with the ServletContext, isn't this the right way to implement a getServletContext?
Satya Maheshwari
Ranch Hand

Joined: Jan 01, 2007
Posts: 368
Please use code tags when posting code.
As already suggested, a servlet is not the right place of having utility methods. A servlet has to undergo a lifecycle managed by the servlet container which determines the information that it has.


Thanks and Regards
mark reusen
Greenhorn

Joined: Oct 20, 2010
Posts: 22
okay, thank's.
Now I use a Java class which is using the ServletContext.
In the contructor I set up the Properties, and in a separate method I code "con = DriverManager.getConnection(databaseName, userName, passWord);".
After creating a Connection (con), I use context.setAttribute to store the con variable.
It seems to work now. The ServletContext is still the same as yesterday, and still alive!
But if you have better suggestions, I love to hear it!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: NullPointerException on getServletContext
 
Similar Threads
ServletContextListener Class fails
Problems with encodeURL
How can we read initparameter(String t) of a servlet
database connection help
How to close db connection