Showing posts with label JSP/SERVLET. Show all posts
Showing posts with label JSP/SERVLET. Show all posts

Wednesday 21 August 2013

Can we call init method in service method of servlet?

This is a very tricky question asked in an interview. The servlet lifecycle is a very important question in any java interview. The goal behind asking this question is to check the knowledge of servlet lifecycle of the candidate. This question can be modified in many ways like can we call destroy method in service method etc. (Read the link --http://javaitblog.blogspot.in/2013/04/what-happens-if-you-call-destroy-from.html). 
For the question “can we call init method in service method”, the direct answer is “Yes”. We can call init method in service method for any number of times. The init method initializes the ServletConfig parameter or initializes the servlet instance. The init method will be called by the container only once when it is started. So there is no use of calling it again in the service method but if we want, we can call it in the service method. To understand it more clearly, please see the below example.
Example Code:
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/demoCalInitMethod")
public class demoCalInitMethod extends HttpServlet {
                private static final long serialVersionUID = 1L;
                ServletConfig config;
                int count=0;
                  
    public demoCalInitMethod() {
        super();
    }

                public void init(ServletConfig config) throws ServletException {
                                this.config = config;
                                ++count;
                }
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
               
                                System.out.println("The value of count variable before calling init methods in service method :- "+count);
                                init(config);
                                init(config);
                                init(config);
                                init(config);
                                init(config);
                                System.out.println("The value of count variable before calling init methods in service method :- "+count);
                }

                protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                                }

                protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                }

}

Output :-

The value of count variable before calling init methods in service method :- 1
The value of count variable before calling init methods in service method :- 6

In the above example, the init method is called in service method for five times. In init method, we incremented an integer type variable “count” with one so whenever this method is called it will increment the value of “count” variable by one. We printed the value of count variable in service method before and after calling the init method explicitly. As the output showing above, it printed the value of count 1 before calling the init methods explicitly (Because container calls it once automatically when it loads the servlet) and 6 after calling  the init methods explicitly because  we called the init method for five times in service method.
So init will initiate the servlet n times if call the init method n times with same ServletConfig object.

Tuesday 6 August 2013

How can we perform Exception Handling in JSP?

Exception handling can be performed in JSP with three ways
  1. Using page directive (isErrorPage=”True” and errorPage=”error.jsp”).
  2. Using simple Try/catch  
  3. Using JSTL

  1.  Page Directive Exception Handling: - This is the most common way of JSP exception handling. In this approach, we use the errorPage and isErrorPage methods of page directive. As in the below example, we used two JSP pages.
·         generateException.jsp
·         error.jsp
The generateException page used the errorPage method of page directive for describing the name of the page which will handle the exceptions occurred in the page (As error.jsp in below example). Now when any exception will occur in the generateException page, it will go to the error.jsp page.
              In error.jsp page we used the isErrorPage method of the page directive to tell the container that this page is for exception handling and then container will give an implicit object “Exception” for handling the exceptions. This can be easily understood with the below example.
generateException.jsp
<%@ page errorPage="error.jsp" %>
<%
  int count=0;
  count=100/count;

%>

error.jsp
<html>
<body>
<%@ page isErrorPage="true" %>
<%="Sorry, Exception occured"%>
</br>
<%="Here is your Exception:- "+exception%>
</body>
</html>


2.  Try/Catch Block exception handling: - This is very much similar to the core java exception handling. We put the code under the try block and catch the exception in exception block.
This can be easily understood with the example below.

generateException.jsp
<%
 try
  {
     int count=0;
     count=100/count;
  }
catch(Exception e)
  {
                out.println("Try/Catch block Exception Handling "+e);
  }

%>

3.       JSTL Exception: - JSTL (Java standard tag library) is used for making coding easy. JSTL gives some standard tags to perform some specific tasks so JSTL also provide tags to perform exception handling. Please refer the below example for JSTL exception handling.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
 <body>
    <c:catch var="ExceptionVar">
    <% int count=0;
     count=100/count; %>
    </c:catch>
    Test :
                <c:if test = "${ExceptionVar != null}">
                out.println("Try/Catch block Exception Handling ");
                ${ExceptionVar}
    </c:if>
    </body>
</html>

Monday 22 July 2013

What is the difference between GET and POST method in java?


Get and Post are both the method of HTML form element and they are used to transfer data with the request when the submit button is pressed as:
 

<form action="firstServlet" method="get">     

         <table>

            <tr> <td>

                 <input type="Text" name="UsrName"/>

            </td> </tr>

            <tr><td>

                 <input type="Text" name="pswd"/>

           </td> </tr>

            <tr><td>

                 <input type="submit" name="submit" value="Submit"/>

           </td></tr>

        </table>

</form>

In the above code we have two text box’s  user name and password and one submit button, When we click on the submit button after putting values in the user name and password boxes the control will transfer to the “firstServlet” servlet with the user name and password entered.

The main differences between GET and POST method are as follow.

 

GET

POST

Get request contents are visible in URL

Post request contents are embedded in the body of HTTP request

Get method can only contain data up to 255k

NO such limit for post method

Get request can be cached

Post request contents are not a part of URL so they cannot be cached

Get requests are usually faster than post requests

They are slower than get because they need some extra time to encapsulate in the body of request

Get is a by default method of HTML form element

Post method need be specified for use

Get request can only contain the text data

Post can contain text as well as binary data