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.
Related
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
What is the difference between these two?
In JSP:
${pageContext.request.contextPath}
and how to achieve same results if coded without Expression Language and in a servlet?
In servlet:
request.getServletPath()
and how to achieve same results if coded in JSP?
${pageContext.request.contextPath} : Returns the portion of the request URI that indicates the context of the request. In fact, it is identical to request.getContextPath(), since ${pageContext.request} refers to the HttpServletRequest of the current request.
For example:
http://localhost:80/myapplication/path/servlet
${pageContext.request.contextPath} returns /myapplication
request.getServletPath() Returns the part of this request's URL that calls the servlet, e.g. /path/servlet
${pageContext.request.servletPath} returns /path/servlet
As an answer to the second part of your question:
request.getServletPath()and how to achieve same results if coded in
a JSP using Expression Language?
Here the equivalent of request.getServletPath()using Expression Language:
${pageContext.request.servletPath}
If you want to use other ServletRequest/HttpServletRequest methods by means of the Expression Language, just use ${pageContext.request.method}, where method is one of the appropriate methods.
In the case of a view handled by a JSP, then ${pageContext.request.servletPath} returned the path of the jsp, and not the servlet path from the web.xml.
To get that I used: ${requestScope['javax.servlet.forward.servlet_path']}
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.
I have a servlet (front-controller), which analyse the request, prepare some necessary data (model) and then should pass it to the jsp to be rendered.
How should I pass the data from servlet to jsp? (I hoped that it was possible to add new parameters to parameters map in the request object, but that map is unmodifiable).
I can add attributes to the request but I don't know how to retrieve them from the jsp.
All the data should be in the request scope. What's the correct way?
I can add attributes to the request but I don't know how to retrieve them from the jsp.
You don't need to specifically 'retrieve' them, just referring them works
request.setAttribute("titleAttribute", "kittens are fuzzy");
and then
Title here: ${titleAttribute}
You can use the request or the session scope for this. Apart from the answer by Nikita Rybak, you can use
request.getSession().setAttribute("key","value");
And then use it in JSP using scriplet.
<%=session.getAttribute("key")%>
Note that in the example given by Nikita, Expression Language(EL) has been used(I am not sure if it's JSTL tags). You need to explicitly state that EL is not to be ignored by using the isELIgnored property.
<%# page isELIgnored="false" %>
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.