Pages

Subscribe Twitter Twitter

Monday, August 2, 2010

JSP QUESTIONS

JSP Questions

Directives
Page Directive <%@ 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” %> Page directive defines information that will be globally available for that page
Include Directive <%@ include file="relative URL" %> Include JSP are 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. We can also include “Static” files using this directive.
Taglib Directive <%@ taglib uri="uriToTagLibrary" prefix="prefixString" %> Taglib directive enables you to create your own custom tags.


Actions
type="" bean Name="" type=""
UseBean tag is used to associate a java bean with jsp.


Sets a property value or values in a bean.

Gets the value of a bean property so that you can display it in a result page.
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 includes the JSP are 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.





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 and it will also forward the http parameters of the previous page to the destination page. It will work at server side.

<%! private void processAmount () { ... } %>

XML syntax for JSP declaration is int x;

Q) Expressions
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.
Ex: <%= (new java.util.Date ()).toLocaleString() %>

XML syntax for JSP expression is Java expression

Q) Scriptlet
A scriptlet can contain variable or method declarations, or expressions that are valid in the page scripting language. Within scriptlet tags, you can
1.Declare variables or methods to use later in the file
2.Write expressions valid in the page scripting language
3.Use any of the JSP implicit objects or any object declared with a tag.
Scriptlets are 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.

XML syntax for JSP scriptlets is Java code

Q) Comments
Html comment  Creates a comment that is sent to the client in the viewable page source.
Ex: ] -->

Hidden Comment  Documents the JSP file, but is not sent to the client.
Ex: <%-- comment --%>


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: - is a screen representation of the model.

 Major benefits of using the MVC 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) Life-cycle of JSP
jspInit ()  container calls the jspInit() to initialize to servlet instance. It is called before any other method, and is 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. It is the last method called n the servlet instance.
 jspInit () & jspDestroy () called only once so we cannot override these methods.

Q) Diff RequestDispatcher.forward(req, res) & RequestDispatcher.include(req, res) & & res.sendRedirect( url)

RequestDispatcher.include(req, res) RequestDispatcher.include() and both include content. The included page is inserted into the current page or output stream at the indicated point.

RequestDispatcher.forward(req, res) in forward req, res would be passed to the destination url and the control will return back to the same method, It will execute at “server side”. (Or) RequestDispatcher.forward(), the servlet engine transfers control of this HTTP request internally from your current servlet or JSP to another servlet or JSP or static file.

Forwards a client request to an HTML file, JSP file, or 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.

res.sendRedirect(url) when ever the client request will come just it will take the request and the request to be forwarded to another page. It cannot forward the http parameters of the previous page. This will work at client side.

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()  does not involve the client's browser. It just takes browser's current request, and hands it off to another servlet/jsp to handle. The client doesn't know that they're request is being handled by a different servlet/jsp than they originally called.
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) Diff <%@ include file="file" %> &

<%@include file="abc.jsp"%> directive acts like C "#include", pulling in the text of the included file and compiling it as if it were part of the including file. The included file can be any type (including HTML or text). (Or) includes a jsp/servlet at compile time meaning only once parsed by the compiler.

include a jsp/servlet at request time it is not parsed by the compiler.

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 communicated with many numbers of objects, but jsp it is not possible.

Q) Can JSP be multi-threaded? How can I implement a thread-safe JSP page?
A) By default the service() method of all the JSP execute in a multithreaded fashion. You can make a page “thread-safe” and have it serve client requests in a single-threaded fashion by setting the page tag’s is Thread Safe attribute to false:
<%@ page is ThreadSafe=”false” %>

Q) How does JSP handle runtime exceptions?
A) You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example:
<%@ 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) 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);
%>

Proxy server caching
response.setHeader("Cache-Control","private");

Q) What's a better approach for enabling thread-safe servlets & JSPs? SingleThreadModel Interface or Synchronization?
A) 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 exhausts the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free.

Q) Servlet – to- JSP communicate?
public void doPost(HttpServletRequest req,
HttpServletResponse res)
{
Try{
govi.FormBean f = new govi.formBean();
string id = req.getParameter(“id”);
f.setName(req.getParameter(“name”));
f.setName(req.getParameter(“addr”));
f.setPersonalizationInfo(info);
req.setAttribute(“fBean”,f);
getServletConfig().getServletContext().getRequestDispatcher(“/jsp/Bean1.jsp”).forward(req, res);
} catch(Exception ex);
}
}

The jsp page Bean1.jsp can then process fBean,






Q) JSP- to-EJB Session Bean communicate?
<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %>
<%!
AccountHome accHome=null;
public void jspInit() {
InitialContext cntxt = new InitialContext( );
Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
}
%>
<%
Account acct = accHome.create();
acct.doWhatever(...);
%>

Q) Servlet output - to - another Servlet?

Servlet1
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(“/../srevlet2”) ;
rd.forward(req, res);

Servlet2

Public void service(servletRequest req, servletResponse res)
{
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(“/../srevlet1”) ;
rd.include(req, res);
}

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 to view an image stored on database with JSP?
<%@ page language="java" import="java.sql.*,java.util.*"%>
<%
String image_id = (String) request.getParameter("ID");
if (image_id != null){
try
{
Class.forName("interbase.interclient.Driver");
Connection con = DriverManager.getConnection("jdbc:interbase://localhost/D:/InterBase/examples/Database/employee.gdb","java","java");
Statement stmt = con.createStatement();
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 {
op.write(blocco[i]);
}
}
rs.close();
stmt.close();
con.close();
} catch(Exception e) {
out.println("An error occurs : " + e.toString());
}
}
%>

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?

2001: A Space Odyssey
The Waterboy
The Tin Drum
Being John Malkovich


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:

package foo;
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. The JSP code to process the posted form data is as follows:


<%! String[] movies; %>





<% movies = movieBean.getMovies();
if (movies != null) {
out.println("You selected:
");
out.println("
    ");
    for (int i = 0; i < movies.length; i++) {
    out.println ("
  • "+movies[i]+"
  • ");
    }
    out.println("
");
} else
out.println ("Don't you watch any movies?!");
%>

0 comments:

Post a Comment