Java Forum / First Aid / May 2005
Help with Java servlet : getServletContext().
Vidya - 29 Apr 2005 15:37 GMT I am newbie to Java, am trying to get a program working, and I have imported the java packages below along with many other imports : import javax.servlet.GenericServlet; .... xsltFile = new File(getServletContext().getRealPath("xslt/" + template)); if(!xsltFile.canRead()) { System.out.println("Error reading XSLT template file '" + xsltFile + "'."); return 0; }
I get the following error, can anyone tell me what the problem is?
com\netod\util\MyClass.java:243: cannot resolve symbol symbol : method getServletContext () location: class com.netod.util.MyClass xsltFile = new File(getServletContext().getRealPath("xslt/" + template));
thanks for any help
kaeli - 29 Apr 2005 15:59 GMT > I am newbie to Java, am trying to get a program working, and I have > imported the java packages below along with many other imports : > import javax.servlet.GenericServlet; > .... > xsltFile = new File(getServletContext(). What are you getting the servletContext FROM? ;)
someServlet.getServletContext()
Probably, depending on where this statement is running from, you want this.getServletContext()
You can call a method on nothing.
HTH
 Signature -- ~kaeli~ Practice safe eating - always use condiments. http://www.ipwebdesign.net/wildAtHeart http://www.ipwebdesign.net/kaelisSpace
Juha Laiho - 30 Apr 2005 19:03 GMT kaeli <tiny_one@NOSPAM.comcast.net> said:
>> I am newbie to Java, am trying to get a program working, and I have >> imported the java packages below along with many other imports : [quoted text clipped - 10 lines] > >You can call a method on nothing. What?
'this.foo()' is equivalent to 'foo()' - at least in all cases I can imagine (and please educate me if there are cases where this isn't so!). It will always call method 'foo()' either on the current class, or on the closest superclass implementing the method.
There are cases where you might need an explicit 'this.' for referencing instance variables (where you have a local variable of the same name, shadowing the instance variable), but for method calls, 'this.' is always superfluous.
 Signature Wolf a.k.a. Juha Laiho Espoo, Finland (GC 3.0) GIT d- s+: a C++ ULSH++++$ P++@ L+++ E- W+$@ N++ !K w !O !M V PS(+) PE Y+ PGP(+) t- 5 !X R !tv b+ !DI D G e+ h---- r+++ y++++ "...cancel my subscription to the resurrection!" (Jim Morrison)
kaeli - 02 May 2005 13:47 GMT > What? > > 'this.foo()' is equivalent to 'foo()' - Yeah, I realized after I posted that how stoopid that was. I didn't have time to come correct myself.
Thanks. *embarrassed grin*
 Signature -- ~kaeli~ Dijon vu - the same mustard as before. http://www.ipwebdesign.net/wildAtHeart http://www.ipwebdesign.net/kaelisSpace
Ross Bamford - 29 Apr 2005 18:17 GMT > I am newbie to Java, am trying to get a program working, and I have > imported the java packages below along with many other imports : [quoted text clipped - 17 lines] > > thanks for any help Without seeing more of your code, but as a "newbie to Java" I think it's a fair guess you're after writing a Web servlet, rather than creating a whole new type of servlet (such as FTP)?
If this is the case, instead of GenericServlet you should extend javax.servlet.http.HttpServlet.
I'm not sure where the not found is coming from - perhaps you're implementing straight Servlet (which doesn't have it) ? If changing to HTTPServlet doesn't help, post more of your code.
Ross
 Signature [Ross A. Bamford] [ross AT the.website.domain] Roscopeco Open Tech ++ Open Source + Java + Apache + CMF http://www.roscopec0.f9.co.uk/ + info@the.website.domain
Vidya - 29 Apr 2005 18:56 GMT Hi Ross, I did include the javax.servlet.http.HttpServlet. Here is more code...if it helps.
import java.io.*; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; import java.util.Hashtable; import java.util.EventObject; import java.net.*; import java.lang.String; import java.io.StringWriter; import java.lang.Integer; import java.applet.*; import javax.activation.DataHandler; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.http.HttpServlet; import javax.servlet.GenericServlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionBindingListener; //import javax.servlet.ServletContext; 'this is a redundant class if serverlet.* has already been imported. import javax.naming.InitialContext; import javax.naming.NamingException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerConfigurationException; import org.apache.xml.utils.SAXSourceLocator; import org.apache.xml.utils.WrappedRuntimeException; import org.w3c.dom.Document; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import javax.xml.parsers.* ; import javax.xml.parsers.DocumentBuilder; .......... ..... public int ProcessParams() { transaction = "locmap"; template = "map.xsl"; url = GetParameter("url", "");
if(url == null || url.equals("")) {
Enumeration paramNames = req.getParameterNames(); int numParams = EnumSize(paramNames);
String trans = GetParameter("transaction", "");
String city = GetParameter("city", ""); String stateProvince = GetParameter("stateprovince", ""); String postalCode = GetParameter("postalcode", ""); String recordId = GetParameter("recordid", ""); String latitude = GetParameter("latitude", ""); String longitude = GetParameter("longitude", "");
String origcity = GetParameter("origcity", ""); String origstateProvince = GetParameter("origstateprovince", ""); String origpostalCode = GetParameter("origpostalcode", ""); String origrecordId = GetParameter("origrecordid", ""); String origlatitude = GetParameter("origlatitude", ""); String origlongitude = GetParameter("origlongitude", "");
String destcity = GetParameter("destcity", ""); String deststateProvince = GetParameter("deststateprovince", ""); String destpostalCode = GetParameter("destpostalcode", ""); String destrecordId = GetParameter("destrecordid", ""); String destlatitude = GetParameter("destlatitude", ""); String destlongitude = GetParameter("destlongitude", "");
if (trans != null && !trans.equals("") && !trans.equals("poimap") && nc_input.get("identifyicon") == null) { if (trans.equals("route")) {
// route trans
// origin if ((origcity == null || origcity.equals("") || origstateProvince == null || origstateProvince.equals("")) && (origpostalCode == null || origpostalCode.equals("")) && (origrecordId == null || origrecordId.equals("")) && (origlatitude == null || origlatitude.equals("")) && (origlongitude == null || origlongitude.equals(""))) { error = 9000; // not enough info for the origin
// destination } else if ((destcity == null || destcity.equals("") || deststateProvince == null || deststateProvince.equals("")) && (destpostalCode == null || destpostalCode.equals("")) && (destrecordId == null || destrecordId.equals("")) && (destlatitude == null || destlatitude.equals("")) && (destlongitude == null || destlongitude.equals(""))) { error = 9000; // not enough info for the destination }
} else {
// other type of trans if ((city == null || city.equals("")
stateProvince == null || stateProvince.equals("")) && (postalCode == null || postalCode.equals("")) && (recordId == null || recordId.equals("")) && (latitude == null || latitude.equals("")) && (longitude == null || longitude.equals(""))) { error = 9000; // not enough info for the center }
} // if (trans.equals("route")) } // if (trans != null && (!(trans.equals(""))))
// EnumSize moved the pointer to the end of paramNames.. reset paramNames = req.getParameterNames();
while(paramNames.hasMoreElements()) { String elem = (String)paramNames.nextElement(); String val = req.getParameter(elem);
if (elem.equals("template") && !(val == null || val.equals(""))) { template = val + ".xsl";
} else if (elem.equals("transaction") && !(val == null || val.equals(""))) { transaction = URLEncoder.encode(val);
} else { if(! val.equals("")) { // add to hashtable passed.put(elem, val);
elem = URLEncoder.encode(elem); val = URLEncoder.encode(val);
if(params.equals("")) { params = "/?" + elem + "=" + val; } else { params += "&" + elem + "=" + val; } } } }
if (!(params == null || params.equals(""))) { params += "&clientid=" + clientId; passed.put("clientid", clientId);
params += "&passwd=" + passwd; passed.put("passwd", passwd);
params += "&transaction=" + transaction; passed.put("transaction", transaction);
url = "http://" + server + params; }
} else {
// Prepend the protocol and server to the returned url url = "http://" + server + "/?clientId=" + clientId + "&" + url;
String tmpTemplate = GetParameter("template", ""); if (!(tmpTemplate == null || tmpTemplate.equals(""))) { template = tmpTemplate + ".xsl"; } }
xsltFile = new File(getServletContext().getRealPath("xslt/" + template)); if(!xsltFile.canRead()) { System.out.println("Error reading XSLT template file '" + xsltFile + "'."); return 0; }
return 1; } // ProcessParams
Thanks Vidya
> > I am newbie to Java, am trying to get a program working, and I have > > imported the java packages below along with many other imports : [quoted text clipped - 35 lines] > Roscopeco Open Tech ++ Open Source + Java + Apache + CMF > http://www.roscopec0.f9.co.uk/ + info@the.website.domain Ross Bamford - 29 Apr 2005 19:30 GMT > Hi Ross, > I did include the javax.servlet.http.HttpServlet. > Here is more code...if it helps. Firstly those imports - You don't need to specifically name the classes if you're using the javax.something.* syntax - that automatically imports all public classes in the package. So for this app, all the javax.servlet.whatever entries could removed, to leave only:
javax.servlet.*; javax.servlet.http.*;
Most apps can get by with only javax.servlet.ServletContext, and the servlet.http.* classes. Once your program is up and running, it's a good idea to remove wildcard definitions but for now, it will make management easier :)
Okay, so, importing it is part one of the process. The method you sent looks like it's part of the servlet? Now. I bet your class definition says:
[public] class YourClass implements Servlet
or maybe 'extends GenericServlet' in place of 'implements Servlet'. Instead, it should be:
[public] class YourClass extends HttpServlet
You will then be able to override one/both of doGet(HttpServletRequest, HttpServletResponse) and doPost(HttpServletRequest, HttpServletResponse) to process get/post requests. Notice these both pass in a ready-to-use request, with the parameters and what-not, and a response ready for you to output to.
These methods then do whatever processing they need to, and use the methods in [Http]ServletResponse to communicate with the client.
Hope this is helpful :)
Ross
 Signature [Ross A. Bamford] [ross AT the.website.domain] Roscopeco Open Tech ++ Open Source + Java + Apache + CMF http://www.roscopec0.f9.co.uk/ + info@the.website.domain
Vidya - 29 Apr 2005 21:05 GMT Thank you very very much Ross. The class was not suffixed with the "extends HttpServlet ". I could compile the class sucessfully after making this change. Best Regards, Vidya.
Vidya - 26 May 2005 19:58 GMT Hi, Although I could compile the class successfully,when I load the jsp page on my web browser, I get the following error in the weblogic server logs:
322952,name=myApp,context-path=/myApp)] Servlet failed with Exception java.lang.NullPointerException. Could there be any reason why I get NullPointerExeption when I use the following line in my code? xsltFile = new File(getServletConfig().getServletContext().getRealPath("xslt/" + template));
Any advice/help will greatly be apreciated. Vidya.
> Thank you very very much Ross. The class was not suffixed with the > "extends HttpServlet ". I could compile the class sucessfully after > making this change. > Best Regards, > Vidya. Andrew Thompson - 26 May 2005 20:17 GMT > File(getServletConfig().getServletContext().getRealPath("xslt/" + > template)); > > Any advice/help will greatly be apreciated. The advice I can give you is that when debugging an NPE caused by a statement such as that, break it down to find out *what* is null!
E.G.
System.out.println( template ); ServletConfig scg = getServletConfig(); System.out.println( scg ); ServletContext sct = scg.getServletContext(); System.out.println( sct ); String s = sct.getRealPath( "xslt/" + template ); System.out.println( s ); File f = new File(s); System.out.println( f ); ...
As an aside, you should not specify the file separator as you have above, it is better to do it like this..
String s = "xslt" + File.separator + template;
..to ensure your application runs correctly on any platform on which it runs. Also, if directory 'xslt' is at the top level of the site, it might be better to specify that.
String s = File.separator + "xslt" + File.separator + template;
HTH
 Signature Andrew Thompson http://www.PhySci.org/codes/ Web & IT Help http://www.PhySci.org/ Open-source software suite http://www.1point1C.org/ Science & Technology http://www.LensEscapes.com/ Images that escape the mundane
Vidya - 26 May 2005 21:37 GMT Hi Thompson,
I used the code below: System.out.println( template ); ServletConfig scg = getServletConfig(); System.out.println( "scg="+scg ); ServletContext sct = scg.getServletContext(); System.out.println( "sct="+sct ); String s = sct.getRealPath( "xslt/" + template ); System.out.println( "path="+s ); File f = new File(s); System.out.println( f );
and I get the error below:
scg=null
Why is the scg null here? Where am I going wrong? Thanks, Vidya.
> > File(getServletConfig().getServletContext().getRealPath("xslt/" + > > template)); [quoted text clipped - 36 lines] > http://www.1point1C.org/ Science & Technology > http://www.LensEscapes.com/ Images that escape the mundane William Brogden - 29 May 2005 18:16 GMT > Hi Thompson, > [quoted text clipped - 16 lines] > Thanks, > Vidya. Probably because you didn't use the right form of the init method. If you use public void init(ServletConfig config) throws ServletException {
You MUST include the line: super.init(config);
otherwise the ServletConfig keeps the null value it was initialzed with. Bill
Vidya - 31 May 2005 17:04 GMT Hi Bill,
As you can see in my prevous postings above, I don't have any "init method" in my code. Since I do not have init method defined anywhere, am I having this problem? Can someone post a working version of sample that uses the getServletContext().getRealPath?
Thanks,
Vidya.
> > Hi Thompson, > > [quoted text clipped - 26 lines] > otherwise the ServletConfig keeps the null value it was initialzed with. > Bill
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|