*
The moose likes Servlets and the fly likes Using Model 2 - NullPointer problem. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Using Model 2 - NullPointer problem." Watch "Using Model 2 - NullPointer problem." New topic
Author

Using Model 2 - NullPointer problem.

Tom Hilliard
Ranch Hand

Joined: Feb 03, 2012
Posts: 39

Hi all, I'm still working through understanding Model 2 and not using scriptlets in JSP dadada...

Stumbled upon a roadblock!

I'm implementing the beerV1 example in Head First Servlets and JSP By Bert Bates, Kathy Sierra, Bryan Basham. So I successfully implemented their version with <%%> scriptlets but I'm now trying to implement it without the scriptlets using EL.

Now the application, a user selects a beer "colour" from form.html



- this POSTS the colour to the BeerSelect.java servlet



That servlet uses the BeerExpert.java to get the brands of beer that relate to the chosen colour.



The BeerExpert returns a List of the brands related to the colour and BeerSelect sets the List in the request.

The list is then used by result.jsp to show the brands.



Now the error I'm getting is a null pointer when adding a brand to the brands List on BeerExpert.java

07-Feb-2012 15:10:50 org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet Ch3 Beer threw exception
java.lang.NullPointerException
at com.example.model.BeerExpert.getBrands(BeerExpert.java:24)
at com.example.web.BeerSelect.doPost(BeerSelect.java:71)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:864)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1665)
at java.lang.Thread.run(Thread.java:662)

Now I notice some issue with the chosen colour, eg, if I choose amber (on form.html), the error still occurs at line 24 on BeerExpert. I'm guessing that this means the "colour" attribute is not what it should be, eg it is null rather than amber?

As I said, I have no clue to exactly what is wrong. I've tried my best to explain the situation I'm in and have also tried my best to remedy it.

If you guys could spot the issue and offer some advice to fix I'd be very grateful

Regards

TH
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4422
    
    8

OK, here's how you diagnose it.

The error is a NullPointerException. That means you're trying to call a method on a null object, or something similar.

The error tells you it is caused by line 24 of BeerExpert.java. That is:

There's only one way that line can throw a NullPointerException. That's if brands is null. So where is brands initialised? And as far as I can tell, it isn't. That's your cause.

There may or may not be a logical problem with your colour attribute - I haven't checked - but that's not what causes the exception.
Amit Baidya
Greenhorn

Joined: Feb 07, 2012
Posts: 1
Matthew Brown wrote:OK, here's how you diagnose it.

The error is a NullPointerException. That means you're trying to call a method on a null object, or something similar.

The error tells you it is caused by line 24 of BeerExpert.java. That is:

There's only one way that line can throw a NullPointerException. That's if brands is null. So where is brands initialised? And as far as I can tell, it isn't. That's your cause.

There may or may not be a logical problem with your colour attribute - I haven't checked - but that's not what causes the exception.
Tom Hilliard
Ranch Hand

Joined: Feb 03, 2012
Posts: 39

Cheers for the reply.

I understand about the null pointer and not initialising the List as a concept (if it doesn't exist then how can we possibly add something to it!), but I'm not sure how it translates to code. Say if I were using an ArrayList, would it be ??? But if I do that then if get a jasper exception instead:

07-Feb-2012 17:40:16 org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet jsp threw exception
org.apache.jasper.JasperException: Cannot find any information on property 'brands' in a bean of type 'com.example.model.BeerExpert'
at org.apache.jasper.runtime.JspRuntimeLibrary.getReadMethod(JspRuntimeLibrary.java:839)
at org.apache.jasper.compiler.Generator$GenerateVisitor.visit(Generator.java:1066)
at org.apache.jasper.compiler.Node$GetProperty.accept(Node.java:1124)
at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2411)
at org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2417)
at org.apache.jasper.compiler.Node$Root.accept(Node.java:495)
at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
at org.apache.jasper.compiler.Generator.generate(Generator.java:3442)
at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:231)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:347)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:327)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:314)
at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:592)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:326)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
at com.example.web.BeerSelect.doPost(BeerSelect.java:69)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:864)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1665)
at java.lang.Thread.run(Thread.java:662)


Also, there is surely a logical error on the "colour" attribute as the error occurs on the else of the conditional every time. Even when I satisfy the if.

So I'm guessing I need to fix the null pointer before considering the logical error?

I'm getting to the point now where I'm losing patience and just want to see a working answer to understand this Model 2. Bloody beer has nothing to do with what I'm wanting to do!

If anyone is willing to check my code and alter/append where necessary to get it not throwing exceptions, along with giving a quick description of why I'd be so so happy, as I say, I just want to get on with changing all my old model code to this new one

Regards

TH

Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61424
    
  67

Yes, you must attend to the NPE before all others.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Tom Hilliard
Ranch Hand

Joined: Feb 03, 2012
Posts: 39

I'm quite miffed with the book mentioned, if only they had show the use of EL in their simple beer example

I really don't want to be a bad programmer but time may force it if I can't get a handle on this soon

Bear Bibeault wrote:Yes, you must attend to the NPE before all others.


agreed but how? Explicitly, what code is needed ?

Regards

TH
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61424
    
  67

You commented out the line that creates the array list.
Tom Hilliard
Ranch Hand

Joined: Feb 03, 2012
Posts: 39

Bear Bibeault wrote:You commented out the line that creates the array list.


OK, so I uncomment it and run = org.apache.jasper.JasperException: Cannot find any information on property 'brands' in a bean of type 'com.example.model.BeerExpert'

And my IDE warns that "Local variable hides a field" at

I guess that means that the global variable "brands" is being affected by that List brands...

So, my first thought is rename the List "brands1" and when I'm finished adding elements, turn brands1 into brands for the return?

Is that a good thought? Or am I well off?

Please excuse my terminology and slow pick up
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18657
    
    8

All of these questions are the sort of thing which regularly appear in the "Beginning Java" forum. (They are a natural part of learning the language.) But you're making things more difficult for yourself by trying to learn servlets and JSP at the same time. I would recommend you drop that for a while and concentrate on learning Java.
Tom Hilliard
Ranch Hand

Joined: Feb 03, 2012
Posts: 39

Its all this bean stuff that confusing me, I understand java enough to make a relatively complex web app using servlet/jsp but using <% JAVA CODE %> scriptlets, using jdbc to get and store things, sending arraylists in request and deling with them via scriptlets on jsps etc.

Now, I want to understand this model to translate what I have already (scriptlet rubbish) to this 'better' model (I put better in inverted comas as I'm yet to see any results, whereas using my old methods I had half a system in a day or so!)

Like I've said before, I'd really like to see a working example of the model to look at and understand.

Regards

TH

Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18657
    
    8

Tom Hilliard wrote:Its all this bean stuff that confusing me, I understand java enough to make a relatively complex web app using servlet/jsp...


And yet you don't understand basic things like declaring variables. I still believe you're out of your depth.
Tom Hilliard
Ranch Hand

Joined: Feb 03, 2012
Posts: 39

Just because I can't articulate it well, doesn't mean I'm out of my depth.

I'm asking if anyone can fix the code, however that may be, so that I can have a look at a working example OR direct me to an existing working example?

TH
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18657
    
    8

Tom Hilliard wrote:Just because I can't articulate it well, doesn't mean I'm out of my depth.


Well, no, your problem wasn't that you couldn't articulate something. You are doing a good job of explaining things in this thread. Your problem was that you didn't recognize that a NPE was caused by a variable that wasn't initialized, and that you didn't understand the Netbeans warning that you had declared a local variable which hid the class-level variable of the same name. Your problem was that you couldn't deal with those things, which have nothing to do with servlets or JSP.

However I respect your decision that you're going to carry on regardless.

As for your JSP problem, a Java Bean should not use static methods. And also its getters should not have parameters. So your BeerExpert class needs to be fixed to match the Java Bean conventions. I would suggest a setColour(String colour) method, which you would call from your servlet using data from the servlet parameter.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61424
    
  67

[Edit: the following was written as Paul was posting so it repeats some things that Paul said.]

Sorry to be contrarian, but I'm siding with Paul. The problems you are having show a less-than adequate grasp of Java itself. It's not a matter of you articulating yourself correctly. It's evident in your code. Getting defensive about it won't help. We were all there at one time. And this has nothing to do with model 1 vs model 2. This is the type of basic Java issue that you're going to run into sooner or later no matter which approach you are taking.

The warning that you are getting is because you are defining the variable brands as both a static member variable (why static?) and as a method variable. The compiler is warning you that that's likely an issue. And it is.

Do you want it to be a member variable, or a method variable?

Once you decide which, you can't use brands until you initialize it, so make sure that whichever approach you pick is properly initialized. What you've got now is ambiguous and the compiler is (rightly) warning you about it.

Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61424
    
  67

Just to stress: we are not picking on you. We're trying to help you the best we can, and that includes not just glossing over things that you really need to know to work in the web app arena.
Tom Hilliard
Ranch Hand

Joined: Feb 03, 2012
Posts: 39

Thanks guys, I do feel grateful for your input. Like I said the most frustrating thing is how much I managed to get done using scriptlets, compared to the nightmare I'm having. Maybe that lulls me into a false sense of competence.

I understand your not picking on me and that I'm sure you understand java alot more than I do.

So I'm going to propose a new question.

If I have this results.jsp using scriptlets...



How exactly do I translate the scriplet into EL (${something})?

Regards

TH
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18657
    
    8

A <c:forEach> element would be just the thing for that.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61424
    
  67

[Edit: Paul snuck in first again!]

It looks like "styles" is already established as a scoped variable on the request, so you don't need to do anything at all to "fetch it". (In other words, there's no need to do anything to replace the getAttribute() statement).

Iteration is done with the <c:forEach> action (tag). Something like:
This defines that within the forEach body, the current iteration element is available as style.

So, that grody mess becomes:


Much better.

This assumes, of course, that the styles scoped variable has been correctly established. If that scriptlet was working, it's likely to be.
Tom Hilliard
Ranch Hand

Joined: Feb 03, 2012
Posts: 39

Paul Clapham wrote:A <c:forEach> element would be just the thing for that.


OK, so I have tried this and made some headway!



and I get this as the page source from the browser



So I can see that the value is there but now what I want to do is print out Jail Pale Ale on one line and Gout Stout on the next one.
I've had a search on google but am not getting very far.

Is what I'm doing along the right tracks? and what am I missing to print the values inside the "styles" List?

Regards TH
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61424
    
  67

See my post. You're close, but no cigar yet.

Also, if you are still seeing <c:forEach> at the browser, you don't have the JSTL correctly configured yet.

And, you only need to use <c:out> for output that needs to be HTML-encoded (which should always be done for untrusted values).
Tom Hilliard
Ranch Hand

Joined: Feb 03, 2012
Posts: 39

Thanks, I don't see the <cut... actually in the browser but in the pages source code (right click> view source code) so is that right?

... so now I have this



and the result I get from "view page source" is




So I obviously need to split the List rather than toString-ing it? Is that correct?

If I use Bear's method -

I get

Pointers on how this is done ;)

Regards

TH
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61424
    
  67

and the result I get from "view page source" is

"View page source" in the browser shows the HTML being sent as the response. Not the JSP source.

Again, if the JSTL tags are being sent to the browser, they're not being evaluated on the server.

Did you set up the JSTL properly? (see the JspFaq)
Did you declare the core JSTL tags on the page?
Tom Hilliard
Ranch Hand

Joined: Feb 03, 2012
Posts: 39

I'm unsure if it is, I have followed the guidelines given in the JSP FAQ. All seems to be in order. declared web.xml file for Servlets 2.5 and JSP 2.1 is correct. Both jstl-api-1.2.jar and jstl-impl-1.2.jar are in the "compile time libraries" and I copy and paste the taglibs on from the faq to my jsp.

Now the taglibs must be declared on my .jsp using - <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> before the DOCTYPE? That right?

So I do that and IDE underlines(red) the taglib declaration and says: The absolute uri:http://java.sun.com/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application.

Again, a google search hasn't yielded anything helpful! It has now though! EDIT So apparently this means No JSTL implementation. Isn't that covered by the jstl_impl_1.2.jar? EDIT

Regards

TH
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61424
    
  67

are in the "compile time libraries"

Irrelevant. Are they in WEB-INF/lib?
Tom Hilliard
Ranch Hand

Joined: Feb 03, 2012
Posts: 39

Bear Bibeault wrote:
are in the "compile time libraries"

Irrelevant. Are they in WEB-INF/lib?


Certainly are.

there is

jstl-1.2.jar (I could probably delete this one?)
jstl-api-1.2.jar
and jstl-impl-1.2.jar

TH
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61424
    
  67

Yeah, you don't want overlapping jars. Remove the irrelevant one.

Is that a runtime error or an IDE warning? IDEs suck at web apps.
Tom Hilliard
Ranch Hand

Joined: Feb 03, 2012
Posts: 39

Bear Bibeault wrote:Yeah, you don't want overlapping jars. Remove the irrelevant one.

Is that a runtime error or an IDE warning? IDEs suck at web apps.


Uneccessary jar gone.

I think its probably an IDE warning.

I say that because I run this jsp:



and get the org.apache.jasper.JasperException: /result.jsp(33,4) According to TLD or attribute directive in tag file, attribute items does not accept any expressions

Mean anything to you?

Regards
TH
Tom Hilliard
Ranch Hand

Joined: Feb 03, 2012
Posts: 39

Have it working as expected now, was using the wrong uri in the taglib declaration... whoops!

Thanks for the help guys.

Now I'm going to post all the code that makes up the app... Could you please tell me that it conforms to the most uptodate model?

form.html


BeerSelect.Java


BeerExpert.java


and finally, result.jsp


So is this it? The wonderful new Model 2? or have I still got work to do?

Very Much Appreciation

TH
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61424
    
  67

Definitely on the right track!
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18657
    
    8

A trivial point: now that you aren't using scriptlets any more, you don't need these any more:

Of course it doesn't do any harm to have them there, but in real-life programs it can be confusing to the next person who gets to work on the code.
Tom Hilliard
Ranch Hand

Joined: Feb 03, 2012
Posts: 39

Thanks for the help guys, got there in the end...

Now to get on translating my old model app to the new model

I'm expecting to stumble upon some issues here and there so expect to hear from me again ;P

Once again, absolutely brilliant work guys, JavaRanch... What a great resource!

Regards

TH
Tom Hilliard
Ranch Hand

Joined: Feb 03, 2012
Posts: 39

Quick question regarding naming conventions.

eg, In the scenario explained above I name my packages com.example.model & com.example.web

What I'd like to clarify is do I replace the "example" bit with something meaningful? Like my project's name or something similar?

So the package would be called com.somethingmeaingful.model & com.somethingmeaningful.model?

Regards

TH
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61424
    
  67

The convention of using reversed domain names is in order to avoid collisions with someone else's packages. Generally, you use a domain that you own, because that guarantees uniqueness. No one else can own that same domain.

For example, I own bibeault.org, so my personal projects use a package structure that follows: org.bibeault.project-name... where project-name is the name of the project to which the package belongs. E.g. org.bibeault.frontman, org.bibeault.resume, org.bibeault.bddb, org.bibeault.discovery, and so on.

When I'm working on a client's project, the packages are named using one of the client's domains.

If you don't own a domain, you should. You can't be considered a serious web developer if you don't own at least one domain.
Tom Hilliard
Ranch Hand

Joined: Feb 03, 2012
Posts: 39

Bear Bibeault wrote:The convention of using reversed domain names is in order to avoid collisions with someone else's packages. Generally, you use a domain that you own, because that guarantees uniqueness. No one else can own that same domain.

For example, I own bibeault.org, so my personal projects use a package structure that follows: org.bibeault.project-name... where project-name is the name of the project to which the package belongs. E.g. org.bibeault.frontman, org.bibeault.resume, org.bibeault.bddb, org.bibeault.discovery, and so on.

When I'm working on a client's project, the packages are named using one of the client's domains.

If you don't own a domain, you should. You can't be considered a serious web developer if you don't own at least one domain.


Cheers for the info, I'm currently a student, without a plan to go into web development... But it may happen.

So for the sake of my project it can be com.tomh.web? or something more meaningful com.3rdyearproject.web?

Regards

TH
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18657
    
    8

If it's just for a student exercise, it really doesn't matter since your code isn't going to be distributed to professional developers. But still it's a good idea to be precise. There's a "name" top-level domain, so "tom.hilliard.name" is a possible domain name. It might already be owned by somebody else (you could check if you liked) but if you pretended you owned it, then your package name would be "name.hilliard.tom".
Tom Hilliard
Ranch Hand

Joined: Feb 03, 2012
Posts: 39

Ah cool, didn't realise .name was available. I have looked for at buying a domain as I'm hoping my final project will have some commercial porspect so it will definitely be something to look out for, but for the purposes of the project any meaingful name will do.

Just looked and com.3rdyearproject.web is not valid, can't start a package name with a number or symbol character

com.dissertation.web & com.dissertation.model have been chosen

TH
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61424
    
  67

Yeah, I also own 3chiles.com (long story), so for those projects, I need to use com._3chiles as the package root.
 
jQuery in Action, 2nd edition
 
subject: Using Model 2 - NullPointer problem.