Tuesday 30 October 2012

JSP INTERVIEW QUESTIONS

These are collections of interview questions and answers regarding JSP.


What is  JSP and its used for?
Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page.

What are the two kinds of comments in JSP?
<%-- JSP Comment --%>
<!-- HTML Comment -->

What is JSP technology?
Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSPs are secure, platform-independent, and best of all, make use of Java as a server-side scripting language.
What is JSP page?
A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content.

How many  implicit objects in JSP?
Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are:
1. request
2. response
3. pageContext
4. session
5. application
6. out
7. config
8. page 
9. exception
How many JSP scripting elements and what are they?
There are three scripting language elements:
--declarations
--scriptlets
--expressions

Why are JSP pages preferred API for creating a web-based client program?
Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.

Is  JSP technology extensible?
YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

Can we use the constructor, instead of init(), to initialize servlet?
Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.

Can you explain What is JSP page life cycle?
When first time a JSP page is request necessary servlet code is generated and loaded in the servlet container. Now until the JSP page is not changed the compiled servlet code serves any request which comes from the browser. When you again change the JSP page the JSP engine again compiles a servlet code for the same.
JSP page is first initialized by jspInit() method. This initializes the JSP in much the same way as servlets are initialized, when the first request is intercepted and just after translation.

Every time a request comes to the JSP, the container generated _jspService() method is invoked, the request is processed, and response generated.

When the JSP is destroyed by the server, the jspDestroy() method is called and this can be used for clean up purposes.

How do I include static files within a JSP page?
Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.
Why does JComponent have add() and remove() methods but Component does not?
because JComponent is a subclass of Container, and can contain other components and jcomponents. How can I implement a thread-safe JSP page? - You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" % > within your JSP page.
How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.
How do you restrict page errors display in the JSP page?
You first set "Errorpage" attribute of PAGE directory to the name of the error page (ie Errorpage="error.jsp")in your jsp page .Then in the error jsp page set "isErrorpage=TRUE". When an error occur in your jsp page it will automatically call the error page.
What do you understand by JSP Actions?
JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon, followed by the action name followed by one or more attribute parameters.
There are six JSP Actions:
<jsp:include/>
<jsp:forward/>
<jsp:plugin/>
<jsp:usebean/>
<jsp:setProperty/>
<jsp:getProperty/> 

What is the difference between <jsp:include page = ... > and
<%@ include file = ... >?.
Both the tag includes the information from one page in another. The differences are as follows:
<jsp:include page = ... >: This is like a function call from one jsp to another jsp. It is executed ( the included page is executed  and the generated html content is included in the content of calling jsp) each time the client page is accessed by the client. This approach is useful to for modularizing the web application. If the included file changed then the new content will be included in the output.

<%@ include file = ... >: In this case the content of the included file is textually embedded in the page that have <%@ include file=".."> directive. In this case in the included file changes, the changed content will not included in the output. This approach is used when the code from one jsp file required to include in multiple jsp files.
  
What is the difference between <jsp:forward page = ... > and
response.sendRedirect(url),?.

The <jsp:forward> element forwards the request object containing the client request information from one JSP file to another file. 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.
sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page. The  response.sendRedirect kills the session variables.
 

implicit Objects
Implicit objects are the objects available to the JSP page. These objects are created by Web container and contain information related to a particular request, page, or application. The JSP implicit objects are:
Variable
Class
Description
application
javax.servlet.ServletContext
The context for the JSP page's servlet and any Web components contained in the same application.
config
javax.servlet.ServletConfig
Initialization information for the JSP page's servlet.
exception
java.lang.Throwable
Accessible only from an error page.
out
javax.servlet.jsp.JspWriter
The output stream.
page
java.lang.Object
The instance of the JSP page's servlet processing the current request. Not typically used by JSP page authors.
pageContext
javax.servlet.jsp.PageContext
The context for the JSP page. Provides a single API to manage the various scoped attributes.
request
Subtype of javax.servlet.ServletRequest
The request triggering the execution of the JSP page.
response
Subtype of javax.servlet.ServletResponse
The response to be returned to the client. Not typically used by JSP page authors.
session
javax.servlet.http.HttpSession
The session object for the client.

What are all the different scope values for the <jsp:useBean> tag?
<jsp:useBean> tag is used to use any java object in the jsp page. Here are the scope values for <jsp:useBean> tag:
a) page
b) request
c) session and
d) application
  
What is JSP Output Comments?
JSP Output Comments are the comments that can be viewed in the HTML source file.
Example:
<!-- This file displays the user login screen -->
and
<!-- This page was loaded on
<%= (new java.util.Date()).toLocaleString() %> -->
 
What is expression in JSP?
Expression tag is used to insert Java values directly into the output. Syntax for the Expression tag is:
<%= 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. The following expression tag displays time on the output:
<%=new java.util.Date()%>
  
What types of comments are available in the JSP?
There are two types of comments are allowed in the JSP. These are hidden and outputcomments. A hidden comments does not appear in the generated output in the html, while output comments appear in the generated output.
Example of hidden comment:
<%-- This is hidden comment --%>
Example of output comment:
<!-- This is output comment -->
 
What is JSP declaration?
JSP Decleratives are the JSP tag used to declare variables. Declaratives are enclosed in the <%! %> tag and ends in semi-colon. You declare variables and functions in the declaration tag and can use anywhere in the JSP. Here is the example of declaratives:
<%@page contentType="text/html" %>
<html>
<body>
<%!
int cnt=0;
private int getCount(){
//increment cnt and return the value
cnt++;
return cnt;
}
%>
<p>Values of Cnt are:</p>
<p><%=getCount()%></p>
</body>
</html>
  
What is JSP Scriptlet?
JSP Scriptlet is jsp tag which is used to enclose java code in the JSP pages. Scriptlets begins with <% tag and ends with %> tag. Java code written inside scriptlet executes every time the JSP is invoked.
Example:
  <%
  //java codes
   String userName=null;
   userName=request.getParameter("userName");
   %>
  
What are the life-cycle methods of JSP?
Life-cycle methods of the JSP are:
a) 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.
b)_jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann't be overridden.
c) jspDestroy(): The container calls this when its instance is about to destroyed.
The jspInit() and jspDestroy() methods can be overridden within a JSP page.

Friday 26 October 2012

HOW TO SEND EMAIL USING JSP

Create a new java web project and create index.jsp page, Then copy the below code and paste in the index.jsp page.



<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Pankaj Bhardwaj</title>
</head>
<body>
<table border="1" width="50%"  cellpadding="0" cellspacing="0">
  <tr>
  <td width="100%">
  <form method="POST" action="mail.jsp"> 
  <table border="1" width="100%" cellpadding="0" cellspacing="0">
  <h1>TEST</h1>
  <tr>
  <td width="50%"><b>To:</b></td>
  <td width="50%"><input type="text" name="to" size="30"></td>
  </tr>
  <tr>
  <td width="50%"><b>From:</b></td>
  <td width="50%"><input type="text" name="from" size="30"></td>
  </tr>
  <tr>
  <td width="50%"><b>Subject:</b></td>
  <td width="50%"><input type="text" name="subject" size="30"></td>
  </tr>
  <tr>
  <td width="50%"><b>Description:</b></td>
  <td width="50%"><textarea name="description" type="text" 
    cols="40" rows="15" size=100>
  </textarea>
  </td>
  </tr>
  <tr>
  <td><p><input type="submit" value="Send Mail" name="sendMail"></td>
  </tr>
  </table>
  </p>
  </form>
  </td>
  </tr>
</table>
</body>
</html>


Now, Create another jsp page naming mail.jsp and copy and paste the below code in this page.



<%@ page language="java" import="javax.naming.*,java.io.*,javax.mail.*,
javax.mail.internet.*,com.sun.mail.smtp.*"%>
<html>
<head> 
<title>Mail</title>
</head>
<body>
<%
try{
  Session mailSession = Session.getInstance(System.getProperties());
  Transport transport = new SMTPTransport(mailSession,new URLName("localhost"));
  transport.connect("localhost",8084,null,null);
  MimeMessage m = new MimeMessage(mailSession);
  m.setFrom(new InternetAddress(%><%request.getParameter("from")%><%));
  Address[] toAddr = new InternetAddress[] {
  new InternetAddress(%><%request.getParameter("to")%><%)
  };
  m.setRecipients(javax.mail.Message.RecipientType.TO, toAddr );
  m.setSubject(%><%request.getParameter("subject")%><%);
  m.setSentDate(new java.util.Date());
  m.setContent(%><%request.getParameter("description")%><%, "text/plain");
  transport.sendMessage(m,m.getAllRecipients());
  transport.close();
  out.println("Thanks for sending mail!");
}
catch(Exception e){
  out.println(e.getMessage());
  e.printStackTrace();
}
%>
</body>
</html>


NOTE: you must add the activation.jar and mail.jar file in your libraries. Otherwise the code will not work properly.



Thursday 18 October 2012

Login with User Name and Password field in java.

This is only the code behind login button  !!!

If you wish to make login page then use this, Simple code for access in a web using user name and password with database connectivity using stored procedure.. 





private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        String user = jTextField2.getText();
        String strpass = jPasswordField2.getText();
        try {
            // TODO add your handling code here:
            Connection con = DBConnection.getDBConnection();
            CallableStatement cs = con.prepareCall("{call USP_LOGIN(?,?)}");
            cs.setString(1, user);
            cs.setString(2, strpass);
            cs.executeQuery();
            ResultSet rs = cs.getResultSet();
            boolean recordfound = rs.next();
            if(recordfound)
            { Desktop.removeAll();  
     Desktop.repaint();  
     Home home = new Home();
   home.setBounds(0, 0, 1280, 980);
     Desktop.add(home);  
     home.setVisible(true); 
     home.jLabel1.setText("WELCOME : "+user);
            }
            else {
                jLabel10.setText("Invalid User ID And Password");
            }    
            
            } catch (SQLException ex) {
            Logger.getLogger(index.class.getName()).log(Level.SEVERE, null, ex);
        }
    }        




Jtable from Database using stored procedure.


Dynamically populate jtable from database with data elements in JAVA.



import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Vector;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author Pankaj
 */
public class ManageInvoice extends javax.swing.JPanel {

    /**
     * Creates new form ManageInvoice
     */
    public ManageInvoice() {
        initComponents();
        Vector columnNames = new Vector();
        Vector data = new Vector();
        try
        {
            Connection conn=DBConnection.getDBConnection();      // DBConnection class with static method                                                                                                                                
                                                                                           //getDBConnection declaring database path    
                                                                                          //and username and password.
            String sql = "{CALL USP_MANAGE_INVOICE()}";
           CallableStatement stmt=conn.prepareCall(sql);                 //If you are using stored procedure
            ResultSet rs = stmt.executeQuery();
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();
            columnNames.add("S.NO.");
            for (int i = 2; i <= columns; i++)
            {
                columnNames.addElement( md.getColumnName(i) );
            }
            int j =1;
            while (rs.next())
            {
                Vector row = new Vector(columns);
                row.add(j++);
                for (int i = 2; i <= columns; i++)
                {
                    row.addElement( rs.getObject(i) );
                }
                row.add(5, new Boolean(true));
                data.addElement( row );
            }
            rs.close();
            stmt.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        JTable table = new JTable(model)
                {
            //  Returning the Class of each column will allow different
            //  renderers to be used based on Class
            public Class getColumnClass(int c)
            {
                return getValueAt(0, c).getClass();
            }
            public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            if (col > 0) {
                System.out.print("hi");
                return true;
            } else {
                 System.out.print("hi2");
                return false;
            }
        }
        };
        TableColumn col;
        for (int i = 0; i < table.getColumnCount(); i++)
        {
            col = table.getColumnModel().getColumn(i);
            col.setMaxWidth(250);
        }
        jScrollPane1.setViewportView(table);
    }
}

Wednesday 17 October 2012

Print button for pdf and dialog box

Print button in java for creating PDF with dialog box. just copy code and paste in a new java 

application to check out this button for pdf generating.






import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintableDemo1 implements Printable {
  public int print(Graphics g, PageFormat pf, int pageIndex) {
    if (pageIndex != 0)
      return NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2Dg;
    g2.setFont(new Font("Serif", Font.PLAIN, 36));
    g2.setPaint(Color.black);
    g2.drawString("Java Source and Support!"144144);
    return PAGE_EXISTS;
  }

  public static void main(String[] args) {
    PrinterJob pj = PrinterJob.getPrinterJob();
    pj.setPrintable(new PrintableDemo1());
    if (pj.printDialog()) {
      try {
        pj.print();
      catch (PrinterException e) {
        System.out.println(e);
      }
    }
  }

}

COLLECTION RELATED INTERVIEW QUESTIONS.

Q:
What is the Collections API?
A:
The Collections API is a set of classes and interfaces that support operations on collections of objects.
Q:
What is the List interface?
A:
The List interface provides support for ordered collections of objects.


Q:
What is the Vector class?
A:
The Vector class provides the capability to implement a growable array of objects. 

Q:
What is an Iterator interface?
A:
The Iterator interface is used to step through the elements of a Collection .
Q:
Which java.util classes and interfaces support event handling?
A:
The EventObject class and the EventListener interface support event processing.

Q:
What is the GregorianCalendar class?
A:
The GregorianCalendar provides support for traditional Western calendars

Q:
What is the Locale class?
A:
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region .

Q:
What is the SimpleTimeZone class?
A:
The SimpleTimeZone class provides support for a Gregorian calendar .

Q:
What is the Map interface?
A:
The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.
Q:
What is the highest-level event class of the event-delegation model?
A:
The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy.

Q:
What is the Collection interface?
A:
The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates.
Q:
What is the Set interface?
A:
The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.
Q:
What is the typical use of Hashtable?
A:
Whenever a program wants to store a key value pair, one can use Hashtable.
Q:
I am trying to store an object using a key in a Hashtable. And some other object already exists in that location, then what will happen? The existing object will be overwritten? Or the new object will be stored elsewhere?
A:
The existing object will be overwritten and thus it will be lost.


Q:
What is the difference between the size and capacity of a Vector?
A:
The size is the number of elements actually stored in the vector, while capacity is the maximum number of elements it can store at a given instance of time.


Q:
Can a vector contain heterogenous objects?
A:
Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.
Q:
Can a ArrayList contain heterogenous objects?
A:
Yes a ArrayList can contain heterogenous objects. Because a ArrayList stores everything in terms of Object.
Q:
What is an enumeration?
A:
An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.


Q:
Considering the basic properties of Vector and ArrayList, where will you use Vector and where will you use ArrayList?
A:
The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one.
Q:
Can a vector contain heterogenous objects?
A:
Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.