Directives
Pag Page | <%@ Page language="java" extends="className" import="className" session="true|false" buffer="8KB" autoFlush="true/false" isThreadSafe="true/false" info="text" errorPage="jspUrl" isErrorPage="true/false" contentType="mimeType” isScriptingEnabled="true|false" isEnabled="true|false” %> XML syntax: - <Jsp: directive.page import=” ” /> | Page directive defines information that will be globally available for that page |
Include | <%@ include file="relative URL" %> XML syntax: - <Jsp: directive.include file=” ” /> <Jsp: directive.page file=” ” /> | Include JSP / Servlet at compile time meaning that only once parsed by the compiler, it will act as a “C” "#include" pulling in the text of the included file and compiling it as if it were part of the including file. |
Taglib | <%@ taglib uri="uriToTagLibrary" prefix="prefixString" %> XML syntax: - <Jsp: root xmlns:prefix1=”http://..” version=”1.2” /> </Jsp: root> | Taglib directive enables you to create your own custom tags. |
Actions
<Jsp: useBean> | <Jsp: useBean id="beanInstanceName" type="" bean Name="” scope="page|request|session|application” class=""/ /> | Is used to instantitate a java bean |
<Jsp: setProperty> | <Jsp: setProperty name="beanInstanceName” property="*" |"propertyName” param="paramName" value="{string | <%= expression %>}" /> | Sets a property value or values in a bean. |
<Jsp: getProperty> | <Jsp: getProperty name="beanInstanceName" Roperty="propertyName" /> | Gets the value of a bean property so that you can display it in a result page. |
<Jsp: param> | <Jsp: param name="beanInstanceName" value=" paramValue "/> | It is used to provide other tags with additional information in the form of name, value pairs. This is used to conjunction with jsp:include, jsp:forward, jsp:plugin. |
<Jsp: include> | <Jsp: include page="relativeURL " flush="true" > <Jsp: param name="username" value="jsmith" /> </jsp: include> | includes the JSP or Servlet at request time, it is not parsed by the compiler and it Includes a static file or sends a request to a dynamic file. |
<Jsp: forward> | <Jsp: forward page="{relativeURL|<%=expression %>}" > <jsp: param name="paramName" value="paramValue"/> </jsp: forward> | When ever the client request will come it will take the request and process the request and the request to be forward to another page (JSP/Sevlet) and it will also forward the http parameters of the previous page to the destination page. It will work at server side. |
<Jsp: plugin> | <Jsp: plugin type="bean/applet" code="classFileName" name="instanceName" codebase="classFileDirectoryName" archive="” align="" height="" width="" hspace="" vspace="”></jsp: plugin> | This action is used to generate client browser specific html tags that ensures the java plug in software is available, followed by execution of applet or java bean component specified in tag. |
Implicit Objects
Objects | Type / purpose | Scope | Sum useful methods |
Request | javax.servlet.http.ServletRequest - Refers to the current request passed to the _jspService() method | Request - Objects accessible from pages processing the request where they were created. | getAttribute, getParameter, getParameterNames, getParameterValues, setAttribute |
Response | javax.servlet.http.ServletResponse - Refers to the response sent to the client. It is also passed to the _jspService() method. | Page | Not typically used by JSP page authors |
Session | javax.servlet.http.HttpSession - JSP 1.2 specification states that if the session directive is set to false, then using the session keyword results in a fatal translation time error. | Session - Objects accessible from pages belonging to the same session as the one in which they were created. | getAttribute, getId, setAttribute. |
application | javax.servlet.ServletContext - Use it to find information about the servlet engine and the servlet environment. | Application - Objects accessible from pages belonging to the same application. | getAttribute, getMimeType, getRealPath, setAttribute |
Out | javax.servlet.jsp.JspWriter - Refers to the output stream of the JSP page. | Page | clear, clearBuffer, flush, getBufferSize, getRemaining |
Config | javax.servlet.ServletConfig - The initialization parameters given in the deployment descriptor can be retrieved from this object. | Page | getInitParameter, getInitParameterNames |
page | java.lang.Object. - Refers to the current instance of the servlet generated from the JSP page. | Page - Objects accessible only within jsp pages where it was created. | Not typically used by JSP page authors |
pageContext | javax.servlet.jsp.PageContext. - Provides certain convenience methods and stores references to the implicit objects. | Scope is up to Page | findAttribute, getAttribute, getAttributesScope, getAttributeNamesInScope, setAttribute. |
exception | java.lang.Throwable. - Available for pages that set the page directive attribute isErrorPage to true. It can be used for exception handling. | Page | getMessage, getLocalizedMessage, printStackTrace, toString |
Scriptlet | <% Java_code %> XML syntax: - <Jsp: scriptlet>Date day = new Date();</> | Business logic can written inside the Scriptlets. Scriptlets will executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it. |
Declaration | <%! int accountnumber=23468; %> <%! private void processAmount () { ... } %> XML syntax: - <jsp: declaration> int a=0; </> | Declares variables (or) methods. This is used for “Global declaration”. |
Expressions | <%= (new java.util.Date()).toLocaleString() %> XML syntax: - <jsp: expression> </> | An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. |
Comments | Html comment à Creates a comment that is sent to the client in the viewable page source. Ex: <! -- <%= expression %> --> Hidden Comment à Documents the JSP file, but it is not sent to the client. Ex: <%-- comment -- %> | Comments are removed from the viewable source of your HTML files by using only JSP comment tags. HTML comments remain visible when the user selects view source in the browser. |
Q) Life-cycle of JSP
* Page translation page is parsed and a java file which is a servlet is created.
* Page compilation page is compiled into a class file.
* Page Loading the class file is loaded.
* Create Instance Instance of servlet is created.
* jspInit( ) container calls the jspInit() to initialize to servlet instance. It will called only once for a servlet instance.
* _jspservice( ) container calls _jspservice() for each request, passing it the request and the response objects.
* jspDestroy( ) container calls this when it decides take the instance out of service.
* Destroy will called if the container crashes.
*jspInit() & jspDestroy() called only once so we cannot override these methods.
Q) Diff res.sendRedirect( ) & req.forward( )
* sendRedirect() sends a redirect response back to the client's browser. The browser will normally interpret this response by initiating a new request to the redirect URL given in the response.
* forward() the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container And then returns to the calling method.
For ex, if you want to hide the fact that you're handling the browser request with multiple servlets/jsp, and all of the servlets/jsp are in the same web application, use forward() or include(). If you want the browser to initiate a new request to a different servlet/jsp, or if the servlet/jsp you want to forward to is not in the same web application, use sendRedirect ().
Q) RequestDispatcher.include(req, res)
PageContext.forward()
<jsp: forward>
PageContext.forward() and RequestDispatcher.forward() are effectively the same. PageContext.forward is a helper method that calls the RequestDispatcher method.
The difference between the two is that sendRedirect always sends a header back to the client/browser. this header then contains the resource(page/servlet) which you wanted to be redirected. the browser uses this header to make another fresh request. thus sendRedirect has a overhead as to the extra remort trip being incurred. it's like any other Http request being generated by your browser. the advantage is that you can point to any resource(whether on the same domain or some other domain). for eg if sendRedirect was called at www.mydomain.com then it can also be used to redirect a call to a resource on www.theserverside.com.
In the case of forward() call, the above is not true. resources from the server, where the fwd. call was made, can only be requested for. But the major diff between the two is that forward just routes the request to the new resources which you specify in your forward call. that means this route is made by the servlet engine at the server level only. no headers are sent to the browser which makes this very efficient. also the request and response objects remain the same both from where the forward call was made and the resource which was called.
RequestDispatcher.include(req, res) RequestDispatcher.include() and <jsp:include> both include content. The included page is inserted into the current page or output stream at the indicated point. It will execute at “server side”.
<Jsp: forward> Forwards a client request to an HTML file/JSP file/servlet for processing. When ever the client request will come it will take the request and process the request and the request to be forward to another page, it will also forward the http parameters of the previous page to the destination page. It will execute at “server side” so the browser unaware of the changes. If page1.jsp redirects to page2.jsp, the browser address bar will still show page1.jsp. Forward operations are faster because all processing is done at server side. res.sendRedirect() operations updates the browser history.
Q) Diff Explicit Objects & Implicit Objects
Explicit objects are declared and created within the code of your JSP page, accessible to that page and other pages according to the scope setting you choose.
Explicit objects are typically JavaBean instances declared and created.
<jsp:useBean id="pageBean" class="mybeans.NameBean" scope="page" />
Implicit objects are created by the underlying JSP mechanism and accessible to Java scriptlets (or) expressions in JSP pages according to the inherent scope setting of the particular object type.
Q) MVC
Model : Model is java bean/entity beans that represent the data being transmitted are received.
Controller : Controller is a servlet that performs necessary manipulations to the model.
View : View is a screen representation of the model.
* Major benefits of using this design pattern is separate the view & model this make it is possible to create are change views with out having to change the model.
1) The browser makes a request to the controller servlet 2) Servlet performs necessary actions to the java bean model and forward the result to the jsp view 3) The jsp formats the model for display and send the html results back top the web browser.
Q) Optimization techniques
Page Directive
<%@ page session="true|false" buffer="none|8kb|size in kb" %>
By default JSP Engine creates session object. If you don't want then make session attribute value as false. It avoids unnecessary creation of session (implicit) object, reduces overhead on memory and garbage collector and increases performance.
Include Mechanism
For include directive, JSP Engine adds the content of the inserted page at compile time, so it does not have an impact on performance. For include action, JSP Engine adds the content of the inserted page at run time which imposes extra overhead.
useBean Action
<jsp:useBean id="objectName" scope="page|request|session|application" />
The scope effects the performance if you don't specify exact scope as per your requirement. What will happen if you set a session scope for an object which is needed only a request? The object will unnecessary reside in the memory even after your work is done. When using the session or application scope object you have to explicitly remove it after you are done. Otherwise the session object will be there in the memory till you explicitly remove or your server removes it after a configured time limit ( typically it is 30 minutes). It reduces the performance by imposing overhead on memory and garbage collector.
- Minimize code in the synchronized block
- Do not use custom tags if you do not have reusability
Q) Diff Jsp & Servlet
* Internally when jsp is executed by the server it get converted into the servlet so the way jsp & servlet work is almost similar.
* In jsp we can easily separate the P.L with B.L, but in servlet both are combined.
* One servlet object is communicate with many number of objects, but jsp it is not possible.
Q) Can JSP be multi-threaded? How can I implement a thread-safe JSP page?
By default the service() method of all the JSP execute in a multithreaded fashion. You can make a page “thread-safe” and serve client requests in a single-threaded fashion by setting the page tag’s is Thread Safe attribute to false:
<%@ page isThreadSafe=”false” %>
Q) How does JSP handle runtime exceptions?
You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page.
<%@ page errorPage=\"error.jsp\" %>
<%@ page errorPage=\"error.jsp\" %>
redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive:
<%@ page isErrorPage=\"true\" %>
Q) WebApplication scopes?
Request :- Life time is until the response is return to the user.
Session :- Until the session timeout (or) session id invalidate.
Application :- Life of container (or) explicitly killed.
Q) What's a better approach for enabling thread-safe servlets & JSPs? SingleThreadModel Interface (or) Synchronization?
SingleThreadModel technique is easy to use, and works well for low volume sites. If your users to increase in the future, you may be better off implementing explicit synchronization for your shared data
Also, note that SingleThreadModel is pretty resource intensive from the server's perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free.
Q) How many objects exist when a JSP has concurrent requests?
JSP documents are compiled to servlets when they are placed in service and operate like standard servlets. Usually a single JSP servlet instance is used to serve any number of virtually simultaneous requests, so only one servlet object exists. If your JSP servlet declares the page directive isThreadSafe="false", the servlet container may create a pool of instances to handle concurrent requests independently. In this case, the number of supporting objects would be multiplied accordingly.
Q) Diff ServletContext & PageContext?
The ServletContext holds references to the overall context of the Web application, such as the servlets that belong to the application, server information, logging facilities and global configuration settings.
The PageContext is a collection of request and response references for a single JSP servlet instance, for handling errors, forwarding requests and suchlike.
Q) Invoking a Servlet from a JSP page? Passing data to a Servlet invoked from a JSP page?
Use <jsp:forward page="/relativepath/YourServlet" />
Variables also can be sent as:
<jsp:forward page=/relativepath/YourServlet>
<jsp:param name="name1" value="value1" />
</jsp:forward>
(or)
response.sendRedirect("http://path/YourServlet").
Variables also can be sent as:
response.sendRedirect("http://path/YourServlet?param1=val1").
Q) How do you pass an InitParameter to a JSP?
<% ! ServletConfig cfg =null;
public void jspInit(){
ServletConfig cfg=getServletConfig();
for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) {
String name=(String)e.nextElement();
String value = cfg.getInitParameter(name);
System.out.println(name+"="+value);
} }
%>
Q) How do I prevent the output of my JSP or Servlet pages from being cached by the Web browser? And Proxy server?
Web browser caching
<% response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
%>
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
%>
Proxy server caching
response.setHeader("Cache-Control","private");
Q) How to view an image stored on database with JSP?
try {
ResultSet rs = stmt.executeQuery("SELECT * FROM IMMAGINE WHERE IMMAGINE_ID = " + image_id);
if (rs.next()) {
String dim_image = rs.getString("IMMAGINE_DIMENSIONE");
byte [] blocco = rs.getBytes("IMMAGINE_IMMAGINE");
response.setContentType("image/jpeg");
ServletOutputStream op = response.getOutputStream();
for(int i=0;i<Integer.parseInt(dim_image);i++) {
op.write(blocco[i]);
}
}
%>
Q) How do I pass values from a list box (with multiple selects) to a Java Bean?
Consider the following HTML, which basically allows the user to select multiple values by means of a checkbox:
What's your favorite movie?
<form method=post action=Movies.jsp>
<input type=checkbox name=faveMovies value="The Waterboy"> The Waterboy
<input type=checkbox name=faveMovies value="The Tin Drum"> The Tin Drum
<input type=submit>
</form>
To handle HTML elements like checkboxes and lists which can be used to select multiple values, you need to use a bean with indexed properties (arrays). The following bean can be used to store the data selected from the above check box, since it contains an indexed property movies:
public class MovieBean {
private String[] movies;
public MovieBean() {
String movies[] = new String[0];
}
public String[] getMovies() {
return movies;
}
public void setMovies(String[] m) {
this.movies = m;
}
}
Although a good design pattern would be to have the names of the bean properties match those of the HTML input form elements, it need not always be the case, as indicated within this example. JSP code to process the posted form data is as follows:
<%! String[] movies; %>
<jsp:useBean id="movieBean" class="foo.MovieBean">
<jsp:setProperty name="movieBean" property="movies" param="faveMovies" />
</jsp:useBean>
<% movies = movieBean.getMovies();
if (movies != null) {
out.println("You selected: <br>");
out.println("<ul>");
for (int i = 0; i < movies.length; i++) {
out.println ("<li>"+movies[i]+"</li>");
}
out.println("</ul>");
} else
out.println ("Don't you watch any movies?!");
%>
</html>