Thursday, August 23, 2012

JSP Quick read

In JSP there are five main tags: 1. Declaration Tag 2. Expression Tag 3. Directive Tag 4. Scriptlet Tag 5. Action Tag Description for each tag with number as mentioned above. 1. <%! %>this allows developer to declare variable or methods which will be outside the service() method of the servlet class. Something like declaring inside the Servlet class as class variable and method. e.g. <%! private int count = 0; private String getAccount(int accountNumber); %> 2. Expression tag is short for out.println() to output the data and show to the user in html format. Don’t end with semicolon(;). This contain only the single statement. e.g. Date : <%= new java.util.Date() %> 3. Directive tags are used to give special instruction to the JSP engine. There are three main different types of directive tag a. page i. language – the language file use e.g. <%@ page language = “java” %> ii. extends - super class of the jsp_servlet e.g. <%@ page extends=”java.lang.Thread” %> iii. import – commonly used to import the classes e.g. <%@page import =”java.util.*” %> iv. buffer – Control the use of the buffer output for the JSP page. Default is 8kb. e.g. <%@ page buffer=”none” %> v. autoFlush – Flush output buffer when full e.g. <%@ page autoFlush=“true“ %> vi. isThreadSafe – set True or false. If true a new thread is started so requests are handled simultaneously. vii. info – to give information about the page typically used to add author,version,copyright and date e.g. viii. errorPage – It should be url to show the page on implict error e.g. ix. isErrorPage – This is set to true to make a JSP page a special error page. This page can access the implicit object of the exception. x. contentType – set the mime type b. include : Allows including the contents of another JSP file inside the present file. It is basically used for navigation, tables, headers and footers that are common to multiple pages. e.g. <%@ include file=”jsp/header.html” %> or from the present folder of file <%@ include file=”footer.html” %> c. Tag library : It is used to add the custom tag that can be used by the page. e.g. for using JSTL core tag syntax is <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 4. With action tag we can use the JavaBeans in the jsp file. e.g. JavaBean Scopes are: page – valid until page completes request – bean instances lasts for the client request session – bean lasts for the client session application – bean instance created and lasts until application ends. 5. Scriptlet tag are the code to write inside the service() method of the Servlet class. Used with the tag Sample program : <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%! public String show(int number){ String text =""; for(int count=0;count<=number;count++){ text = text + " Text"+count+" "; } return text; } %> <%=show(10)%> Output: Text0 Text1 Text2 Text3 Text4 Text5 Text6 Text7 Text8 Text9 Text10 Implicit Object: JSP engine provide several objects which are available in Servlet. i.e. out - out object is the intantiation of javax.servlet.jsp.JspWriter. This is used to show the text on the page. request – each time client request a page the JSP engine creates a new object of javax.servlet.http.HttpServletRequest. response – for each response the jsp engine creates a new object of javax.servlet.http.HttpServletResponse and it is used to send the response to the browser. application - It is same as ServletContext object in the Servlet. session - It is an instance of HttpSession used for the track information about the client. Each client has one global session object. pageContext – this object contain information about the directives used in the page. e.g. It represent the entire JSPPage config – It is an instance of java.servlet.ServletConfig. It has the same methods and interfaces that the ServletConfig object have in the servlet. exception – It is available only when the previous JSP page throws an uncaught exception and the is set for the present page.The exception object is the wrapper containing the exception thrown from the previous page. page - This object is an actual reference to the instance of the page. It is same as this object used in Java class. Managing the request from the page ( Form creation)
e.g. code informationForm.jsp
Name : Enter the course Category : Description: Search engines: yahoo google
informationFormConfirm.jsp Confirmed: Name : Course category : Description : Search Engine : yahoo = google = Some More examples : Knowing the client information : JSP Bean: JavaBeans are reusable components. It represents a simple java class with some properties. The bean properties are accessed by Getter and Setter method. They are used to separate the business and presentation logic. We have four different scope for the JavaBean in JSP 1) Page Scope: It helps to keep the data available while the page is loading. It will disappear as soon as the response sent to the browser 2) Request Scope : It will be available as long as request object is available. If tag is used the request scope javabean will be available in the next page if tag is used then the javabean will be null once the page redirect to new page. 3) Session Scope : This is available till the client open the browser and exit from it. 4) Application Scope: These javabean will be available for all the page and client till application is running. e.g. ================================ useBean.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>

Using Beans and Page Scope

The counter value is ==================================== checkValueBean.jsp ========================================= Change scope as request, session and application and check the output. Observation: You will find as the scope set to session the value on the other page(checkValueBean.jsp) also getting the latest value. When used as application value will be updated on other browser also when used from different web browser session. Once the variable used it will be available on the server and if any page use the same bean object to increment the value it will add up from the value set from other pages. Modularization in JSP: provide the option to add the page in the runtime. When page incounter this tag in the runtime it will call the jsp page compile it and use. This tag will be used for the page which needs to be reloaded with the change without restarting the server. this tag can be used to include the JSP file during the compile time itself. Exception Handling in JSP: An Exception is an event, which occurs during the execution of a program that disrupts the normal flow of the programs instructions. When an error occurs within a method , the method creates an object and hands it off to the runtime system. Traditional form of managing the exception object. Second way : Define the error page in the page directive as During the execution or processing the JSP page if any error occurs then the container automatically calls the errorPage and direct the flow to it. Any page can be used to show the errors but the page directive have to be set for that page as Session Tracking in JSP For tracking the users data and object throughout the application while he moves from one page to another session tracking is used. Session are used to hold the specific users data. JSP provides implicit object session. 1. Cookies : cookies are small text files stored in the client side. Excellent most widely used approach. 2. URL re-writing : 3. Hidden form fields: 4. Using session object in the JSP. Login.jsp
Enter Username : Enter Password :
Container Managed Security:: Web.xml file of the application: application /jsp/* admin BASIC securityapp Testing the Application Security admin JSPWebProject index.html index.htm index.jsp default.html default.htm default.jsp

Wednesday, August 22, 2012

Datastructure Java


List :

ArrayList and LinkedList




  • List is a ordered collection.

  • Can contain duplicate elements

  • You can access element in a list by their integer indexes.

  • ArrayList is the default choice. Offer constant time positional access, quite fast.

  • Consider LinkedList for frequently add elements to the beginning of the List or iterate over the List and delete elements from its interior. These are constant time operation in the LinkedList and linear operation in ArrayList.

  • Positional access is much slower in LinkedList. Linear time for LinkedList and constant time for the ArrayList.







  • Set :

    HashSet and TreeSet



    • A collection that CANNOT contain duplicate elements.

    • Used to represent cards in a poker hand or processes running on a machine

    • HashSet is much faster but no ordering guarantees. This is mostly used.

    • TreeSet is in order iteration . What you entered will be in same sequence while iteration FIFO

    • Default initial capacity is 101. Should set it twice the size that you expect the Set to grow.
      Set s = new HashSet(17); Here intial capacity is set to 17

    • Load factor is the tuning parameter. Default is (.75) when the number of entries exceeds the product of the load factor and the current capacity the capacity is doubled. Higher value decrease the space overhead, but increase the time it takes to look up an entry.


    Map :

    HashMap and TreeMap




    • Map is an Object that maps key to values.

    • Maps CANNOT contain duplicate keys

    • HashMap is not ordered , TreeMap is ordered analogous to List.



    Synchronized Collections



    • HashTable and Vector are fully synchronized Classes in the collections framework are not synchronized by default.

    • Wrapper classes add functionality to the standard Collection (interface) implementation.

    • Factory method defined in the Collections class(not to be confused with the Collection interface).

    public static Collection synchronizedCollection(Collection c);


    public static Set synchronizedSet(Set s);


    public static List synchronizedList(List list);


    public static Map synchronizedMap(Map m);


    public static SortedSet synchronizedSortedSet(SortedSet s);


    public static SortedMap synchronizedSortedMap(SortedMap m);



    • Iterate over synchronized collection , you have to manually synchronise the iteration operation. Failing to use this idiom can result in non-deterministic behavior.

    Collection c = Collections.synchronizedCollection(myCollection);
    Synchronized(c){
    Iterator i = c.iterator(); // it should be inside synchronized block
    While(i.hasNext()){
    System.out.println(i.next());
    }





    Algorithms




    • sort and binarySearch available in Collections class as static method.

      public static int binarySearch(List list, Object key);
      public static int binarySearch(List list, Object key,Comparator c);

      public static void sort(List list);
      public static void sort(List list, Comparator c);
    References : http://java.sun.com/docs/books/performance/1st_edition/html/JPAlgorithms.fm.html
    (Read more on this link. This blog is summary sun java)