Thursday, 14 January 2016

Step by step configuration of Hibernate, Spring MVC, Primefaces

Step by step configuration of Hibernate, Spring MVC, Primefaces


So, you have decided to use Spring, Hibernate and Primefaces in your application. I am very much fond of each one of them cause, all of them very easy to use and open source. I use all of them in my own application.
But, the first time I tried to configure them in my application, I had nightmare. The most tough part was to configure Hibernate with Spring and to find how to use Spring beans in Managed Beans. But now my application is stable and development has become easy for me now.
So, I thought of sharing the knowledge to configure the application to use all of them.
I will use HSQL as DB for this post. I assume that you are capable of configuring your DB in the configuration files. Because, you are reading this post means, you are an advanced Java Developer.

Prerequisite
1.     You have knowledge on Spring, Hibernate and JSF and know the basics of setting them up individually
2.     Knowledge of Eclipse IDE or Maven or any other build tool
3.     Working database
4.     Hibernate 4 and Spring 4 (For another pair of these, generally these configuration needs a little change in the session factory configuration, which you can figure out in ease)
5.     Primefaces (3 or 4) and Spring(3 or 4)
This pair can have any combination. Choose any. Spring versioons are compatible with Primefaces versions.
Configuration
 I will go step by step for the configurations.


1. Mention the required libraries in your build - Required library list is huge cause Spring, Hibernate and Primefaces depend on different libraries. So please be careful otherwise you will get many exceptions. There are total 28 dependencies in total.
    §  antlr-2.7.7.jar
    §  commons-logging-1.1.1.jar
    §  dom4j-1.6.1.jar
    §  el-impl-2.2.1-b05.jar
    §  hibernate-commons-annotations-4.0.5.Final.jar
    §  hibernate-core-4.3.7.Final.jar
    §  hibernate-jpa-2.1-api-1.0.0.Final.jar
    §  hsqldb.jar
    §  jandex-1.1.0.Final.jar
    §  javassist-3.18.1-GA.jar
    §  jboss-logging-3.1.3.GA.jar
    §  jboss-logging-annotations-1.2.0.Beta1.jar
    §  jboss-transaction-api_1.2_spec-1.0.0.Final.jar
    §  jsf-api-2.2.8-02.jar
    §  jsf-impl-2.2.8-02.jar
    §  jstl-1.2.jar
    §  primefaces-4.0.jar
    §  spring-aop-4.1.3.RELEASE.jar
    §  spring-beans-4.1.3.RELEASE.jar
    §  spring-context-4.1.3.RELEASE.jar
    §  spring-context-support-4.1.3.RELEASE.jar
    §  spring-core-4.1.3.RELEASE.jar
    §  spring-expression-4.1.3.RELEASE.jar
    §  spring-jdbc-4.1.3.RELEASE.jar
    §  spring-orm-4.1.3.RELEASE.jar
    §  spring-tx-4.1.3.RELEASE.jar
    §  spring-web-4.1.3.RELEASE.jar
    §  spring-webmvc-4.1.3.RELEASE.jarWith all these dependencies, WebContent/WEB-INF/lib looks like

    2.       Setup JSF for your applicationDependency declaration is complete. The next step is to setup Faces for your application.
    In your web.xml mention faces servlet and the extensions you want to map with JSF and run your server. It should be working.
    If not, then delete the web.xml and retry. Here is one sample for ease.




     <?xml version="1.0" encoding="UTF-8"?>  
     <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
          xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
          http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
          id="WebApp_ID" version="2.5">  
          <display-name>PrimeFaces Web Application</display-name>  
          <!-- Change to "Production" when you are ready to deploy -->  
          <context-param>  
               <param-name>javax.faces.PROJECT_STAGE</param-name>  
               <param-value>Development</param-value>  
          </context-param>  
          <!-- Welcome page -->  
          <welcome-file-list>  
               <welcome-file>faces/index.xhtml</welcome-file>  
          </welcome-file-list>  
          <!-- JSF mapping -->  
          <servlet>  
               <servlet-name>Faces Servlet</servlet-name>  
               <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>  
               <load-on-startup>1</load-on-startup>  
          </servlet>  
          <!-- Map these files with JSF -->  
          <servlet-mapping>  
               <servlet-name>Faces Servlet</servlet-name>  
               <url-pattern>/faces/*</url-pattern>  
          </servlet-mapping>  
          <servlet-mapping>  
               <servlet-name>Faces Servlet</servlet-name>  
               <url-pattern>*.jsf</url-pattern>  
          </servlet-mapping>  
          <servlet-mapping>  
               <servlet-name>Faces Servlet</servlet-name>  
               <url-pattern>*.faces</url-pattern>  
          </servlet-mapping>  
          <servlet-mapping>  
               <servlet-name>Faces Servlet</servlet-name>  
               <url-pattern>*.xhtml</url-pattern>  
          </servlet-mapping>  
     </web-app>  
    

    3.       Add Spring MVC to FacesNow, add Spring MVC to your faces application. You have to include  Spring context file as context-param with param name contextConfigLocation and RequestContextListener and ContextLoaderListener as your application listener.
    So, basically you have to add three more tags in your web.xml.
    Now, it’s time to write faces-config.xml. Here you mention SpringBeanFacesELResolver as the EL Resolver for your faces application.
    After adding these, restart the server to check if configuration is working.
     <context-param>  
         <param-name>contextConfigLocation</param-name>  
         <param-value>  
           /WEB-INF/resources/context.xml  
         </param-value>  
       </context-param>  
          <listener>  
         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
       </listener>  
       <listener>  
         <listener-class>  
           org.springframework.web.context.request.RequestContextListener  
         </listener-class>  
       </listener>  
    

    This is the faces-config file 
     <?xml version="1.0" encoding="utf-8"?>  
     <faces-config xmlns="http://java.sun.com/xml/ns/javaee"  
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
     http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"  
          version="2.0">  
          <application>  
               <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>  
          </application>  
     </faces-config>  
    

    4.       Add Hibernate to SpringIn your context file, DriverManagerDataSource as data source, hibernate4.LocalSessionFactoryBean as sessionFactory and use this in your DAO classes. Add POJO, hibernate configurations and mappings etc in the project.
    Again restart the server and it is in complete configuration.


     <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans  
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
          <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">  
               <property name="driverClassName" value="org.hsqldb.jdbc.JDBCDriver">  
               <property name="url" value="jdbc:hsqldb:hsql://localhost:1521/opt/db">  
               <property name="username" value="SA">  
               <property name="password" value="">  
          </property></property></property></property></bean>  
          <bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">  
               <property name="dataSource" ref="dataSource">  
               <property name="configLocation" value="classpath:hibernate.cfg.xml">  
          </property></property></bean>  
          <bean class="dao.EmployeeDaoImpl" id="employeeDAO">  
               <property name="sessionFactory" ref="sessionFactory">  
          </property></bean>  
          <bean class="service.EmployeeService" id="service">  
               <property name="dao" ref="employeeDAO">  
          </property></bean>  
     </beans>  
    

    Hibernate configuration 
     <?xml version="1.0" encoding="utf-8"?>  
     <!DOCTYPE hibernate-configuration SYSTEM   
     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
     <hibernate-configuration>  
          <session-factory>  
               <property name="hibernate.dialect">  
                    org.hibernate.dialect.HSQLDialect  
               </property>  
               <property name="hibernate.connection.driver_class">  
                    org.hsqldb.jdbc.JDBCDriver  
               </property>  
               <!-- Assume test is the database name -->  
               <property name="hibernate.connection.url">  
                    jdbc:hsqldb:hsql://localhost:1521/opt/db  
               </property>  
               <property name="hibernate.connection.username">  
                    SA  
               </property>  
               <property name="hibernate.connection.password">  
               </property>  
               <!-- List of XML mapping files -->  
               <mapping resource="resources/Employee.hbm.xml" />  
          </session-factory>  
     </hibernate-configuration>  
    

    Mapping 
     <?xml version="1.0" encoding="utf-8"?>  
     <!DOCTYPE hibernate-mapping PUBLIC   
      "-//Hibernate/Hibernate Mapping DTD//EN"  
      "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">   
     <hibernate-mapping>  
       <class name="bean.Employee" table="EMPLOYEE">  
        <meta attribute="class-description">  
          This class contains the employee detail.   
        </meta>  
        <id name="sapCode" type="int" column="sap_code">  
          <generator class="native"/>  
        </id>  
        <property name="firstName" column="first_name" type="string"/>  
        <property name="lastName" column="last_name" type="string"/>  
        <property name="middleName" column="middle_name" type="string"/>  
       </class>  
     </hibernate-mapping>  
    

    5.   Retrieve Spring beans in Managed Beans
    All the setup is complete. To retrieve Spring beans, in your Managed beans, use @ManagedProperty on attributes.

     package managedbeans;  
     import javax.faces.bean.ManagedBean;  
     import javax.faces.bean.ManagedProperty;  
     import service.EmployeeService;  
     @ManagedBean(name = "editor")  
     public class EditorBean {  
          @ManagedProperty(name = "service", value = "#{service}")  
          private EmployeeService service;  
          private String value = "Editor";  
          /**  
           * @return the value  
           */  
          public String getValue() {  
               return value;  
          }  
          /**  
           * @param value  
           *      the value to set  
           */  
          public void setValue(String value) {  
               this.value = value;  
          }  
          /**  
           * @return the service  
           */  
          public EmployeeService getService() {  
               return service;  
          }  
          /**  
           * @param service  
           *      the service to set  
           */  
          public void setService(EmployeeService service) {  
               this.service = service;  
          }  
          public void save() {  
               System.out.println("Using service");  
               System.out.println(getValue());  
               System.out.println(service.getEmployees());  
          }  
     }  
    


    Enjoy the development with these components. They are really cool stuffs.

    I've complete websites built on top of these three only. They really are helpful for faster development, better maintainability, less coding, good looking GUI. You are free to take a look in the below locations,

    https://assistant-palash90.rhcloud.com/req-resp.asst

    https://temperatureconverter-palash90.rhcloud.com/
    Java Online Course | Java EE Training


    Java Training Institutes in Chennai | java j2ee training institutes in chennai | Java Training in Chennai | J2EE Training in Chennai | Java Course in Chennai


    Java Interview Questions | Java Training Institutes | Core Java Interview Questions Hibernate Training | Hibernate Online Training | Hibernate Training Courses | Hibernate Training in Chennai | Online Hibernate Training



    Monday, 11 January 2016

    JavaSE J2EE JavaEE Interview Questions

    Q:
    What is a output comment?
    A:
    A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.
    JSP Syntax
    <!-- comment [ <%= expression %> ] -->
    Example 1

    <!-- This is a commnet sent to client on
    <%= (new java.util.Date()).toLocaleString() %>
    -->

    Displays in the page source:
    <!-- This is a commnet sent to client on January 24, 2004 -->

    Q:
    What is a Hidden Comment?
    A:
    A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page.
    You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>. 
    JSP Syntax
    <%-- comment --%>
    Examples
    <%@ page language="java" %>
    <html>
    <head><title>A Hidden Comment </title></head>
    <body>
    <%-- This comment will not be visible to the colent in the page source --%>
    </body>
    </html>

    Q:
    What is a Expression?
    A:
    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. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like
    <%= someexpression %>
     <%= (new java.util.Date()).toLocaleString() %>
    You cannot use a semicolon to end an expression

    Q:
    What is a Declaration?
    A:
    A declaration declares one or more variables or methods for use later in the JSP source file.
    A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file.

    <%! somedeclarations %>
    <%! int i = 0; %>
    <%! int a, b, c; %>

    Q:
    What is a Scriptlet?
    A:
    A scriptlet can contain any number of language statements, 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 (see also Declaration).

    2.Write expressions valid in the page scripting language (see also Expression).

    3.Use any of the JSP implicit objects or any object declared with a <jsp:useBean> tag.
    You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.
    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.

    Q:
    What are implicit objects? List them?
    A:
    Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below
    • request
    • response
    • pageContext
    • session
    • application
    • out
    • config
    • page
    • exception

    Q:
    Difference between forward and sendRedirect?
    A:
    When you invoke a forward request, 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 completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

    Q:
    What are the different scope valiues for the <jsp:useBean>?
    A:
    The different scope values for <jsp:useBean> are
    1. page
    2. request
    3.session
    4.application

    Q:
    Explain the life-cycle mehtods in JSP?
    A:
    THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. The HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService().
    The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.
    The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.
    The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.
    Q:
    How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
    A:
    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.
    <%
    response.setHeader("Cache-Control","no-store"); //HTTP 1.1
    response.setHeader("Pragma\","no-cache"); //HTTP 1.0
    response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
    %>

    Q:
    How does JSP handle run-time 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\" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.
     

    Q:
    How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
    A:
    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. 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. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe .

    Q:
    How do I use a scriptlet to initialize a newly instantiated bean?
    A:
    A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.
    The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.

    <jsp:useBean id="foo" class="com.Bar.Foo" >
    <jsp:setProperty name="foo" property="today"
    value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>" / >
    <%-- scriptlets calling bean setter methods go here --%>
    </jsp:useBean > 

    Q:
    How can I prevent the word "null" from appearing in my HTML input text fields when I populate them with a resultset that has null values?
    A:
    You could make a simple wrapper function, like
    <%!
    String blanknull(String s) {
    return (s == null) ? \"\" : s;
    }
    %>
    then use it inside your JSP form, like
    <input type="text" name="lastName" value="<%=blanknull(lastName)% >" >

    Q:
    What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
    A:
    Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.
    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 - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool. 

    Q:
    How can I enable session tracking for JSP pages if the browser has disabled cookies?
    A:
    We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie.

    Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page. Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.
    hello1.jsp
    <%@ page session=\"true\" %>
    <%
    Integer num = new Integer(100);
    session.putValue("num",num);
    String url =response.encodeURL("hello2.jsp");
    %>
    <a href=\'<%=url%>\'>hello2.jsp</a>
    hello2.jsp<%@ page session="true" %>
    <%
    Integer i= (Integer )session.getValue("num");
    out.println("Num value in session is " + i.intValue());
    %> 
    Q:
    What is the difference b/w variable declared inside a declaration part and variable declared in scriplet part?
    A:
    Variable declared inside declaration part is treated as a global variable.that means after convertion jsp file into servlet that variable will be in outside of service method or it will be declared as instance variable.And the scope is available to complete jsp and to complete in the converted servlet class.where as if u declare a variable inside a scriplet that variable will be declared inside a service method and the scope is with in the service method.

    Q:
    Is there a way to execute a JSP from the comandline or from my own application?
    A:
    There is a little tool called JSPExecutor that allows you to do just that. The developers (Hendrik Schreiber <hs@webapp.de> & Peter Rossbach <pr@webapp.de>) aim was not to write a full blown servlet engine, but to provide means to use JSP for generating source code or reports. Therefore most HTTP-specific features (headers, sessions, etc) are not implemented, i.e. no reponseline or header is generated. Nevertheless you can use it to precompile JSP for your website. 
    Q:
    Explain the life cycle methods of a Servlet.
    A:
    The javax.servlet.Servlet interface defines the three methods known as life-cycle method.public void init(ServletConfig config) throws ServletException
    public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
    public void destroy()

    First the servlet is constructed, then initialized wih the init() method.
    Any request from client are handled initially by the 
    service() method before delegating to the doXxx() methods in the case of HttpServlet.

    The servlet is removed from service, destroyed with the 
    destroy() methid, then garbaged collected and finalized.


    Q:
    What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
    A:
    The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root.

    The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.


    Q:
    Explain the directory structure of a web application.
    A:
    The directory structure of a web application consists of two parts.
    A private directory called WEB-INF
    A public resource directory which contains public resource folder.

    WEB-INF folder consists of
    1. web.xml
    2. classes directory
    3. lib directory


    Q:
    What are the common mechanisms used for session tracking?
    A:
    Cookies
    SSL sessions
    URL- rewriting


    Q:
    Explain ServletContext.
    A:
    ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.


    Q:
    What is preinitialization of a servlet?
    A:
    A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the <load-on-startup> element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

    Q:
    What is the difference between Difference between doGet() and doPost()?
    A:
    A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following:
    http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN
    doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string.

    Q:
    What is the difference between HttpServlet and GenericServlet?
    A:
    A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1).
    Both these classes are abstract.

    Q:
    What is the difference between ServletContext and ServletConfig?
    A:
    ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized
    ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet.

    Q:
    What is a output comment?
    A:
    A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.
    JSP Syntax
    <!-- comment [ <%= expression %> ] -->

    Example 1

    <!-- This is a commnet sent to client on
    <%= (new java.util.Date()).toLocaleString() %>
    -->

    Displays in the page source:
    <!-- This is a commnet sent to client on January 24, 2004 -->

    Q:
    What is a Hidden Comment?
    A:
    A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page.
    You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>. 
    JSP Syntax
    <%-- comment --%>
    Examples
    <%@ page language="java" %>
    <html>
    <head><title>A Hidden Comment </title></head>
    <body>
    <%-- This comment will not be visible to the colent in the page source --%>
    </body>
    </html>

    Q:
    What is a Expression?
    A:
    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. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like
    <%= someexpression %>
     <%= (new java.util.Date()).toLocaleString() %>
    You cannot use a semicolon to end an expression

    Q:
    What is a Declaration?
    A:
    A declaration declares one or more variables or methods for use later in the JSP source file.
    A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file.

    <%! somedeclarations %>
    <%! int i = 0; %>
    <%! int a, b, c; %>

    Q:
    What is a Scriptlet?
    A:
    A scriptlet can contain any number of language statements, 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 (see also Declaration).

    2.Write expressions valid in the page scripting language (see also Expression).

    3.Use any of the JSP implicit objects or any object declared with a <jsp:useBean> tag.
    You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.
    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.

    Q:
    What are implicit objects? List them?
    A:
    Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below
    • request
    • response
    • pageContext
    • session
    • application
    • out
    • config
    • page
    • exception

    Q:
    Difference between forward and sendRedirect?
    A:
    When you invoke a forward request, 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 completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

    Q:
    What are the different scope valiues for the <jsp:useBean>?
    A:
    The different scope values for <jsp:useBean> are
    1. page
    2. request
    3.session
    4.application

    Q:
    Explain the life-cycle mehtods in JSP?
    A:
    THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. The HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService().
    The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.
    The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.
    The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.
    Q:
    How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
    A:
    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.
    <%
    response.setHeader("Cache-Control","no-store"); //HTTP 1.1
    response.setHeader("Pragma\","no-cache"); //HTTP 1.0
    response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
    %>

    Q:
    How does JSP handle run-time 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\" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.
     

    Q:
    How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
    A:
    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. 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. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe .

    Q:
    How do I use a scriptlet to initialize a newly instantiated bean?
    A:
    A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.
    The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.

    <jsp:useBean id="foo" class="com.Bar.Foo" >
    <jsp:setProperty name="foo" property="today"
    value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>" / >
    <%-- scriptlets calling bean setter methods go here --%>
    </jsp:useBean > 

    Q:
    How can I prevent the word "null" from appearing in my HTML input text fields when I populate them with a resultset that has null values?
    A:
    You could make a simple wrapper function, like
    <%!
    String blanknull(String s) {
    return (s == null) ? \"\" : s;
    }
    %>
    then use it inside your JSP form, like
    <input type="text" name="lastName" value="<%=blanknull(lastName)% >" >

    Q:
    What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
    A:
    Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.
    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 - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool. 

    Q:
    How can I enable session tracking for JSP pages if the browser has disabled cookies?
    A:
    We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie.

    Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page. Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.
    hello1.jsp
    <%@ page session=\"true\" %>
    <%
    Integer num = new Integer(100);
    session.putValue("num",num);
    String url =response.encodeURL("hello2.jsp");
    %>
    <a href=\'<%=url%>\'>hello2.jsp</a>
    hello2.jsp<%@ page session="true" %>
    <%
    Integer i= (Integer )session.getValue("num");
    out.println("Num value in session is " + i.intValue());
    %> 
    Q:
    What is the difference b/w variable declared inside a declaration part and variable declared in scriplet part?
    A:
    Variable declared inside declaration part is treated as a global variable.that means after convertion jsp file into servlet that variable will be in outside of service method or it will be declared as instance variable.And the scope is available to complete jsp and to complete in the converted servlet class.where as if u declare a variable inside a scriplet that variable will be declared inside a service method and the scope is with in the service method.

    Q:
    Is there a way to execute a JSP from the comandline or from my own application?
    A:
    There is a little tool called JSPExecutor that allows you to do just that. The developers (Hendrik Schreiber <hs@webapp.de> & Peter Rossbach <pr@webapp.de>) aim was not to write a full blown servlet engine, but to provide means to use JSP for generating source code or reports. Therefore most HTTP-specific features (headers, sessions, etc) are not implemented, i.e. no reponseline or header is generated. Nevertheless you can use it to precompile JSP for your website. 
    Q:
    Explain the life cycle methods of a Servlet.
    A:
    The javax.servlet.Servlet interface defines the three methods known as life-cycle method.
    public void init(ServletConfig config) throws ServletException
    public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
    public void destroy()

    First the servlet is constructed, then initialized wih the init() method.
    Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet.

    The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.


    Q:
    What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
    A:
    The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root.

    The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.


    Q:
    Explain the directory structure of a web application.
    A:
    The directory structure of a web application consists of two parts.
    A private directory called WEB-INF
    A public resource directory which contains public resource folder.

    WEB-INF folder consists of
    1. web.xml
    2. classes directory
    3. lib directory


    Q:
    What are the common mechanisms used for session tracking?
    A:
    Cookies
    SSL sessions
    URL- rewriting


    Q:
    Explain ServletContext.
    A:
    ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.


    Q:
    What is preinitialization of a servlet?
    A:
    A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the <load-on-startup> element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

    Q:
    What is the difference between Difference between doGet() and doPost()?
    A:
    A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following:
    http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN
    doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string.

    Q:
    What is the difference between HttpServlet and GenericServlet?
    A:
    A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1).
    Both these classes are abstract.

    Q:
    What is the difference between ServletContext and ServletConfig?
    A:
    ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized
    ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet.