22
The include file is done at translation-time. The include directive should be used to include static content. The include action version is a dynamic include it is a full JSP that is executed, and its output is included in the parent JSP. The include page is done at request-time. The include action should be used to include static/dynamic content. Include Directive <%@ include file="relativeURL" %> Include Action (or jsp:include) <jsp:include page="{relativeURL | <%= expression %>}" /> or <jsp:include page="{relativeURL | <%= expression %>}"> <jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" /> </jsp:include> pagejava.lang.Object The page object represents the generated servlet instance itself, i.e., it is same as the "this" keyword used in a Java file. As a result, you do not typically know who the super class is, and consequently do not normally make use of this object or its methods. The pageContext object represents the environment for the page, containing useful information like page attributes, access to the request, response and session objects, as well as the JspWriter referenced by out. 1

JSP SARANS

Embed Size (px)

Citation preview

Page 1: JSP SARANS

The include file is done at translation-time. The include directive should be used to include static content.

The include action version is a dynamic include it is a full JSP that is executed, and its output is included in the parent JSP. The include page is done at request-time. The include action should be used to include static/dynamic content.

Include Directive

<%@ include file="relativeURL" %>

Include Action (or jsp:include)

<jsp:include page="{relativeURL | <%= expression %>}" />or <jsp:include page="{relativeURL | <%= expression %>}"> <jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" /></jsp:include>

pagejava.lang.Object

The page object represents the generated servlet instance itself, i.e., it is same as the "this" keyword used in a Java file. As a result, you do not typically know who the super class is, and consequently do not normally make use of this object or its methods.

The pageContext object represents the environment for the page, containing useful information like page attributes, access to the request, response and session objects, as well as the JspWriter referenced by out.

pageContextjavax.servlet.jsp.PageContext

application = pageContext.getServletContext (); config = pageContext.getServletConfig (); session = pageContext.getSession (); out = pageContext.getOut ();

1

Page 2: JSP SARANS

A JSP page services requests as a servlet.

jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.

_jspService(): The container calls the _jspService() for each request and it passes the request and the response objects. _jspService() method cann?t be overridden.

jspDestroy(): The container calls this when its instance is about to destroyed.

The jspInit() and jspDestroy() methods can be overridden within a JSP page.

These methods are generated after JSP page translated and compiled, the JSP pages's servlet follows the servlet life-cycle:

If an instance of the JSP page's servlet does not exist, the container o Loads the JSP page's servlet class

o Instantiates an instance of the servlet class

o Initializes the servlet instance by calling the jspInit method

The container invokes the _jspService method, passing request and response objects.

If the container needs to remove the JSP page's servlet, it calls the jspDestroy method.

JSP scriptlet (i.e., <% scriptlet %>) and experssion (i.e., <%= expression%>), when translated into a servlet, will end up in the body of doGet or doPost method.

JSP declaration (i.e., <%! declaration %>), when translated into a servlet, will end up being instance variables or methods in the servlet class.

A variable defined inside of a JSP declaration could translate to an instance variable and a variable defined inside of a JSP scriptlet could translate to a local variable in doGet or doPost method.

You may have jspInit() or jspDestroy() methods defined in the JSP declaration. They are equivalent to Servlet's init() and destory() methods.

A server side comments is of the form

<%-- comments --%>

The client-side style, or output comments

<!-- comments ... -->

2

Page 3: JSP SARANS

JSP pages are compiled dynamically into servlets when requested, so page authors can easily make updates to presentation code. JSP pages can also be precompiled if desired.

JSP handle runtime exceptions<%@ page errorPage="error.jsp" %><%@ page isErrorPage="true" %><%= exception.getMessage() %>

With the following stack trace:

<% ByteArrayOutputStream baos = new ByteArrayOutputStream(); exception.printStackTrace(new PrintStream(baos)); out.print(baos);%>When an error page is also indicated in the web.xml descriptor, the JSP error page applies first, then the web.xml.

You can not override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() may be overridden to perform some initialization task i.e., allocating resources like database connections, network connections, and so forth for the JSP page. jspDestroy() may be overridden to manually release some resorces that the jsp file is holding.

The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations:

<%!public void jspInit() {. . .}%><%!public void jspDestroy() {. . .}%>

The jspDestroy() method is only called when the JSP container is shut down, not after processing each request. It doesn't have access to any of the implicit JSP objects (since they are local variables in the _jspService() method).

3

Page 4: JSP SARANS

The response object handles the output to the client. This object can be used for creating HTTP Headers, creating cookies, setting content type and redirecting workflow.

Bascilly, the <jsp:include page=... /> happens at runtime but <%@ include file=... %> happens at compile time. <jsp:include> simply passes control to a different page for a while. Under <jsp:include>, the two pages share 'request' scope but have a different 'page' scope.

Servlets are well suited for dynamically generating binary data such as images or a new content type.

the implicit objects are not available in declarative part of JSP. JSP pages are translated into servlets and then they are compiled before they can be viewed. Declaring a variable in a JSP page means that the variable will become a (non static) class attribute in the corresponding servlet. At the time when the servlet is compiled, there is no such thing as a request because a request can't come in until after the servlet is compiled and made available by the container.

In other words, request is a input parameter for the _jspService() method, therefore can only be accessed within _jspService() method.

Note that the exception object is created only if the JSP uses the page directive to set isErrorPage set to true. When a JSP generates an error and forwards that error to the error page, it sets the JSP exception object of the error page to the generated error

First page

<%@page errorPage="ErrorPage.jsp" %>

ErrorPage.jsp

<%@ page isErrorPage='true' %><%out.print("Error Message : "); out.print(exception.getMessage());%>

There are two kind of errors, compile-time errors and Runtime errors, can occur in the JSP lifecycle:

Compile-time errors : Compile-time errors occur when a client first invokes a JSP. JRun transforms the JSP into its XML view, and then compiles a servlet from the XML view. If an error occurs at any time during this process, a compile-time error is thrown. You

4

Page 5: JSP SARANS

must catch that error outside of the JSP. However, if you do not test or precompile the JSP, you might not catch the error at all.

Runtime errors : Runtime errors occur when a JSP successfully compiles but then tries to process code that contains an invalid statement; for example, when you try to include a nonexistent file. Runtime errors are easy to handle because you know that the JSP compiled successfully, you just need to catch the error and examine the output.

Cookies are stored on the server and referenced with a session ID that is passed back and forth between the client and the server. Cookies are a general mechanism used by server-side applications to store information in individual browsers. The server-side application can retrieve cookies stored in a browser. With cookies, your web application can create specific variables for each browser. Such variables might include a user name or the last-accessed date. Cookies provide a persistence mechanism that you can use to compensate for the HTTP protocol stateless nature.

<% out.println("Cookies received by the server:");

Cookie[] myCookies = request.getCookies();

for(int n=0; n < myCookies.length; n++) { out.print("[" + myCookies[n].getName() + "] = "); out.print(myCookies[n].getValue() + ";"); }

out.println("Cookies added by the server:"); Cookie objCookie = new Cookie("domain", "www.xyzws.com"); objCookie.setPath("/"); objCookie.setMaxAge(60*60*24*365); response.addCookie(objCookie); ....%>

So if your starting page is a JSP, a session would have already been created when you get the first request.

<%@ page session="false" %>

This will prevent a session from being created when a JSP is served.

5

Page 6: JSP SARANS

If "true" then the implicit script language variable named "session" of type javax.servlet.http.HttpSession reference the current/new session for the page. If "false" then the page does not participate in a session; the "session" implicit variable is unavailable, and any reference to it within the body of the JSP page is illegal and shall result in a fatal translation error. Default is "true".

A JavaBean is basically a Java class which satisfies a few simple rules (it must have a public no-arg constructor, no public instance variables, properties have getters and setters; actually, you can get around the last rule by supplying a BeanInfo object for your bean).

getServletConfig().getServletContext().getRealPath(request.getServletPath()); //returns file name and pathapplication.getRealPath(request.getServletPath()); //returns file name and paththis.getClass().getName(); //returns the class name

The request.getSession() returns the current HttpSession associated with this request, or if the request does not have a session, creates one new session.

The request.getSession(boolean create) returns the current HttpSession associated with this request or, if there is no current HttpSession and create is true, returns a new session. If create is false and the request has no valid HttpSession, this method returns null and no new session created.

There is actually no difference between the request.getSession() method and the request.getSession(true) method.

request.getParameter() always returns String value and the data come from client. request.getAttribute() to get an object added to the request scope on the server side i.e. using request.setAttribute().

<%@ page import="java.util.*" import="java.io.*"%><% request.setAttribute("PAGE", "first.jsp");%><jsp:forward page="/second.jsp"/>

and second.jsp

<%@ page import="java.util.*" import="java.io.*"%>From Which Page : <%=request.getAttribute("PAGE")%><br>Data From Client : <%=request.getParameter("CLIENT")%>

6

Page 7: JSP SARANS

The basic difference between getAttribute() and getParameter() is that the first method extracts a (serialized) Java object and the other provides a String value.

Implicit objects are a set of Java objects that the JSP Container makes available to developers in each page. These objects may be accessed as built-in variables via scripting elements and can also be accessed programmatically by JavaBeans and Servlets. The implicit objects are created automatically for you within the service method.

What is the difference between jsp:forward and response.sendRedirect?

The <jsp:forward ..> is actually a call to HttpServletRequest.forward(String url) which passes the request object within the server to either a servlet or a JSP page. The new servlet or JSP page continues to process the same request and the browser is not aware of the fact that more than one servlet or page is involved. In other words, the client is not aware that the request is being forwarded anywhere. The URL shown in the browser stays unchanged when you do forward.

The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file. The lines in the source JSP file after the <jsp:forward> element are not processed.

The page invoked by the <jsp:forward> action has access to all the parameters in the original request object. You can add new parameters to the request object to pass to the target page by using the <jsp:param name="..." value="..." />.

Be careful when using <jsp:forward> with unbuffered output. If the JSP file has any data in the out object, using will cause an IllegalStateException.

The response.sendRedirect() creates a new request object which doesn't carry any of old requests. The first request handler JSP page tells the browser to make a new request to the target servlet or JSP page. The URL shown in the browser therefore changes to the URL of the new page when you redirect.

A redirect is slower than a forward because the browser has to make a new request. Another difference is that request scope objects are no longer available after a redirect because it results in a new request. If you need to pass data to the page you redirect to, you have to use a query

7

Page 8: JSP SARANS

string and pass them as request parameters (or save the data as session or application scope objects).

Forward is faster than redirect but one disadvantage is that URL is not changed and also it works with in same web application. Also, when you choice to use forward, you need to ask what happens if the user reloads the page.

Expressions of the form <%= expression%> that are evaluated and inserted into output, Scriptlets of the form <% code %> that are inserted into the servlets service method, and

Declarations of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods.

implicit objects

Object Class or Interface Description & Scope

request http.HttpServletRequest Data included with the HTTP Request. request scope.

response http.HttpServletResponseHTTP Response data, e.g. cookies. page scope.

pageContextjsp.pageContextProvides access to all the namespaces associated with a JSP page and access to several page attributes. page scope.

session http.HttpSession User specific session data. session scope.

applicationServletContext Data shared by all application pages. application scope.

out jsp.JspWriter Output stream for page context. page scope.

config ServletConfig Servlet configuration information. page scope.

page jsp.HttpJspPage Page's servlet instance. page scope.

Note that the implicit variables are only available within the jspService method and thus are not available within any declarations.

8

Page 9: JSP SARANS

Within a scriptlet, you can do any of the following:

Declare variables or methods to use later in the JSP page. Write expressions valid in the page scripting language.

Use any of the implicit objects or any object declared with a <jsp:useBean> element.

Write any other statement valid in the scripting language used in the JSP page.

If you want to use the characters "%>" inside a scriptlet, enter "%\>" instead.

When you write a declaration in a JSP page, remember these rules:

You must end the declaration with a semicolon (the same rule as for a Scriptlet, but the opposite of an Expression).

<% int i = 0;%>

You can already use variables or methods that are declared in packages imported by the page directive, without declaring them in a declaration element.

You can declare any number of variables or methods within one declaration element, as long as you end each declaration with a semicolon. The declaration must be valid in the Java programming language.

<% int i = 0; long l = 5L; %>

For example,

<%@ page import="java.util.*" %><HTML><BODY><%! Date getDate() { System.out.println( "In getDate() method" ); return new Date(); }%>Hello! The time is now <%= getDate() %></BODY></HTML>

Can I declare static variables by using the JSP declaration?

9

Page 10: JSP SARANS

Yes, You can. For example,

<%! static public int counter = 0; %>

The effect of this declaration is to create an integer variable named counter that is shared by all instances of the page's servlet class. If any one instance changes the value of this variable , all instances see the new value. In practice, because the JSP container typically creates only one instance of the servlet class representing a particular JSP page, there is a little difference between declaring instance variables and class variables. The major exception to this rule is when a JSP page sets the isThreadSafe attribute of the page directive to false, indicating that the page is not thread-safe. In this case, the JSP container may create multiple instances of the page's servlet class, in order to handle multiple simultaneous requests,one request per instance. Now to share a variable 's value across multiple requests under these circumstances, the variable must be declared as static: class variable , rather than an instance variable.

When the isThreadSafe attribute is true, which is default, however , it makes little practical difference. Declaring as instance variable saves a little bit typing.

The request object retrieves the values that the client browser passed to the server during an HTTP request such as headers, cookies or parameters associated with the request.

getParameter(String param) returns the value of the specified parameter as a string if it exists or null if it doesn't.

getParameterValues(String param) returns an array of String objects containing all of the values that the given request parameter has or null if the parameter doesn't have any values.

getParameterNames() returns an Enumeration object that contains the names of all the parameters contained in the request. If the request has no parameters, the method returns an empty Enumeration object.

Enumeration parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()){ String parameterName = (String) parameterNames.nextElement(); String parameterValue = request.getParameter(parameterName); out.println(parameterName + " has value " + parameterValue + "<br>");

String[] radioStrs = request.getParameterValues("radioGroup"); if (radioStr != null) { for (int i = 0; i < radioStrs.length; i++){ out.println(radioStrs[i] + "<br>"); }

10

Page 11: JSP SARANS

The request implicit object is an instance of HTTPServletRequest, and response is an instance of HTTPServletResponse objects.

The request object retrieves the values that the client browser passed to the server during an HTTP request such as headers, cookies or parameters associated with the request.The response can be used for the same purposes as the HttpServletResponse in a servlet, such as creating HTTP Headers, creating cookies, setting content type and redirecting workflow.

The session implicit object is an instance of javax.servlet.http.HttpSession. This variable is only valid for Http protocols. The session is one of the JSP built-in variables (like request) that is available in the service body of a JSP.

How to display all the session variables in an HTML page?<%@ page language="java" import="java.util.*" %><html><body>Session attributes:<% session.setAttribute("test.name", "Test Attribute List"); session.setAttribute("test.float", new Float(5.0)); session.setAttribute("test.int", new Integer(10)); session.setAttribute("test.Object", new StringBuffer("StringBuffer")); session.setAttribute("test.boolean", new Boolean(true)); session.setAttribute("test.double", new Double(343.1)); for (Enumeration e = session.getAttributeNames(); e.hasMoreElements(); ) { String attribName = (String) e.nextElement(); Object attribValue = session.getAttribute(attribName);%><BR><%= attribName %> - <%= attribValue %>

<%}%></body></html>

How can I retain the session when using window.open() to open a new window?

It depends on where you are opening your new window from?

If it is a JSP then just use the encodeURL method to generate the new window URL. Something like the following for your url:

<%=response.encodeURL(...)%>

11

Page 12: JSP SARANS

all that does is put the session id on the end of the url as an additional name/value pair in the query.

If it is an HTML page then how is it generated? If it just a static file then I dont think you can get the session info to it, you'll have to change the page to be generated by a JSP or servlet. If it is already generated by a servlet you can jst use the encodeURL method to create the URL and place it in the generated page.

The following JSP code changes the session timeout value:

<p>The session timeout is: <%=session.getMaxInactiveInterval()%></p><%session.setMaxInactiveInterval(3000);%><p>The session timeout has been set to: <%=session.getMaxInactiveInterval()%></p>

So if you are using a JSP as the starting point try adding this decaration to your page:

<%@ page session="false" %>

This will prevent a session from being created when a JSP is served.

It's important to note, though, that if you store objects in the application, session, request or page contexts, they are not guaranteed to be thread safe. The response and exception objects are created for the current thread and therefore they are safe.

Although the request and page objects themselves are threadsafe, objects stored in them are only safe if they are not also used by other threads. Remember that one of these contexts only stores a reference to an object, not a separate copy of it.

For example, if you create a completely new object in the method, and place it in the request context, it will be threadsafe:

<% String name = new String("Kevin"); request.setAttribute("user", name);%>

If you use an existing object which is also present in one of the unsafe contexts (application or session), it will not be threadsafe:

12

Page 13: JSP SARANS

<% String name = (String)session.getAttribute("name"); request.setAttribute("user", name);%>

If you use an existing object which is a static (class) or member (instance) variable in the servlet class, it will not be threadsafe:

<%! String name = (String)session.getAttribute("name");%><% request.setAttribute("user", name);%>

The JSP page by default is not thread safe, if you want to make it thread safe then you have add the following directive in your JSP page declaration:

<%@ page isThreadSafe="false" %>

With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine.

JSPs are normally perfectly thread-safe, since your run of the JSP does not hold any state (member variables).

For example, if you happen to use <%! %>, this will place the code in class level and not in the _jspService method. You introduce class member into the JSP object that makes JSP becomes thread-unsafe.

If your JSP is not thread-safe you will have to add the isThreadSafe=false in order for things to work correctly. Such way, it does not make your JSP thread-safe but it does make your web application thread-safe by instructing the servlet container to cater for the thread-unsafety of your JSP:

If isThreadSafe=true then the JSP container may choose to dispatch multiple outstanding client requests to the page simultaneously. Page authors using true must ensure that they properly synchronize access to the shared state of the page.

13

Page 14: JSP SARANS

If isThreadSafe=false then the JSP container shall dispatch multiple outstanding client requests, one at a time, in the order they were received, to the page implementation for processing.

Note that even if the isThreadSafe attribute is false the JSP page author must ensure that accesses to any shared objects are properly synchronized., The objects may be shared in either the ServletContext or the HttpSession

The page implicit object is of type Object and it is assigned a reference to the servlet that executing the _jspService() method. Page is the instance of the JSP page's servlet processing the current request.

Since page is a variable of type Object, it cannot be used to directly call the servlet methods. To access any of the methods of the servlet through page it must be first cast to type Servlet.

<%= this.getServletInfo(); %><%= ((Servlet)page).getServletInfo(); %>

But the following code will generate error, because can not use page directly without casting:

<%= page.getServletInfo(); %>

The config object is an object of type javax.servlet.ServletConfig. The ServletConfig for this JSP page. Has a page scope.

The config can be used to retrieve the configuration parameters that are specific to a JSP page. These parameters are set up within the deployment descriptor.

The config object can be used to retrieve the ServletContext object through its getServletContext() method. Thus the following code retrieves information about the currently executing server, and in my own setup it generates the output.

<%ServletContext ct = config.getServletContext();out.print(ct.getServerInfo());%>

The application implicit object is an instance of javax.servlet.ServletContext.

The deployment descriptor file web.xml

<web-app> <context-param> <param-name>applparam</param-name> <param-value>applvalue</param-value> </context-param>

14

Page 15: JSP SARANS

<servlet> <servlet-name>TestServlet</servlet-name> <jsp-file>/index.jsp</jsp-file> <init-param> <param-name>pageparam</param-name> <param-value>pagevalue</param-value> </init-param> </servlet>

<servlet-mapping> <servlet-name>TestServlet</servlet-name> <url-pattern>/test.jsp</url-pattern> </servlet-mapping>

<servlet> <servlet-name>TestServlet1</servlet-name> <jsp-file>/test1.jsp</jsp-file> </servlet>

<servlet-mapping> <servlet-name>TestServlet1</servlet-name> <url-pattern>/test1.jsp</url-pattern> </servlet-mapping>

</web-app>

The file test.jsp

<% out.print(application.getInitParameter("applparam")); out.print(config.getInitParameter("pageparam"));%>

The file test1.jsp

<% out.print(application.getInitParameter("applparam")); out.print(config.getInitParameter("pageparam")); //null%>

The out implicit object is used for writing data to the output stream and is an object of type javax.servlet.jsp.JspWriter.

JSP page authors are prohibited from writing directly to either the PrintWriter or OutputStream associated with the ServletResponse.(See JavaServer Pages Specification Version 1.2): For example, you can not use the following code in you JSP otherwise you will get compiling error:

<% response.getWriter().println("Hello!"); %>

15

Page 16: JSP SARANS

What is the pageContext implicit object?

A pageContext implicit object is used for storing and retrieving page-related information and sharing objects within the same translation unit and same request. Also used as a convenience class that maintains a table of all the other implicit objects.

It stores referece to the implicit objects. The following example shows how PageContext is used to populate other implicit objects.

public void _jspService (HttpServletRequest request, HttpServletResponse response)

throws java.io.IOException, ServletException { ... try { ... application = pageContext.getServletContext (); config = pageContext.getServletConfig (); session = pageContext.getSession (); out = pageContext.getOut (); ... } catch (Throwable t) { ... } finally { ... } } Provides convenience methods to get and set attributes in different scopes. This

example uses attributes to save and retrieve data in each of the four scopes: <% // Save data pageContext.setAttribute("attr1", "value0"); // PAGE_SCOPE is the

default pageContext.setAttribute("attr2", "value1", PageContext.PAGE_SCOPE); pageContext.setAttribute("attr3", "value2",

PageContext.REQUEST_SCOPE); pageContext.setAttribute("attr4", "value3",

PageContext.SESSION_SCOPE); pageContext.setAttribute("attr5", "value4",

PageContext.APPLICATION_SCOPE); %> <%-- Show the values --%> <%= pageContext.getAttribute("attr1") %> <%= pageContext.getAttribute("attr2", PageContext.PAGE_SCOPE) %> <%= pageContext.getAttribute("attr3", PageContext.REQUEST_SCOPE) %>

16

Page 17: JSP SARANS

<%= pageContext.getAttribute("attr4", PageContext.SESSION_SCOPE) %> <%= pageContext.getAttribute("attr5", PageContext.APPLICATION_SCOPE) %>

Provides convenience methods for transferring requests to other resources in your application:

PageContext

   

  void include (String relativeURL)

Includes the output of another resource in the output of the current page. Same as ServletRequest.getRequestDispatcher ().include ();

  void forward (String relativeURL)

Forwards the request to another resource.

Same as

ServletRequest.getRequestDispatcher ().forward ();

For example, to forward a request to another resource from a servlet, we have to write the following to lines:

RequestDispatcher rd = request.getRequestDispatcher ("other.jsp"); rd.forward (request, response);

In a JSP page, we can do that in just one line by using the pageContext variable:

pageContext.forward ("other.jsp");

A PageContext instance is obtained by a JSP implementation class by calling the JspFactory.getPageContext() method, and is released by calling JspFactory.releasePageContext().

17