MY mENU


Wednesday 21 March 2012

implement a thread-safe JSP page


How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?

            You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive in the JSP.

<%@ page isThreadSafe="false" %>

The generated servlet can handle only one client request at time so that we can make JSP as thread safe. We can overcome data inconsistency problems by this approach. The main limitation is it may affect the performance of the system. 

Various attributes Of Page Directives in Jsp

Page directive contains the following 13 attributes.
  1. language
  2. extends
  3. import
  4. session
  5. isThreadSafe
  6. info
  7. errorPage
  8. isError page
  9. contentType
  10. isELIgnored
  11. buffer
  12. autoFlush
  13. pageEncoding.

Comments In Jsp

The three kinds of comments in JSP and the difference between them
Three types of comments are allowed in JSP

JSP Comment:
<%-- this is jsp comment --%>
This is also known as hidden comment and it is visible only in the JSP and in rest of phases of JSP life cycle it is not visible.
HTML Comment:This is also known as template text comment or output comment. It is visible in all phases of JSP including source code of generated response.
Java Comments.
With in the script lets we can use even java comments .
<%
// single line java comment
/* this is multiline comment */
%>

This type of comments also known as scripting comments and these are visible in the generated servlet also.

Jsp Interview Questions-part3

How to pre-compile JSP?
Add jsp_precompile as a request parameter and send a request to the JSP file. This will make the jsp pre-compile.
http://localhost:8080/jsp1/test.jsp?jsp_precompile=true
It causes excution of JSP life cycle until jspInit() method without executing _jspService() method.

The benefits of pre-compiling a JSP page?
It removes the start-up lag that occurs when a container must translate a JSP page upon receipt of the first request.

How many JSP scripting elements and explain them?
Inside JSP four types of scripting elements are allowed.
1. Scriptlet <% any java code %>     
                    Can be used to place java code.
2. declarative <%! Java declaration %>
                   Can be used to declare class level variables and methods
3. expression: <%= java expression %>
                    To print java expressions in the JSP
4. comment <%-- jsp comment --%>

What is a Scriptlet?
JSP scriptlet can be used to place java code.
Syntax:

<%
Any java code
%>
The java code present in the scriptlet will be placed directly inside _jspService() method .

What is a JSP declarative?
JSP declarations are used to declare class variables and methods (both instance and static) in a JSP page. These declations will be placed directly at class level in the generated servlet and these are available to the entire JSP.
Syntax:

<%! This is my declarative %>

Eg: <%! int j = 10; %>

How can I declare methods within my JSP page?
We can declare methods by using JSP declarative tag.

<%!
public int add(inti,intj){
return i+j;
}
%>

What is the difference b/w variable declared inside a declaration and variable declared in scriplet ?
Variable declared inside declaration part is treated as a instance variable and will be placed directly at class level in the generated servlet.

<%! int k = 10; %>

Variable declared in a scriptlet will be placed inside _jspService() method of generated servlet. It acts as local variable.
<%
int k = 10;
%>
What is a Expression?
JSP Expression can be used to print expression to the JSP.
Syntax:

<%= java expression %>

Eg: <%= new java.util.Date() %>

The expression in expression tag should not ends with semi-colon . The expression value will become argument to the out.pritln() method in the generated servlet.

 What is output comment?
The comment which is visible in the source of the response is called output comment.

JspInit(), JspService(), JspDestroy() methods in Jsp


The jspInit() method:
The jspInit() method of the javax.servlet.jsp.JspPage interface is similar to the init() method of servlets. This method is invoked by the container only once when a JSP page is initialized. It can be overridden by a page author to initialize resources such as database and network connections, and to allow a JSP page to read persistent configuration data. 



 The _jspService() method:
The _jspService() method of the javax.servlet.jsp.HttpJspPage interface is invoked every time a new request comes to a JSP page. This method takes the HttpServletRequest and HttpServletResponse objects as its arguments. A page author cannot override this method, as its implementation is provided by the container.



The jspDestroy() method:
The jspDestroy() method of the javax.servlet.jsp.JspPage interface is invoked by the container when a JSP page is about to be destroyed. This method is similar to the destroy() method of servlets. It can be overridden by a page author to perform any cleanup operation such as closing a database connection.


Difference between _jspService() and other life cycle methods.


JSP contains three life cycle methods namely jspInit( ), _jspService() and jspDestroy().
- In these, jspInit() and jspDestroy() can be overridden and we cannot override _jspService().
- Web container always generate _jspService() method with JSP content. If we are writing _jspService() method , then generated servlet contains two _jspService() methods which will cause compile time error. To show this difference _jspService() method is prefixed with ‘_’ by the JSP container and the other two methods jspInit() and jspDestroy() has no special prefixes. 

What are the lifecycle phases of a JSP?

Life Cycle Phases of Jsp:


Life cycle of JSP contains the following phases: 
  1.  Page translation: -converting from .jsp file to .java file 
  2.  Page compilation: converting .java to .class file 
  3.  Page loading : This class file is loaded. 
  4.  Create an instance :- Instance of servlet is created 
  5.  jspInit() method is called 
  6.  _jspService() is called to handle service calls 
  7.  jspDestroy() is called to destroy it when the servlet is not required.

JSP Interview Questions-part2

 Explain the life-cycle mehtods in JSP?

The 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. 


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.



What JSP lifecycle methods can I override?
We can override jspInit() and jspDestroy() methods but we cannot override _jspService() method.



How can I override the jspInit() and jspDestroy() methods within a JSP page?
By using JSP declation tag



<%! 
        public void jspInit() {
                . . .
        }
%>
<%!     
        public void jspDestroy() {
                . . .   
        }
%>



 Explain about translation and execution of Java Server pages?

A java server page is executed within a Java container. A Java container converts a Java file into a servlet. Conversion happens only once when the application is deployed onto the web server. During the process of compilation Java compiler checks for modifications if any modifications are present it would modify and then execute it.

Why is _jspService() method starting with an '_' while other life cycle methods do not?
_jspService() method will be written by the container hence any methods which are not to be overridden by the end user are typically written starting with an '_'. This is the reason why we don't override _jspService() method in any JSP page.

What are the advantages of JSP over Servlet?


What are the advantages of JSP over Servlet?
  1. Best suitable for view components
  2. we can separate presentation and business logic
  3. The JSP author not required to have strong java knowledge
  4. If we are performing any changes to the JSP, then not required to recompile and reload explicitly
  5. We can reduce development time.

Differences between Servlets and JSP:


Differences between Servlets and JSP:


Servlets


JSP

1. Best suitable for processing logic

1. Best suitable for presentation logic

2. we cannot separate business and presentation logic

2. Separation of presentation and business logic is possible

3. Servlet developer should have strong knowledge in Java

3.JSP author is not required to have strong knowledge in Java

4. For source code changes ,we have to perform explicitly compilation

4. For source code changes ,it is not required to perform explicit compilation

5. Relatively development time is more

5. Relatively development time is less

Jsp Interview Questions

What is JSP ? 

Java Server Pages (JSP) is a server side component for the generation of dynamic information as the response. Best suitable to implement view components (presentation layer components). It is part of SUN’s J2EE platform.



Explain the benefits of JSP?

These are some of the benefits due to the usage of JSP they are:

  •  Portability, reusability and logic components of the language can be used across various platforms. 
  • Memory and exception management. 
  • Has wide range of API which increases the output functionality.
  • Low maintenance and easy deployment. 
  • Robust performance on multiple requests.

Is JSP technology extensible?

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



Can we implement an interface in a JSP?
No 



Explain the differences between ASP and JSP?
The big difference between both of these technologies lies with the design of the software. JSP technology is server and platform independent whereas ASP relies primarily on Microsoft technologies.

Can I stop JSP execution while in the midst of processing a request?
Yes. Preemptive termination of request processing on an error condition is a good way to maximize the throughput of a high-volume JSP engine. The trick (assuming Java is your scripting language) is to use the return statement when we want to terminate further processing.

Explain JSP API ?

The JSP API contains only one package : javax.servlet.jsp

It contains the following 2 interfaces: 

  1. JspPage: This interface defines the two life cycle methods jspInit() and jspDestroy()
  2.  HttpJspPage:This interface defines only one life cyle method _jspService() method.

Every generated servlet for the jsp's should implement either JspPage or HttpJspPage interface either directly or indirectly.

Generate Pyramid For a Given Number in Java

Generate Pyramid For a Given Number in Java
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class GeneratePyramidExample {
      public static void main (String[] args) throws Exception{
            BufferedReader br= new BufferedReader (new InputStreamReader(System.in));
                System.out.println("Enter Number:");
                     int as= Integer.parseInt (br.readLine());
                         System.out.println("Enter X:");
                             int x= Integer.parseInt (br.readLine());
  int y = 0;
    for(int i=0; i<= as ;i++) {
            for(int j=1; j <= i ; j++) {
                  System.out.print(y + "\t");
                      y = y + x;
                   }
           System.out.println("");
         }
    }
}

Output of this example would be

Enter Number:
5
Enter X:
1

0
1 2
3 4 5
6 7 8 9
10 11 12 13 14

----------------------------------------------

Enter Number:
5
Enter X:
2

0
2 4
6 8 10
12 14 16 18
20 22 24 26 28

----------------------------------------------

Enter Number:
5
Enter X:
3

0
3 6
9 12 15
18 21 24 27
30 33 36 39 42

Addition of Two Numbers in C++

Addition of Two Numbers in C++:

#include
#include
void main ()
   {
        int a,b,c;
         clrscr ();
           cout <<" Enter A: ";
              cin >>a;
                cout <<" Enter B: ";
                   cin >>b;
                      c= a+b;
                        cout <<"\n Addition is: "<               getch ();
        }

Fibonacci Series c language

Fibonacci Series c language 

 #include
    main() {
        int n, first = 0, second = 1, next; 
           printf("Enter the number of terms\n");
              scanf("%d",&n);
                printf("First %d terms of Fibonacci series are :-\n",n); 
                   for ( int i = 0 ; i< n ; i++ ) { 
                      if ( i<= 1 ) 
                       next = i; 
                         else { 
                           next = first + second; 
                             first = second; 
                               second = next; 
                                 } 
                         printf("%d\n",next); 
                  } 
          return 0; 
    }

Random Numbers in Java

Write a program to generate 5 Random nos. between 1 to 100, and it. should not follow with decimal point.

class RandomDemo{
      public static void main(String args[]){
          for(int i=1;i<=5;i++){
              System.out.println((int)(Math.random()*100));
          }
    }
}