Scriptlets let you insert arbitrary code into servlet's _jspService method.
Can anyone explain this statement with an example containing a block of code?
I am aware about syntactical stuff of JSP and Servlets, what I need to know is
In what context arbitrary code is used?
_jspService() is a method of JSP life cycle then,
What does it mean by servlet's method?
A JSP is in fact transformed by the container into a Java class extending HttpServlet, that class is then compiled and executed exactly as a hand-coded servlet would be.
The code you have into the JSP is transformed into Java code that constitutes the _jspService method of the generated servlet. So, for example
<html>
<% String foo = "hello"; out.println(foo); %>
is transformed by the container, into something like
void _jspService(JspWriter out) {
out.println("<html>");
String foo = "hello"; out.println(foo);
}
So, whatever code you write into your scriptlets (arbitrary code) ends up in the _jspService method of the servlet created by the container from the JSP.
Related
I have a JSP file named as project.jsp. It contains a variable
String context = request.getcontextpath();
which will deliver context path of my server URL.
/ARUBA-LIB-G3245-KITKAT from http://localhost:8080/ARUBA-LIB-G3245-KITKAT/.
Now I want to access this context variable from my project.jsp file to java class which is in jar format file and resides in WEB-INF/lib/AuthenticateDetails.jar.
How can I access this variable from specified java class file?
The same as in java, an import statement and so on.
<%# page import="java.util.Random"
import="org.authdetails.dao.SomeClass" %>
(Or many imports in one import=... with line break in string.
<% new SomeClass(contextPath); %>
Using the MVC (Model-View-Controller) principle, one normally has a servlet (Controller, compilable!) that prepares the data (Model) and puts the data as request attributes, and then forwards to the JSP (view).
In the JSP you can use EL (Expression Language) variables, where some are predefined to access session variables, request parameters and such.
Combining that with JSP tags, one rarely needs to use <% ... %> scriptlets.
Pass the context path variable to the processing method in the library class (library class should be accessible from the jsp though import directive)
JSP is thread safe by default but What is the meaning when we say
a JSP is thread-safe
?
When a jsp is create is become a servlet in the application server. All the logic runs from jspService method, all the references or variables you have in your jsp become local variables, that is why jsp can be considered thread safe by default.
Check this link to review the jsp lifecycle .
At the end all the code that you have in the jsp will be within the _jspService method.
All the content of your JSP will be inside.
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws java.io.IOException, ServletException {
JSP is not thread safe in general! JSP is compiled into servlet and one instance can be used to serve multiple requests, so every class field (modified during the request execution) is considered not being thread safe. How can you declare class field in JSP? Using JSP declaration:
<%! private Object notThreadSafe = new Object(); %>
(BTW you can even declare methods in JSP declarations).
JSP can be thread safe, if you don't use these JSP declarations. Everything else (html/jsp tags, scriptlet code <% /* some code*/ %>, jsp expression <%= "some expression" %>,... ) is being compiled into jspService method as Koitoer has mentioned.
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;
}
%>
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
I have a java class which performs some operations on files. Since the java code is huge I don't want to write this code in jsp. I want to call the methods in jsp whenever required.
Please tell me the path where I need to keep this file. Also some example code how to use it would be helpful.
In the servlet (which runs before the JSP):
Person p = new Person(); // instantiate business object
p.init(...); // init it or something
request.setAttribute("person", p); // make it available to the template as 'person'
In the template you can use this:
your age is: ${person.age} <%-- calls person.getAge() --%>
I think the question is, how do you make Java code available to a JSP? You would make it available like any other Java code, which means it needs to be compiled into a .class file and put on the classpath.
In web applications, this means the class file must exist under WEB-INF/classes in the application's .war file or directory, in the usual directory structure matching its package. So, compile and deploy this code along with all of your other application Java code, and it should be in the right place.
Note you will need to import your class in the JSP, or use the fully-qualified class name, but otherwise you can write whatever Java code you like using the <% %> syntax.
You could also declare a method in some other utility JSP, using <%! %> syntax (note the !), import the JSP, and then call the method declared in such a block. This is bad style though.
Depending on the kind of action you'd like to call, there you normally use taglibs, EL functions or servlets for. Java code really, really doesn't belong in JSP files, but in Java classes.
If you want to preprocess a request, use the Servlet doGet() method. E.g.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Preprocess request here.
doYourThingHere();
// And forward to JSP to display data.
request.getRequestDispatcher("page.jsp").forward(request, response);
}
If you want to postprocess a request after some form submit, use the Servlet doPost() method instead.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Postprocess request here.
doYourThingHere();
// And forward to JSP to display results.
request.getRequestDispatcher("page.jsp").forward(request, response);
}
If you want to control the page flow and/or HTML output, use a taglib like JSTL core taglib or create custom tags.
If you want to execute static/helper functions, use EL functions like JSTL fn taglib or create custom functions.
Although I'll not advice you to do any java calls in JSP, you can do this inside your JSP:
<%
//Your java code here (like you do in normal java class file.
%>
<!-- HTML/JSP tags here -->
In case you're wondering, the <% ... %> section is called scriptlet :-)
Actually, jsp is not the right place to 'performs some operations on files'. Did you hear about MVC pattern?
If you still interested in calling java method from jsp you can do it, for example:
1. <% MyUtils.performOperation("delete") %> (scriptlet)
2. <my-utils:perform operation="delete"/> (custom tag)
Anyway I recomend you to google about scriptlets, jsp custom tags and MVC pattern.
Best Regards, Gedevan