nullpointexception when i use those variables declared inside the scriptlet - java

I got the following code kind of inside of my <% %> in my jsp file.
Two problems here:
Why doesnt my breakpoint doesnt stop in those lines?
Why does have a nullpointerException happen when i use these variables somewhere inside my jsp like these <%=beneficiariesList%>. This value debugging in eclipse in the display view says " beneficiariesList cant be resolved" . For example tipoBeneciarioDatosClientes says the value which is "XXXX"
<% ...... bla bla bla
String tipoBeneficiarioDatosClientes = "XXXXX";
String beneficiariesList = "XXXXX";
if (null != polizaBean.xxxxx() && !polizaBean.getTipoBeneficiario().isEmpty()) {
tipoBeneficiarioDatosClientes = polizaBean.xxxxxx();
if(tipoBeneficiarioDatosClientes.equalsIgnoreCase("xxxxx")) {
JSONArray beneficiaries = JSONArray.fromObject(polizaBean.xxxxx());
beneficiariesList = beneficiaries.toString();
}
}
%>

You have a NullPointerException because variables which you are using inside Scriptlets <% ... %> are only available inside that scriplet.
If you want to declare variable which will be available in Expressions <%= %> you need to declare them inside a Declations block <%! %>.
From JSP 2.0 Specification :
Declarations are used to declare variables and methods in the
scripting language used in a JSP page.
...
Declarations are initialized when the JSP page is initialized and are made
available to other declarations, scriptlets, and expressions.

Related

Assigning form input value to java variable in jsp

I have a scenario in which i am rendering a jsp page .One of my value is in my model Form entity.I am assigning it in one of my form input like below :
<s:hidden name="myModelName.myUserName"/>
I am trying to assign it to my java variable inside my jsp.I tried accessing the model directly like this
<%= String myName = myModelName.myUserName %>
But i get error message "myModelName cannot be resolved.I have then tried accessing from the hidden field.But i dont know how to use it.Anyway i need the value in java variable inside jsp for some reason.Anyone help me out how to do it
You can do something like this:
assign your model property value to variable userName
<c:set var="userName" scope="session" value="${myModelName.myUserName}"/>
and then you can output it using this tag:
<c:out value = "${userName}"/>
You can read more about JSTL tags here: Using JSTL tags
Hope this helps. Ask if you need anything else.

simple way to transfer data from java class to javascript

I have a string String myString = "This is some text." I also have a getter getMyString()
I have a jsp page I want to bring it to and then store it in localStorage. since this isn't exactly my expertise I've tried doing it like...
var myJSString = "<%=myString%>";
var myJSString = <% getMyString(); %>
they both give me the same error
HTTP Status 500 - org.apache.jasper.JasperException: Unable to compile class for JSP
root cause
org.apache.jasper.JasperException: Unable to compile class for JSP
I've looked through numerous tutorials and I haven't been able to get this to work. What other ways are there to put a java variable into a javascript variable?
Why don't use Expression Language or JSTL? e.g.
Expression Language
var myJSString = "${myString}";
JSTL
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
...
var myJSString = '<c:out value="${myString}"/>';
You cant really access the variables created by JSP in javascript. What I used to do is , create a hidden element and assign the value to it via scriptlet. Once the page loads , access the hidden element's value via javascript.
<input type="hidden" id="accountName" value='<%= bean.getAccountName(); %>'/>
Now when the page is rendered you will get something like this.
<input type="hidden" id="accountName" value='Myaccountname'/>
You can access this value with javascript using document.getelementByID("accountName");
Note:
1.getAccountName() should be called from a bean
2.I havent checked the syntax of the code above.Just typed it fast , but this method will get your job done.

JSP declaration scriptlet access bean

I got a situation with a project I'm working on (not my code). I'm a somewhat beginner with JSPs, so it would be great to find out what happened.
So I have a code like this (it's a lot simplified):
<jsp:useBean id="accessManager" scope="session" class="AccessManager" />
<%! Object x = accessManager %>
<% Object y = accessManager %>
The second line doesn't work, it doesn't know what accessManager is. The third line (y) works.
I know that declaration scriptlets translate into java class attributes or methods, which are executed once when the jsp in initialized, and normal scriptlets (<% %>) are translated into the _jspService method. But what's the scope of the two? Or why can't I access the bean from the declaration scriptlet?
Thanks!
! is used to specify a no-context.
If you use <%! Object x = accessManager; %> it will produce Code like this.
class Index {
Object x = accessManager;
}
If you use <% Object x = accessManager; %> it will produce Code like this:
class Index {
public void foo(){
Object x = accessManager;
}
}
Look at C:\Program Files\apache-tomcat-*\work\Catalina\localhost\*\org\apache\jsp\ for the Generated .java-File.
(The example is simplyfied.)
Use either of the declaration depending on where you would like to add the code in the servlet.
Scriptlet of the form <% code %> that are inserted into the servlet's service method. So, it becomes part of your application logic.
Scriptlet Declarations of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods. So, it becomes part of the servlet class. One very good use of it is to insert a method into servlet and use that method from within service method (under tag <% code %>) For ex:
<%!
public int sum(int a, int b) {
return a + b;
}
%>

JSP inner function printing

Should be direct HTML printing in a JSP declaration tag function legal?
<%! void recursivePaintLevels(List<String> things, int deepLevel){ %>
<ul class="level-<%=deepLevel%>">
<% for (int i=0; i<things.size(); i++){ %>
<li class="whatever">
//(...)
</li>
<% } %>
</ul>
<% } %>
And then call it like this in normal JSP body flow:
//(...)
<% recursivePaintLevels(things, 1); %>
I mean would be like using same normal JSP logic of implicit out.println() but in a method.
For me it is not working (Eclipse says 'Syntax error, insert "Finally" to complete TryStatement') but I am not sure if my error has something to do with it.
I also know I should use JSLT and EL, but this is my choice.
No, it's not legal. The JSP page is effectively implemented as one big method that executes all of the code within the page. In java, you can't simply insert other methods nested within a method.
You code would generate something like this:
public void _jspService(...) {
...
void recursivePaintLevels(...) {
...
}
}
And that's simply not legal java.
Instead you should defer the code to a utility library class bundled with your web app.
You MIGHT be able to create a recursive tag file, I have not tried that.
I believe this is pretty much legal and valid though a bad practice.I think the problem here is because of the double quotes "level-<%=deepLevel%>"
Try separating that using
<% String str= "level-"+deepLevel; %>
and then use
<ul class="<%=str%>"> .
or simply replace the whole line with out.println
EDIT:
It appears that the body of the methods in jsp should not have any scriptlets. I have tried to embed one scriptlet with no content and observed that the generated java file adds the first part (from delcaration to the content before scriptlet )at the begging and the remaining part of the method at the end (and all member variables and other method declarations become part of this method). Apologies for providing wrong answer (as i have noticed that behavior with the cached jsp).
Looks like out.prinltn is the only solution for this problem

Print simple String in EL without JSTL

I'm not sure if I can do this, but I'm trying to print a string with Expression Language only (no JSTL). The string is going to often-times be null, and I want an empty string printed to HTML instead of the word "null". This is what I'm trying (without success):
<%
myString = "";
myString = someMethodThatMayReturnNull(); // returns string or null
%>
<b>${myString}</b><br />
<b>${ (empty myString) ? "myString-is-empty" : "myString-is-NOT-empty" }</b><br />
The reason I don't want to use JSTL is because I'm trying to make the minimum changes to a fairly good sized system.
Scriptlets and EL doesn't share the same variable scope. You need to prepare EL variables as attributes of page, request, session or application scope. As you have right now, it is always empty.
<%
myString = "";
myString = someMethodThatMayReturnNull(); // returns string or null
request.setAttribute("myString", myString); // It's now available by ${myString}
%>
Note that you normally do that Scriptlet part inside a Servlet. Also note that EL is null-safe, so anything which is truly null, i.e. if (object == null) passes, then it simply won't be printed at all.
Or, if your concrete problem is that it prints literally ${myString} and so on in the browser, while it worked with JSTL <c:out>, then it means that you aren't using a JSP 2.0 compatible servletcontainer or that your webapp's web.xml is not declared conform at least Servlet 2.4, or that you have isElIgnored set to true. Verify and fix it all.
EL print the variables only when its available in pageContext scope. Here the variables are in page scope. If the variable is in some other scope, you have to specify the scope while using it. Do something like this to print the value of 'mystring' variable.
<%
myString = "stackoverflow";
pageContext.setAttribute("myString",myString);
%>
${myString}
It will print the value of myString, if myString is 'null' it will print empty string(nothing will be printed).
suppose if put the variable in request scope, you have to use "requestScope"
<%
myString = "stackoverflow";
request.setAttribute("myString",myString);
%>
${requestScope.myString}
why do u want to check String null in jsp code?
If you do not want to use scriptlet then you can check string null in mentod itself and return empty string in case of null.
myString = someMethodThatMayReturnNull(); // it should never return null.
And method is from other code then you can wrap this with your java code.

Categories