Java j2ee interview questions by shivprasad koirala pdf


    Sample JAVA_J2EE Interview Questions - Shivprasad Koirala (Questpond - Free ebook download as PDF File .pdf), Text File .txt) or read book Mail [email protected] for any of my titles above,. Sample JAVA/J2EE JAVV Interview Questions. - download JAVA/J2EE: Interview Questions (With Set of 2 CDs) book online at best About the Author: Shivprasad Koirala is an IT professional with the. JAVA Interview Questions. By. Shivprasad Koirala This PDF only has questions which can help you to judge what level do you stand.

    Language:English, Spanish, Portuguese
    Genre:Personal Growth
    Published (Last):30.08.2016
    Distribution:Free* [*Registration Required]
    Uploaded by: BRIANNA

    75955 downloads 151745 Views 25.44MB PDF Size Report

    Java J2ee Interview Questions By Shivprasad Koirala Pdf

    Java j2ee job interview companion ebook. Vijay Ekkaladevi. Pocket java. Kumaran K. 25 best hibernate interview questions and answers. Read the most frequently asked top J2EE Interview Questions and answers for freshers and experienced job interview questions pdf J2EE. Java Interview Questions by Shivprasad Koirala. Web Application Development Using Java, J2ee, HIbernate & Spring MVC. Price:$ Java certification.

    Working pressure min. Retracted piston force, theoretical. Extended piston force, theoretical. Speed max. Cushioning energy. Moving mass, internal. Language pack: No language pack installed. In other. Page 20, Table 6. There is a typo. Target or nontarget. The success rate is low when the MSN radius is shorter than 1. Log Likelihood.

    StringBuffer is a peer class of String that provides almost all functionality of strings. String represents fixed-length, immutable character sequences. Comparatively StringBuffer represents mutable, growable and writeable character sequences. Below is a simple code which shows clearly the efficiency of StringBuffer object. When we loop using String class we are creating 10 objects.

    But with StringBuffer only one object is created. It is very much similar to StringBuffer except for one difference: The advantage of StringBuilder is good performance. In case of multithreading, you must use StringBuffer rather than StringBuilder. The function or the method can not change variable values. In pass By ref the function or subroutine receives a pointer of the variable. And any changes to variable value are also visible outside the function or subroutine.

    Lets try to understand the concept from the below snippet code. Even when we have changed the object reference it still reflects the old object value. In short object references are passed by value. Access modifiers decide whether a method or a data variable can be accessed by another method in another class or subclass.

    Java provides four types of access modifiers: Private - Can be accessed only within the class. Even methods in subclasses in the same package do not have access. Default - Its private access by default accessible to classes in the same package but not by classes in other packages, even if these are subclasses.

    Assertion includes a Boolean expression. If the Boolean expression evaluates to false AssertionError is thrown. Assertion helps a programmer to debug the code effectively. Assertion code is removed when the program is deployed. Below is a code snippet which checks if inventory object is null. Many times in project you need to create exact copy of the object and operate on them.

    To do this there two ways of doing it Shallow clone and Deep clone. When an object is Shallow cloned the parent object or the top level object and its members are duplicated. But any lower level objects are not duplicated.

    Rather references of these objects are copied. So when an object is shallow cloned and you modify any of it child classes it will affect the original copy. When an object is deep cloned the entire object and its aggregated objects are also duplicated. Below is the diagram which explains things in a clear and pictorial manner.

    In the above diagram there are three blocks the first block is the original object, second block is the Shallow clone and the third is Deep clone block.

    Here the object to be cloned is a simple Customer class which has multiple addresses. Now when you shallow clone it you can see the top class clsCustomer is duplicated but clsAddresses still refers to the. But in case of Deep clone complete new copy is created of the whole structure. In order to implement shallow cloning we need to implement cloneable interface and override the clone method with implementation.

    You can look in to the below code snippet. In the above code snippet we have defined a class clsExampleClone which implements the Cloneable interface.

    We have also provided implementation for the clone method. It just returns the parents clone object. Once we have defined this object we created the. All objects implement a clone method Every object is responsible for cloning itself via its clone method. So when the parent is called it makes calls to all the referenced objects inside the class and calls its clone method. Serialization This is the best way to deep cloning and not to mention best answer in interview of how to implement deep cloning.

    There are three steps to do deep cloning using serialization: Below is the code snippet which implements all the above steps.

    In the above code snippet note the three important steps which have been marked for simplicity. Define a complex object and try to create a deep cloned object from the function. That means only one instance of the object need to be running. It makes sense that no object of the class need to be created.

    Below are some important points to be noted for final modifiers: They play the same role as constant variables. But you can change the object data.

    Static initializer block is a method with no name sounds funny hmm , no arguments, and no return type. It doesn't need a name, because there is no need to refer to it from outside the class definition. The code in a static initializer block is executed by the JVM when the class is loaded.

    You can use the static initializer block to initialize static variables or do some class level initialization. Static initializer block runs only once irrespective of how many instances you create of the object. Above is the code snippet which shows how static initializers work.

    The first thing which will execute is the static initializer block and then the void main method. One of the important point to keep in mind is it runs before the constructor. Feel free to test it using constructor. You can have more than one static initializer block in your class definition, and they can be separated by other code such as method definitions and constructors.

    The static initializer blocks will be executed in the order in which they appear in the source code. Changing the type of the value from one type to other is termed as casting. For instance look at the below code snippet in which we are trying to cast integer value to double data type. To explicitly cast an expression prefix the expression with type name as shown in the code snippet below.

    For instance in the below code snippet my inventory object is type casted and stored as type Object. When you try to move a big value data type to a small data type variable it leads to narrowing conversion. Below is the code snippet which explains in detail of how the conversion happens. In the below code we are trying to move double to an integer data type. Because integer data type is smaller than double data type it looses its decimal portion.

    Widening conversion is exactly vice versa of the same in which try to move small data type value to big one. In this case no conversion happens and neither have we loosed.

    Below is the conversion tree which says when Widening conversion will happen and when narrowing conversion will be done. So if we try to move up the tree that means if we try move char to int, int to long, float to double widening conversion will happen. If we try to move down the tree like int to char, double to int narrowing conversion will happen and probably also data loss.

    We need to specify explicit casting only if narrowing conversion is taking place. Doing that we say to the compiler that we are aware of the data loss which can happen. Let us first try to understand the question in a more precise manner. Glance the below class diagram which depicts a typical hierarchical relation ship between two wheelers. So can we move an object of Cycle to object of two wheeler?. Answer is yes we can do it by type casting the parent to child type. Again the law of conversion hierarchy applies here.

    In the below figure you can see the two arrows one which points from top to down and the other vice-versa. So if you are moving from down the hierarchy to the top you do not need to do explicit casting. That means if you move cycle object to two wheeler compiler will not throw error. But if you try to move two wheeler to cycle it will throw an error if you have not defined explicit casting of the object type. Below is the sample pseudo code which shows how things work.

    Basically there are four important keywords which form the main pillars of exception handling: Code which you want to monitor for exception is contained in the try block. If any exception occurs in the try block its sent to the catch block which can handle this error in a more rational manner. To throw an exception manually you need to call use the throw keyword. If you want to put any clean up code use the finally block. The finally block is executed irrespective if there is an error or not.

    Below is a small error code snippet which describes how the flow of error goes. Arithmetic exception will flow from try block to the arithmetic catch block and then execute the finally block. But the general exception will flow from the try block, then to the exception. In short the finally block always execute. All exception types are subclasses of Throwable.

    Throwable is at the top of the exception class hierarchy. Immediately below Throwable are two subclasses that partition exceptions into two distinct branches. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch.

    This is also the class that you will subclass to create your own custom exception types. There is an important subclass of Exception, called RuntimeException. Exceptions of this type are automatically defined for the programs that you write and include things such as division by zero and invalid array indexing.

    Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Stack overflow is an example of such an error. Exceptions generated from runtime are called unchecked exceptions, since it is not possible for the compiler to determine that your code will handle the exception.

    Exception classes that descend from RuntimeException and Error classes are unchecked exceptions. Examples for RuntimeException are illegal cast operation, inappropriate use of a null pointer, referencing an out of bounds array element. Error exception classes signal critical problems that typically cannot be handled by your application. Examples are out of memory error, stack overflow, failure of the Java VM. Thrown exceptions are referred to as checked exceptions. The compiler will confirm at compile time that the method includes code that might throw an exception.

    Moreover the compiler requires the code that calls such a method to include this call within a try block, and provide an appropriate catch block to catch the exception.

    Below are some unchecked exceptions: Below are some checked exceptions: Just define a subclass of Exception and then you can override methods to provide custom functions. The chained exception feature allows you to associate another exception with an exception. This second exception describes the cause of the first exception. Consider a situation in which you are getting null exception because of permission issues.

    You would like to know if this exception is associated with some other exception. For chained exceptions there are two constructors and two methods. The constructors are shown here: That is, causeExc is the underlying reason that an exception occurred. The second form allows you to specify a description at the same time that you specify a cause exception.

    Above is the code snippet which shows chained exception in action. We have defined a method by name demo. In demo we have thrown a null pointer error. But after that we set the main cause of error using initcause as arthimetic exception. You can also see the display. You can get the main cause of error using getCause method. Serialization is a process by which an object instance is converted in to stream of bytes. There are many useful stuff you can do when the object instance is converted in to stream of bytes for instance you can save the object in hard disk or send it across the network.

    In order to implement serialization we need to use two classes from java. Using writeobject we can write and readObject can be used to read the object from the stream. Below are two code snippet which used the FileInputStream and FileOutputstream to read and write from harddisk. When performance becomes a important criteria, then you can serialize using the java. Externalizable interface instead of the Serializable interface. Externalizable requires that you write the details of reading and writing the object's state to the byte stream.

    The ObjectOutputStream class no longer simplifies this process. You must use the methods readExternal and writeExternal method to write the object in to stream and read from stream. Below is the syntax for the same javadoc [ options ] [ packagenames ] [ sourcefiles ] [ files ] Arguments can be in any order.

    Options Command-line options that is doctitle, windowtitle, header, bottom etc. You must separately specify each package you want to document.

    Javadoc uses -sourcepath to look for these package names. Javadoc does not recursively traverse subpackages. The path that precedes the source file name determines where javadoc will look for it. Javadoc does not use -sourcepath to look for these source file names. Doclets helps us to specify the content and format for Javadoc tool. By default Javadoc uses the standard doclet provided by sun.

    But you can supply your own customized output for Javadoc. This is a newly added feature in J2SE 5. Auto boxing is the process in which primitive type is automatically boxed in to equivalent type wrapper.

    There is no need to explicitly do casting for the same. Auto boxing is vice versa of the same. Value of the boxed object is converted in to primitive data type. You can see in the below code snippet we have two samples of Auto boxing and Unboxing.

    So programmer may be tempted to use this feature extensively. For instance the below code would be more efficient if primitive data type was used. Believe me I never liked that code. A maintainable inheritance depth should be maximum 5. Anything above that is horrible. But depending on environments you will get stack over flow error.

    To understand the concept we have three variations defined above. You will understand why we are talking about synchronized methods when the fundamental is about volatile. Before we start dealing with the above fundamentals lets try to understand the concept of main memory in java. Main memory is a memory which at any moment of time holds the correct value of variable. So when variables are updated its possible that value in main memory can be different from the value of the actual variables.

    Ok now that we know about the main memory fundamentals lets go ahead with the above three cases and then try to understand the concept of volatile variables. For the first case i. For the second case because the variable is defined as volatile it is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory.

    Effectively, a variable declared volatile must have its data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value.

    Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency. Volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot.

    Clearly synchronized is likely to have more overhead than volatile. A thread is a path of execution that run on CPU, a process is a collection of threads that share the same virtual memory. A process has at least one thread of execution, and a thread always run in a process context.

    A process is a collection of virtual memory space, code, data, and system resources. A thread is code that is to be serially executed within a process. A processor executes threads, not processes. One more significant difference between process and thread is every process has its own data memory location but all related threads can share same data memory and have their own individual stacks. Thread is a light weighted process, collection of threads become process. Thread safe is used to describe a method that can run safely in multithreaded environments allowing accessing to data in a safe and efficient way.

    Thread safety is achieved by synchronization. Synchronization assures that the object data is not accessed by multiple threads at the same time. Semaphore is an object which helps two threads to communicate with one another in order to synchronize there operation.

    Monitor is a body of code which can be executed by only one thread at a time. If any other thread tries to get access at the same time, it will be suspended until the current thread releases the Monitor. Synchronized blocks implement the concept of monitors described in the first answer. Below is the code snippet of the synchronized block. In the above code we have two methods Safe and Unsafe.

    You can see how the Safe method is using the Synchronized keyword thus ensuring that multiple threads do not execute this method. Thread class. Create a class which extends the thread class. When the class is instantiated, the thread and object are created together and the object is automatically bound to the thread.

    By calling the object's start method, the thread is started and immediately calls the object's run method. Runnable interface Create the thread and supply it an object with a run method. This object will be permanently associated with the thread. The object's run method will be invoked when the thread is started. This method of thread creation is useful if you want many threads sharing an object.

    Below is a sample code which inherits from thread class. Then creates object of the class and calls start. Next is the code snippet which creates thread using the runnable interface. You can see the class is implements the runnable interface.

    And later this class is tied up with thread object. Below are some of the main differences between threads using runnable interface and by extending the thread class. If our class is already extending another class we can't extend Thread class because java doesn't support multiple inheritance so we have left only one choice that is implementing Runnable interface.

    Below is the code snippet: By using wait and notify , a thread can give up its hold on a lock at an arbitrary point, and then wait for another thread to give it back before continuing.

    By executing wait from a synchronized block, a thread gives up its hold on the lock and goes to sleep. Later, when the necessary event happens, the thread that is running it calls notify from a block synchronized on the same object. Now the first thread wakes up and begins trying to acquire the lock again. Every thread has priority.

    If, at any time, a thread of a higher priority than the current thread becomes runnable, it preempts the lower priority thread and begins executing. By default, threads at the same priority are scheduled round robin, which means once a thread starts to run In order to set thread priority below is the code snippet: It causes the currently executing thread object to temporarily pause and allow other threads to execute.

    Daemon threads are designed run in background. One example of a daemon thread is the garbage collector thread. You can use setDaemon to mark a thread as daemon. Lets try to understand how servlets work in multi-threaded environments. In most circumstances only a single servlet instance will exist in the servlet container. That means for every request a new object will not be created.

    But all the method call like the service ,doget ,dopost etc are executed inside their own thread. So any local variables declared inside these methods will not be shared across requests. That means all the local variables are thread safe. But any variable declaration for example instance variables will be shared across request. You can see in the below code HitCount variable will be shared across request which means its not thread safe. So at any moment of time two threads will not be executing the same servlet instance which gurantees thread safety.

    JDBC Note: JDBC allows a developer to write applications that is database independent. JDBC allows you to write Java code, and leave the platform database specific code to the driver. There are four major components in JDBC. Driver manager section creates the connection object.

    Connection object create the statement object with the required SQL which is then executed against the database. And finally database gives the result back in the resultset. You can also find the setup installation in the CD supplied. Above is the code snippet which makes the select. Basically there are four steps to connect to database using JDBC Same is highlighted in the above figure: In order to created the connection object we need to give the URL where the database is located with proper credentials.

    Statement object will be used to fire the sql. I How do you handle SQL exceptions? So if you want to catch any database related error below is the code snippet to go about it: The error description varies from driver to driver depending how vendor has implemented it.

    It can be obtained from the SQLException by calling the "sqlex. SQL State is a five character string which has two parts. The first two characters define the class of the state and the three characters later define subclass of the error code. Below figure can show you the difference. Above shows a small table section for the error code i. Actually the error code table is huge do look in to documentation for more depth.

    The only point we wanted to highlight is the way the SQL State code structure is. For instance in the above the SQL State code represents a warning of disconnect error. When do we really want to use SQL State?. There are situations where you will like your program to recover or to do more customize handling.

    For instance in the above scenario we get a disconnect error and we would like our program to connect to some other server.

    In short SQL State can be useful when we want our program to act depending on the severity of the error. Vendor Error code This returns us vendor specific error code which can be useful in case the driver itself has some errors. Using the above three information you can really show some in depth information to the end user. Below is the code snippet for the same.

    This driver communicates directly with the database server. It requires the driver binary code to be present on the JAVA client application. Second section is the middle ware or so called the application server which passes the request to database.

    Middle ware section can be type 1, type 2 JDBC driver or a native code. Type 4 drivers are completely written in JAVA. Using Type4 we can move towards platform independence and avoid any kind of deployment issues. But because this kind of driver is very specific to particular database vendor it can be available only by the RDBMS or DBMS vendor as they have more depth about the protocol.

    The one big issue is if you are changing the database you need to also change the driver which means you need to change the connection string to load the driver.

    But the connection string change is a small issue if you design your application architecture carefully you can really make it configurable. Some times really ODBC driver is the only way to access some databases. Meta-data is data about data. For instance meta-data for a database are schemas, catalogs, tables and columns.

    I have made inline comment so that we can understand it line by line. If you note in previous questions we used "DriverManager. Just for hint purpose below is the code snippet. It contains types and properties of the column in the result set. Below is code snippet which displays column name, type and whether the column allows nulls or not. I have also provided inline comments so that every line of code in the snippet can be understood.

    Below are the major points of difference: As "RowSet" is a disconnected from database it needs to maintain Meta data for columns. It is scrollable and can also be serialized. Get the "CachedRowSet" object manipulate all your data and send the whole bunch of manipulated data in on go to the Database. It maintains a connection to the database while the client has reference to it.

    But the added feature is it can produce XML presentation of the data cached. If you are thinking of exposing your data through web services or to provide data to thin client which are written in different language other than JAVA. The above diagram shows the complete relationship between all the interface and classes. That means it contains the rows that satisfy the conditions of the query.

    There are three basic types of resultsets: Forward-only results set These types of resultset are non-scrollable and moves only forward. Scroll-insensitive set Resultset is scrollable so the cursor can move forward, backward, to a particular row etc.

    While the resultset is open it does not show any changes done to the underlying database. Scroll-sensitive set Resultset is scrollable so the cursor can move forward, backward, to a particular row etc. Resultset is sensitive to changes when it is open or used. In the previous questions we had executed SQL using "Statement" object. Below is a simple SQL which will be executed from the code.

    But if you notice nothing has changed considerably other than the values i. Sometimes in complicated SQL statement with huge joins you can see the parsing, syntax checking and code generation is more than executing the actual SQL statement. So if we can some how tell the database that this SQL is going to get executed multiple times but the only change is the data it can really speed up the SQL turn around time.

    That can be done by using "PreparedStatement" interface. Following are the four basic steps: Step1 is our usual statement which we have discussed many times in our previous questions.

    It prepares the SQL statement with the stored procedure name. Keep a note until we are adding the data i. In Step5 all the data inputs are finally sent to the database. Transaction can be defined as a one event or a series of event that must all complete successfully. If one or more event fails then the whole event should be rolled back. If any of the events above fail everything should be rolled back. A transaction is proper if it fulfils ACID properties.

    These four properties are as below: Any invalid data should roll back the whole transaction. If the transaction executes successfully then it should take database from one state which is consistent to other state which is also consistent. Isolation ensures that transactions do not affect each other. So that if there is a problem at any point we can restore back to the original state. There are situations in which multiple users need to interact with database at the same.

    There can be situations where two users access the same resource. For instance in a customer table two users at the same time are trying to update the customer information. This can lead to quiet confusion. This situation is called concurrency problems. Concurrency problems can be solved by proper locking. Exclusive Locks A transaction places an exclusive lock on data when it is modifying the data.

    This lock prevents other transactions from reading or updating the locked data. The data remains locked until the transaction is committed or rolled back. Shared Locks Shared locks permit other transactions to read the locked data but prevent these transactions from modifying the data. The isolation level of transactions involved in the locking process determines the duration of the lock.

    Read Locks A read lock is a lock placed on a resource that is being read or accessed by a transaction. Read lock prevents other transaction to read or update the data which is locked by a read lock. Update Locks Update lock prevents any other transaction to update data. When a transaction tried to update data update lock converts to an exclusive lock. There are three types of locking level for a resource: For instance if you execute a query against a single row it will place row level lock.

    But in case you are selecting more than one row database will go for table level lock or page lock. Page is the memory which holds part of the table or the whole table.

    But again it depends this escalation depends on what type of database you are using. Migration from one level of locking to other is called as Lock escalation. Lost Updates Lost updates occur if you let two transactions modify the same data at the same time, and the transaction that completes first is lost. This isolation level disregards any type of locks, so two simultaneous data modifications are not aware of each other.

    Lets say that these two transactions are now been entered from two different counters of the company. Now both the counter user starts making entry at the same time Actually speaking at But as said in lost updates the first transaction is not considered and the second transaction overrides it. I hope the company does not loose the customer. Non-Repeatable Read Non-repeatable reads occur if a transaction is able to read the same row multiple times and gets a different value each time.

    Because you let two transactions modify data at the same time, you can get some unexpected results. For instance, a customer wants to book flight, so the travel agent checks for the flights availability. Travel agent finds a seat. While the travel agent is booking the seat, some other travel agent books the seat.

    In short the travel agent gets different status at different times for the seat. Dirty Reads Dirty reads are a special case of non-repeatable read. This happens if you run a report while transactions are modifying the data that you're reporting on. For example there is a customer invoice report which runs on 1: Actually customer has no money pending but is still issued an invoice. Phantom Reads Phantom reads occur due to a transaction being able to read a row on the first read, but not being able to modify the same row due to another transaction deleting rows from the same table.

    Lets say you edit a record in the mean time somebody comes and deletes the record , you then go for updating the record which does not exist In other words, no one can acquire any type of locks on the affected row while it is being modified. Transaction Isolation level decides how is one process isolated from other process. Using transaction levels you can implement locking.

    There are four transaction levels: Other transactions can insert and modify data in the same table, however, as long as it is not locked by the first transaction. This is the least restrictive isolation level resulting in the best concurrency but the least data integrity.

    However, even though the locks are held on read data, new rows can still be inserted in the table, and will subsequently be read by the transaction. This setting does not allow the insertion of new rows in the range that is locked; therefore, no phantoms are allowed.

    In pessimistic locking transaction locks the record as soon as it selects the row to update. While in optimistic locking it is only locked when the actual updating takes place. Step1 select the record which needs to be updated, Step2 perform the necessary operation on the record and Step3 update the record. In pessimistic locking we lock the record right from Step1 to Step3 that means as soon as you select the record lock it and keep it lock until you complete the operation.

    No other transaction can access the same until you release the lock. While in optimistic locking you do not lock the record for the complete cycle but only when you are actually updating the record.

    java j2ee interview questions by shivprasad koirala pdf free download

    You can see from the figure above pessimistic locking have longer locking life time than optimistic so it has least amount of concurrency. So in order a row is locked as soon as it is selected you can use the select query something as shown below. In order to implement optimistic locking we do something like this in the SQL update. So when we actually want to update, we just make a check before the update are the old values same or has some thing changed.

    This can be done by putting a comparison on the where clause of the update query. For instance in the above SQL update column1 had value 4 and column4 had value "ss" so we make a compare before update to ensure that nothing has changed.

    If anything has changed the update will not happen thus ensuring safe concurrency. Deadlocks occur when two transactions are each blocked waiting for the other transaction to complete. In order to get a clear understanding of how dead lock occurs lets look at the sequence of events in the below table. Later when actually transaction A goes to update the values it finds himself in a blocking situation as Transaction B is trying to do the same.

    And on the other end Transaction B also goes in to blocking stage as Transaction A is trying to update the customer name. This situation is termed as dead lock. So what happens in such kind of dead locks….. If you planned your database locking well this will not be situation it will roll back one of the transactions and make road for other thus let you come out from the chicken and egg situation. You need to pass the appropriate transaction level constant to the method.

    This is the default behavior for JDBC drivers. But definitely you want to control the commit and roll back of the transaction. For that you need make the connection object's auto commit property as false. Below table has list of common transaction related method and properties in the connection object. JDBC 3. Using save points you can mark one or more places in transaction and some time later you can perform rollback to one of those "Savepoint".

    Below code snippet will give a clear idea of how save points can be used. In the above code snippet we have defined two save points Step1 and Step2.

    Download Shivprasad Koirala Questpond Sample JAVAJ2EE Interview Quest pdf

    After that we can rollback to a particular save point using rollback. For instance step3 and step4 show how we can rollback to a particular save point. You can also rollback every thing using our traditional commit and rollback as shown in step5 and step6. Servlets are small program which execute on the web server. They run under web server environment exploiting the functionalities of the web server.

    In CGI for every request there is a new process started which is quiet an overhead. In servlets JVM stays running and handles each request using a light weight thread. In CGI if there are request then CGI program is loaded in memory while in servlets there are thread and only one copy of the servlet class. There are three methods which are very important in servlet life cycle i.

    Server invokes "init " method when servlet is first loaded in to the web server memory. Once initialized servlet remains in memory to process subsequent request.

    So for every HTTP request "service " method of the servlet is called.

    Finally when server unloads the "servlet " from the memory it calls the "destroy" method which can be used to clean up any resource the servlet is consuming. They form the core of Servlet API. Servlets are not part of core Java but are standard extensions provided by Tomcat. Servlet Interface This interface has the init , service , and destroy methods that are called by the server during the life cycle of a servlet. Following are the method in Servlet interface: ServletConfig getServletConfig: String getServletInfo: ServletConfig Interface This interface is implemented by the servlet container.

    Servlet can access any configuration data when its loaded. The methods declared by this interface are summarized here: Following are the methods in ServletConfig interface: String getInitParameter String param: Enumeration getInitParameterNames: ServletContext Interface It gives information about the environment. It represents a Servlet's view of the Web Application. Using this interface servlet can access raw input streams to Web Application resources, virtual directory translation, a common mechanism for logging information, and an application scope for binding objects.

    String getMimeType String file: String getRealPath String vpath: String getServerInfo: It gives data regarding client request. String getCharacterEncoding: If no size is there then it returns A null value is returned if the type cannot be determined. ServletInputStream getInputStream: String getParameter String pname: Enumeration getParameterNames: String[ ] getParameterValues String name: String getProtocol: BufferedReader getReader: String getRemoteAddr: String getRemoteHost: String getScheme: String getServerName: ServletResponse Interface The ServletResponse interface is implemented by the servlet containerUsed to give response back to the client.

    ServletOutputStream getOutputStream: PrintWriter getWriter: GenericServlet Class The GenericServlet class provides implementations of the basic life cycle methods for a servlet. GenericServlet implements the Servlet and ServletConfig interfaces. It is implemented by the servlet container and provides an input stream that a servlet developer can use to read the data from a client request.

    It defines the default constructor. In addition, a method is provided to read bytes from the stream. The method returns the actual number of bytes read or —1 if an end-of-stream condition is encountered. It is implemented by the servlet container and provides an output stream that a servlet developer can use to write data to a client response. A default constructor is defined. Servlet Exception Classes javax. The first is ServletException, which indicates that a servlet problem has occurred.

    The second is unavailableException, which extends ServletException. It indicates that a servlet is unavailable.

    Most of the java application developers extend HttpServlet class as it provides more HTTP protocol-specific functionalities. For instance we can inherit from GenericServlet class to make something like MobileServlet. So GenericServlet class should be used when we want to write protocol specific implementation which is not available. But when we know we are making an internet application where HTTP is the major protocol its better to use HttpServlet.

    The javax. Cookie[ ] getCookies: String getHeader String field: Enumeration getHeaderNames: String getMethod: String getPathTranslated: String getQueryString: String getRemoteUser: String getRequestedSessionId: String getRequestURI: String getServletPath: HttpSession getSession: If a session does not exist, one is created and then returned. HttpSession getSession boolean new: Otherwise, returns the existing session for this request.

    This section is explained in more detail in further questions. It enables a servlet to formulate an HTTP response to a client. Several constants are defined. These correspond to the different status codes that can be assigned to an HTTP response.

    Below are the methods and functions for the interface void addCookie Cookie cookie: If so, returns the modified version of URL. Otherwise, returns URL. All URLs generated by a servlet should be processed by this method. All URLs passed to sendRedirect should be processed by this method. HttpSession Interface HTTP protocol is a stateless protocol and this interface enables to maintain sessions between requests.

    Object getAttribute String attr: Returns null if attr is not found. Enumeration getAttributeNames: String getId: The methods that are invoked when an object is bound or unbound are void valueBound HttpSessionBindingEvent e void valueUnbound HttpSessionBindingEvent e Here, e is the event object that describes the binding. Cookie Class The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state information. Cookies are valuable for tracking user activities.

    For example, assume that a user visits an online store. A cookie can save the user's name, address, and other information. The user does not need to enter this data each time he or she visits the store. A servlet can write a cookie to a user's machine via the addCookie method of the HttpServletResponse interface.

    The data for that cookie is then included in the header of the HTTP response that is sent to the browser. » shivprasad koirala interview questions pdf free download

    The names and values of cookies are stored on the user's machine. The expiration date determines when this cookie is deleted from the user's machine. If an expiration date is not explicitly assigned to a cookie, it is deleted when the current browser session ends. Otherwise, the cookie is saved in a file on the user's machine. If the user enters a URL whose domain and path match these values, the cookie is then supplied to the Web server.

    Http: www site. If you are looking for Architecture Career email saying Career. What is database or databas This file you can free download and Judge for download the english.

    Net questions interview so reinforced torrent questions free. Answers is book by online dumps notes questions size: shivprasad Swati Agarwal Interview Questions.

    Swati Agarwal Interview Questions. How do you sign out from forms authentication. By Swati Agarwal in. NET 4. Shivprasad i Jul 26, Software testing interview questions Shivprasad Koirala, Sham Sheikh. Good java j2ee interview questions pdf 4shared. Com 2 MB Added: Interview sharepoint, questions shivprasad answers questions www.

    Org-Download free pdf files, ebooks and documents-interview question.

    Related articles:

    Copyright © 2019