hkguile
hkguile

Reputation: 4359

jsp simply code throwing a nullPointerException

Here is the test.jsp

<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%
    String str = request.getParameter("str");
    if (str.equals("play")) {
    }                  
%>

Errors:

type Exception report

message

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

exception

org.apache.jasper.JasperException: java.lang.NullPointerException

root cause java.lang.NullPointerException

note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.1.1 logs.

The above code have errors if run, what the problems of above codes?

Upvotes: 0

Views: 2018

Answers (5)

Advait
Advait

Reputation: 127

Please debug the .java file from where you are getting the "str" value from. And check if you are getting a null in that position. If yes, Then that is why it is throwing a NULL Pointer Exception. Str!=NULL would not solve your problem as you would not get the desired output & lead to your confusion even more. PS : Please avoid using scriptlets in JSP.

Upvotes: 0

kukudas
kukudas

Reputation: 4934

There is no request parameter for "str" so the str variable is null. As others suggested you might use this "play".equals(str);.

Upvotes: 0

Nomad
Nomad

Reputation: 1102

Another way to do this. If you have constant string e.g. in your case "play" compare with it the variable rather than what you are doing. i.e.

 if ( ("play").equals(str))
 {

 }  

In this way you wont get Null Pointer exception because String is not equal to null (if str is null). In your case since str is null so null.equals is giving you null pointer exception.

Also trying printing out the value of str before if statement like below to see what value is coming.

out.println("Str:"+str);

Hope this helps.

Upvotes: 0

Ramesh PVK
Ramesh PVK

Reputation: 15446

Having scriptlets in jsp is very bad programming practise.

For the problem you are facing , i think the parameter is not found. Check if the parameter is being sent for the request.

Upvotes: 1

Shashank Kadne
Shashank Kadne

Reputation: 8101

Change if (str.equals("play")) to if (str!=null && str.equals("play"))

Your request parameter is null it seems.

Upvotes: 1

Related Questions