Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

getServletConfig() does not work

 
Joseph Sweet
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//from within a servlet...

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

ServletContext context = getServletConfig().getServletContext();

}


Should work ha???

Well it gives me the following error:

HTTP Status 500 -

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

java.lang.NullPointerException
uploadAttachments.doPost(uploadAttachments.java:51)
javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

note The full stack trace of the root cause is available in the Apache Tomcat/5.5.7 logs.
Apache Tomcat/5.5.7
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try:
 
Joseph Sweet
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Ben,

Isn't getServletContext() a method of of ServletConfig. I cannot use it like it is a method of HttpServlet.

Anyway I tried it and I get the following error:

HTTP Status 500 -

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

java.lang.NullPointerException
javax.servlet.GenericServlet.getServletContext(GenericServlet.java:159)
uploadAttachments.doPost(uploadAttachments.java:52)
javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

note The full stack trace of the root cause is available in the Apache Tomcat/5.5.7 logs.
Apache Tomcat/5.5.7
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
 
Joseph Sweet
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class uploadAttachments extends HttpServlet {

Connection theConnection;
private ServletConfig config;

public void init(ServletConfig config) throws ServletException{
this.config=config;
}


public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

ServletContext context = getServletConfig().getServletContext();

}

}


//however, if I use ServletContext context = config.getServletContext();
//then it compiles
//why is that?
//shouldn't the HttpServlet.getServletConfig() return the same ServletConfig that config points to?
[ April 02, 2005: Message edited by: Joseph Sweet ]
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joseph,
I'm not sure what you're trying to do.
If you need the context, from within one of the service methods, just use
this.getServletContext().

There's no need to go through the ServletConfig object.
It's main purpose is to allow the retrieval of init-params.

From:
http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletConfig.html
A servlet configuration object used by a servlet container used to pass information to a servlet during initialization.

[ April 02, 2005: Message edited by: Ben Souther ]
 
Joseph Sweet
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ben,

I am trying to upload files from a client to the server.

As I mentioned before, you cannot use "this.getServletContext()" inside a service method (like doPost, service...) since this method is not defined in the HttpServlet class, it is defined in the ServletConfig class, and you get the one that matches your specific servlet by.... calling to getServletConfig() from within your service methods (doPost, service...).

You can see the examples for that on the web.

Okay here is the full code. I replaced config.getServletContext().getRealPath("/tempUpload/")
with
this.getServletContext().getRealPath("/tempUpload/")
as you suggested and of course I got

java.lang.NullPointerException
javax.servlet.GenericServlet.getServletContext(GenericServlet.java:159)
uploadAttachments.doPost(uploadAttachments.java:72)
javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

my question is: why does the code work when I use config.getServletContext().getRealPath("/tempUpload/")
(I got the config value through the HttpServlet's init() method), but it won't work when I use getServletConfig().getServletContext().getRealPath("/tempUpload/")

WHY???

here is the code:


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.util.List;
import java.util.Iterator;
import java.io.File;

import utilities.ServletUtilities;

import java.sql.*;


public class uploadAttachments extends HttpServlet {

Connection theConnection;
private ServletConfig config;

public void init(ServletConfig config) throws ServletException{
this.config=config;
}


public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

HttpSession session = request.getSession(true);

out.println("Content Type = " + request.getContentType());

boolean[] fileExistsArray;
fileExistsArray = new boolean[ServletUtilities.getAttachNum()];


DiskFileItemFactory factory = new DiskFileItemFactory();

// maximum size that will be stored in memory.
// including form field
factory.setSizeThreshold(4096); //defualt is 1024 byte

//the location for saving data that is larger than getSizeThreshold()
factory.setRepository(new File(this.getServletContext().getRealPath("/tempUpload/")));
out.println(config.getServletContext().toString());


ServletFileUpload upload = new ServletFileUpload(factory);

//maximum size before a FileUploadException will be thrown
//-1 for no maximum.
upload.setSizeMax(ServletUtilities.getMaxUploadedFileSize());

List fileItems;



try {

fileItems = upload.parseRequest(request);
Iterator itr = fileItems.iterator();



while(itr.hasNext()) {

FileItem fi = (FileItem)itr.next();

//Check if not form field so as to only handle the file inputs
//else condition handles the submit button input

if(!fi.isFormField()) { // file

out.println("<br>FILE NAME: "+fi.getName());
out.println("SIZE: "+fi.getSize());

if (fi.getSize()>0 && fi.getSize()<=ServletUtilities.getMaxUploadedFileSize()) {

out.println(fi.getOutputStream().toString());
out.println(fi.getFieldName());
File real = new File(fi.getFieldName());

//in JSP: File fNew= new File(application.getRealPath("/temp/"), real.getName());
File fNew= new File(this.getServletContext().getRealPath("/tempUpload/"), real.getName());

out.println(fNew.getAbsolutePath());

//write to server
fi.write(fNew);

}

}

else { // not file
out.println("<br>Field name = " + fi.getFieldName());
out.println("Field value = " + fi.getString());
}

}


}

catch (FileUploadException e) {
//session.setAttribute("tooLargeFile", "true");
//response.sendRedirect("../register2.jsp");
out.println("error 1 " + e.getMessage());//Print trapped error.
}

catch (Exception e) {
out.println("error 2 " + e.getMessage());//Print trapped error.
}


}

public void destroy(){

}

}
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65228
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As I mentioned before, you cannot use "this.getServletContext()" inside a service method (like doPost, service...) since this method is not defined in the HttpServlet class,


Completely incorrect.
[ April 02, 2005: Message edited by: Bear Bibeault ]
 
Joseph Sweet
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are completely right.

Then why does this line:
getServletContext().getRealPath("/tempUpload/")

give me:

java.lang.NullPointerException
javax.servlet.GenericServlet.getServletContext(GenericServlet.java:159)
uploadAttachments.doPost(uploadAttachments.java:72)
javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

???
[ April 02, 2005: Message edited by: Joseph Sweet ]
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65228
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is the issue, The whole servletConfig thing was a red herring.

Some suggestions:

1) When posting code, use the UBB code tags (the button below the reply areas labeled CODE) to preserve the formatting of your code. More people will read your code is you make it readable.

2) Apply basic debugging techniques. What is getServletContext() returing? A null?

How exactly is the servlet being invoked?
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As I mentioned before, you cannot use "this.getServletContext()" inside a service method (like doPost, service...) since this method is not defined in the HttpServlet class,


It most certainly is defined in HttpServlet (actually its a method of the parent class GenericServlet).
http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/GenericServlet.html #getServletContext()



Then why does this line:
getServletContext().getRealPath("/tempUpload/")


The answer is in the API:
getRealPath
public java.lang.String getRealPath(java.lang.String path)

Returns a String containing the real path for a given virtual path. For example, the path "/index.html" returns the absolute file path on the server's filesystem would be served by a request for "http://host/contextPath/index.html", where contextPath is the context path of this ServletContext..

The real path returned will be in a form appropriate to the computer and operating system on which the servlet container is running, including the proper path separators. This method returns null if the servlet container cannot translate the virtual path to a real path for any reason (such as when the content is being made available from a .war archive).

Parameters:
path - a String specifying a virtual path
Returns:
a String specifying the real path, or null if the translation cannot be performed
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65228
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This method returns null if the servlet container cannot translate the virtual path


True, but that would not cause the line in question to NPE. However, if the return value is subsequently used without checking, that would cause an NPE.
 
Joseph Sweet
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ben, Bear

Okay, I see now that I can call getServletContext() inside a service method of a servlet.

Ben, the problem as it seems to me is not with the getRealPath("/tempUpload/") method. The problem is that the getServletContext() returns an exception: java.lang.NullPointerException

The servlet is being invoked through doPost, while submitting a form.

Look at this servlet:



It invokes an exception:

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

java.lang.NullPointerException
javax.servlet.GenericServlet.getServletContext(GenericServlet.java:159)
uploadAttachments.doPost(uploadAttachments.java:51)
javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)




But, when I do not overide the init() method, everythings works fine:





Also, when I keep the overiding init() method, and use the config value I have gotten, everything is fine:




WHY is that??? What is in the init() method that does this crazy thing ???
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65228
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's it!!!

By over-riding the init method you are preventing the base class from initializing.

Your should either invoke the base class init method from yours, or bettter yet, over-ride the init() method that takes no paramters. This method is called from the base class init method and so you don't have to worry about the base class initialization.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65228
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the javadoc:

This implementation stores the ServletConfig object it receives from the servlet container for later use. When overriding this form of the method, call super.init(config).


But it's best to simply override the no-parameter version of init().
[ April 02, 2005: Message edited by: Bear Bibeault ]
 
Joseph Sweet
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes I can see it now.

Thank you for the great help

 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nice catch, both of you.
I should have noticed the lack of super.init(config) in the init method.
 
Smita Talawadekar
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you use init(servletconfig) and forgot to call super.init(config) then servletconfig object will not be set to the actual one and you will not get the servletconfig object. As a result, in this case, you are calling getServletContext() on a null servletConfig object hence getting null pointer exception.
It is BETTER to use init(). If you use init() you have no such worries as calling super.init().

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic