In Expression Language, I can access my model like so: ${model.member}
How do I achieve the same thing when I want to use <%=some_method(${model.member}); %>
The reason is because I have some HTML helper methods I created to separate logic from UI, and I need to pass a member of the model to create the user control.
The JSP's main method has the following signature:
_jspService(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException
Based on this, you can access the request and response objects programattically from a scriptlet. For example:
<%= request.getParameter("foo").toString() %>
or
<%= request.getAttribute("bar").toString() %>
If you want to do something more complication, you could precede these with scriptlets to declare / initialize local (Java) variables; e.g.
<% String foo = request.getParameter("foo") == null ?
"no foo" : request.getParameter("foo").toString(); %>
<%= foo %>
You can use this to lookup your model in the request or response object (I think it will be an attribute of the request with name "model"), cast it to the appropriate type, and call its getter methods.
The reason is because I have some HTML helper methods I created to separate logic from UI, and I need to pass a member of the model to create the user control.
A better idea would be to turn those helper methods into custom JSP tags so that you can use them without resorting to scriptlets. JSPs with embedded scriptlets are generally thought to be hard to read and hard to maintain. One small mistake (or one change to the model API) and the JSP generates bad Java on your deployment platform and you get a broken page.
Take a look at JSTL custom functions. It allows a way for you to call static functions from your code in a JSTL standard way. You just need to set then up in your tld file.
Related
I need to call in a JSP a method that is defined in another JSP that should be included dynamically (include page ) not statically (include file), but I get a jsp compilation error "method is undefined". It works fine when I use <%#include file=""%>.
The reason I need this is that our JSP ends up getting too big and we get this error: "The code of method _jspService(HttpServletRequest, HttpServletResponse) is exceeding the 65535 bytes limit" (whence the need to include other jsps dynamically), therefore we're splitting some of its funcionality into smaller JSPs.
Foo.jsp
<%#page language="java"%>
<%!
public String getSomeID(String param) throws Exception {
return "someId";
}
%>
Bar.jsp
<jsp:include page="Foo.jsp"></jsp:include>
String id = getSomeID(param);
I'm aware that the better option here is to use a preprocessing servlet. We'll probably do that. But, for now, I merely wish to know if it is possible to call methods from another jsp while including it dynamically.
You can't reference the code from your Foo.jsp in Bar.jsp
if you are doing that with jsp:include.
Both pages in that cases are compiled into independent servlets behind the scene. Let's call them Foo_Servlet and Bar_Servlet.
What actually happens in that case is the following: Bar_Servlet while handling the request passes control and original request to Foo_Servlet.
Once Foo_Servlet completes the response of execution of Foo_Servlet (and not original jsp code) is combined with a response of Bar_Servlet.
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
We often do the following inside the scriptlet:
<%
request.getCookies();
%>
Can anyone tell me, what is request here? I know it represents HttpServletRequest but I haven't declared it. I just do not understand this.
request is a variable of type HttpServletRequest that is declared and initialized for you in the code generated by the servlet container when the JSP code is transformed into a Servlet class and compiled, it also known as one of implicit objects in JSP.
Note that using scriptlets in JSP is bad practice for years. You should learn JSP EL, the JSTL, and choose an MVC framework that allows separating the Java code for the pure markup-generation code.
When we can access all the implicit variables in JSP, why do we have pageContext ?
My assumption is the following: if we use EL expressions or JSTL, to access or set the attributes we need pageContext. Let me know whether I am right.
You need it to access non-implicit variables. Does it now make sense?
Update: Sometimes would just like to access the getter methods of HttpServletRequest and HttpSession directly. In standard JSP, both are only available by ${pageContext}. Here are some real world use examples:
Refreshing page when session times out:
<meta http-equiv="refresh" content="${pageContext.session.maxInactiveInterval}">
Passing session ID to an Applet (so that it can communicate with servlet in the same session):
<param name="jsessionid" value="${pageContext.session.id}">
Displaying some message only on first request of a session:
<c:if test="${pageContext.session['new']}">Welcome!</c:if>
note that new has special treatment because it's a reserved keyword in EL, at least, since EL 2.2
Displaying user IP:
Your IP is: ${pageContext.request.remoteAddr}
Making links domain-relative without hardcoding current context path:
login
Dynamically defining the <base> tag (with a bit help of JSTL functions taglib):
<base href="${fn:replace(pageContext.request.requestURL, pageContext.request.requestURI, pageContext.request.contextPath)}/">
Etcetera. Peek around in the aforelinked HttpServletRequest and HttpSession javadoc to learn about all those getter methods. Some of them may be useful in JSP/EL as well.
To add to #BalusC's excellent answer, the PageContext that you are getting might not be limited to what you see in the specification.
For example, Lucee is a JSP Servlet that adds many features to the interface and abstract classes. By getting a reference to the PageContext you can gain access to a lot of information that is otherwise unavailable.
All 11 implicit EL variables are defined as Map, except the pageContext variable.
pageContext variable provides convenient methods for accessing request/response/session attributes or forwarding the request.
I need to call a method of java class from jsp page.. While calling that in jsp page, need to set some request parameters also. How do i do that in jsp page?
Ex :
Java class :
public void execute() {
string msg = request.getParameter("text");
}
JSP file :
I need to call the method here and also need to set parameter values (eg : &text=hello)
Please help me...
Just embed your Java code inside the JSP. The object "request" is available to get parameters (parameters can't be set). Unless you plan to forward to another JSP in another context with an attribute should be enough.
To refer to your own class do not forget to add the import statement at the beginning of the JSP (similiar to an import in a Java class).
<!-- JSP starts here -->
<%#page import="test.MyClass" %>
<%
MyClass myClass = new MyClass();
String text=myClass.execute();
// This is not neccessary for this JSP since text variable is already available locally.
// Use it to forward to another page.
request.setAttribute("text");
%>
<p>
This is the <%=text%>
</p>
You cannot set request parameters. I suggest you try using the attributes as suggested in the previous answers.
You can't set request parameters - they're meant to have come from the client.
If you need to give the method some information, you should either use normal method parameters, or some other state. The request parameters are not appropriate for this, IMO.