how to call inner class method or variable from outer jsp? - java

this is my index.jsp page:
<html>
<body>
<%!
public class myclass{
private final int foo = 42;
public int getFoo() {
return foo;
}
}
%>
</body>
</html>
how to call myclass method or variable in other jsp page ?
please help me .

You don't from any "other" JSP. Those declarations should be treated as local to the JSP. If you need a class to be used by multiple JSPs, write it as a separate Java source file, compile it, and include it in your webapp in WEB-INF/classes.

Did you try to use something like
<%# include file="/myFile.jsp" % >
???

Related

nullpointexception when i use those variables declared inside the scriptlet

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.

How to call java constant variables from jsp expression language in Spring?

I've spent a day looking for the right solution, but no luck!
The question is that how to call java constant variables from jsp with el ${bean.objectName} for example. What is the best practice?
I wonder if this is doable, im quite new to Spring and jsp.
Constant class:
public class RNConstant {
public static final String HELLO_WORLD = "Hello World again!";
public static final String DEFAULT_LOCALE = "id_ID";
public static final String CONTEXT_PATH_SOAP_SR = "soap.sr";
}
Expectation in jsp to be called with EL
<p>${RNConstant.HELLO_WORLD}</p>
I could do this with scriptlet as below, but i could not get this working if it runs in weblogic. This works in apache tomcat v7 or v8
<%# page import="static id.co.telkom.common.RNConstant.*" %>
...
...
<%= HELLO_WORLD %>
Error in weblogic
home.jsp:2:18: Syntax error on token "static", Identifier expected after this token
<%# page import="static id.co.telkom.common.RNConstant.*" %>
^-------------------------------------^
home.jsp:11:19: HELLO_WORLD cannot be resolved
Hello world! <%=HELLO_WORLD%>
^--------^
java version: 1.6
pom.xml
spring
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.6</java-version>
<org.springframework-version>3.2.8.RELEASE</org.springframework-version>
<org.springjs-version>2.0.5.RELEASE</org.springjs-version>
<org.springws-version>2.2.1.RELEASE</org.springws-version>
<org.springsecurity-version>3.2.3.RELEASE</org.springsecurity-version>
<jackson-version>1.9.10</jackson-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
</properties>
Scriplet issue was solved with below codes, and Content of RNConstant is still the same.
<%# page import="id.co.telkom.common.RNConstant" %>
...
...
<%= RNConstant.HELLO_WORLD %>
Cheers,
Hendry
Keep the import statement simple
<%# page import="static id.co.telkom.common.RNConstant.*" %>
Remove ".*" after RNConstant. Also remove static word in the beginning.
<%# page import="id.co.telkom.common.RNConstant" %>.
To call HELLO_WORLD constant use
<p>${RNConstant.HELLO_WORLD}</p> <p>${RNConstant.HELLO_WORLD}</p>
Expectation in jsp to be called with EL
<p>${RNConstant.HELLO_WORLD}</p>
EL checks the bean and translates HELLOWORLD to getHELLOWORLD() because specs says that attributes must be accessed in this way, so you must create a getter or visibility for constants will be limited in jsp view:
public class RNConstant
{
public final static String HELLO_WORLD = "Hello World again!";
public static String getHELLO_WORLD() {
return HELLO_WORLD;
}
}
If you can't create getters check this answer

Can't get JSP to recognize classes & functions in other JSPs

I'm supporting an older JSP system that may be using non-standard way of including classes and functions. Instead of writing classes files and compiling them into jar files, the classes are written directly in "child" JSPs and then included in a "parent" JSP.
The problem I'm having is that in JDeveloper, even though the IDE recognize the files in the include statement, I get error messages that MyClass and ChildFunction() are not defined. When I drop the 2 JSPs on the server, the page loads and runs with the expected results. As a result, when I work on the real code, I have a 1000+ line JSP with over a hundred syntax errors, so I can't tell if my code is even syntactically correct until I drop it on a server. I'm hoping its something simple (/stupid) like a classloader error or a bad configuration, but I haven't been able to fix it. Any help is greatly appreciated.
I've included two stub files below:
MyClass.jsp FILE:
<%# page import="java.lang.*,java.net.*,java.text.*,javax.servlet.http.*" %>
<%!
class MyClass() {
public MyClass() { super(); }
private int it=0;
public void setIt (int it) {this.it = it; }
public int getIt () { return it; }
}
public String ChildFunction(){
return " ChildFunction ";
}
%>
Parent.jsp FILE:
<%# page contentType="text/html;charset=WINDOWS-1252"%>
<%# page language="java" session="true" import="java.lang.*,java.net.*,java.text.*,javax.servlet.http.*" %>
<HTML>
<HEAD><TITLE>Test page</TITLE></HEAD>
<BODY>
<%# include file="./MyClass.jsp" %>
<br>Result of calling Child Function:<% out.print(ChildFunction()); %>
<br>Result of declaring MyClass:
<%
MyClass mc = new MyClass();
out.print(mc.getIt());
%>
</BODY>
</HTML>
Before someone suggest that I put the code in class files and use EAR/WAR files to deploy, that's not an option. This is an existing legacy system that I need to be able to support.
Don't put functions or subclasses in JSPs expecting to use them in others. (That is what they are after all, subclasses under that particular JSP.) It is very bad design. Create classes in actual .java files, compile them, and then call them from the JSPs. Even that is not particularly recommended (see How to avoid Java code in JSP files), but its better, a lot better.
If you have access to the filesystem, you don't need to put classes in a EAR/WAR. Just put them on the filesystem under webapps/{theApp}/WEB-INF/classes/...
You can even dispense with an IDE altogether, and just save all your .java files under webapps/{theApp}/WEB-INF/classes/... open a console, cd to that directory, and javac them. There is certainly no need to put class files in jars.
You do, of course, have to restart the application afterwards.

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

Categories