Download AJT Question Bank With Solution : Click here
Q-1: Give significance of MVC architecture in building n-tier application. Explain in detail.
Ans: N-tier architecture usually has each layer separated by the network. I.E. the presentation layer is on some web servers, then that talks to backend app servers over the network for business logic, then that talks to a database server, again over the network, and maybe the app server also calls out to some remote services (say Authorize.net for payment processing).
MVC is a programming design pattern where different portions of code are responsible for representing the Model, View, and controller in some application. These two things are related because, for instance the Model layer may have an internal implementation that calls a database for storing and retrieving data. The controller may reside on the webserver, and remotely call appservers to retrieve data. MVC abstracts away the details of how the architecture of an app is implemented.
N-tier just refers to the physical structure of an implementation. These two are sometimes confused because an MVC design is often implemented using an N-tier architecture.
Q-2: Explain various types of JDBC drivers and comment on selection of driver.
JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server.
For example, using JDBC drivers enable you to open database connections and to interact with it by sending SQL or database commands then receiving results with Java.
The Java.sql package that ships with JDK contains various classes with their behaviours defined and their actual implementaions are done in third-party drivers. Third party vendors implements the java.sql.Driver interface in their database driver.
JDBC Drivers Types:
JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates. Sun has divided the implementation types into four categories, Types 1, 2, 3, and 4, which is explained below:
Type 1: JDBC-ODBC Bridge Driver:
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine. Using ODBC requires configuring on your system a Data Source Name (DSN) that represents the target database.
When Java first came out, this was a useful driver because most databases only supported ODBC access but now this type of driver is recommended only for experimental use or when no other alternative is available.
The JDBC-ODBC bridge that comes with JDK 1.2 is a good example of this kind of driver.
Type 2: JDBC-Native API:
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique to the database. These drivers typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client machine.
If we change the Database we have to change the native API as it is specific to a database and they are mostly obsolete now but you may realize some speed increase with a Type 2 driver, because it eliminates ODBC's overhead.
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
Type 3: JDBC-Net pure Java:
In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use standard network sockets to communicate with an middleware application server. The socket information is then translated by the middleware application server into the call format required by the DBMS, and forwarded to the database server.
This kind of driver is extremely flexible, since it requires no code installed on the client and a single driver can actually provide access to multiple databases.
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the client application. As a result, you need some knowledge of the application server's configuration in order to effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database, understanding the nuances will prove helpful.
Type 4: 100% pure Java:
In a Type 4 driver, a pure Java-based driver that communicates directly with vendor's database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself.
This kind of driver is extremely flexible, you don't need to install special software on the client or server.
Further, these drivers can be downloaded dynamically.
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols, database vendors usually supply type 4 drivers.
Which Driver should be used?
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4. If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver. Type 2 drivers are useful in situations where a type 3 or type 4 driver is not available yet for your database. The type 1 driver is not considered a deployment-level driver and is typically used for development and testing purposes only.
Q-3: Explain architecture of J2EE. List out java technologies supported by J2EE along with their applications.
The JavaTM 2 SDK, Enterprise Edition (J2EE SDK) is the reference implementation provided by Sun Microsystems, Inc.
J2EE Server
- Naming and Directory - allows programs to locate services and components through the Java Naming and Directory InterfaceTM (JNDI) API
- Authentication - enforces security by requiring users to log in
- HTTP - enables Web browsers to access servlets and JavaServer PagesTM (JSP) files
- EJB - allows clients to invoke methods on enterprise beans
Enterprise bean instances run within anEJB container. The container is a runtime environment that controls the enterprise beans and provides them with important system-level services. Since you don't have to develop these services yourself, you are free to concentrate on the business methods in the enterprise beans. The container provides the following services to enterprise beans:
Transaction Management
When a client invokes a method in an enterprise bean, the container intervenes in order to manage the transaction. Because the container manages the transaction, you do not have to code transaction boundaries in the enterprise bean. The code required to control distributed transactions can be quite complex. Instead of writing and debugging complex code, you simply declare the enterprise bean's transactional properties in the deployment descriptor file. The container reads the file and handles the enterprise bean's transactions for you.
Security
The container permits only authorized clients to invoke an enterprise bean's methods. Each client belongs to a particular role, and each role is permitted to invoke certain methods. You declare the roles and the methods they may invoke in the enterprise bean's deployment descriptor. Because of this declarative approach, you don't need to code routines that enforce security.
Remote Client Connectivity
The container manages the low-level communications between clients and enterprise beans. After an enterprise bean has been created, a client invokes methods on it as if it were in the same virtual machine.
Life Cycle Management
An enterprise bean passes through several states during its lifetime. The container creates the enterprise bean, moves it between a pool of available instances and the active state, and finally, removes it. Although the client calls methods to create and remove an an enterprise bean, the container performs these tasks behind the scenes.
Database Connection Pooling
A database connection is a costly resource. Obtaining a database connection is time-consuming and the number of connnections may be limited. To alleviate these problems, the container manages a pool of database connections. An enterprise bean can quickly obtain a connection from the pool. After the bean releases the connection, it may be re-used by another bean.
Web Container
The Web container is a runtime environment for JSP files and and servlets. Although these Web components are an important part of a J2EE application, this manual focuses on enterprise beans. For more information on developing Web components, see the home pages for the JavaServer PagesTM and Java Servlet technologies.
Java EE 7 Technologies
Learn more about the technologies that comprise the Java EE 7 platform using the specifications, and then apply them with the Java EE 7 SDK.
Specification downloads are the final releases. Please check the individual JSR pages for download updates such as maintenance releases.
Specification downloads are the final releases. Please check the individual JSR pages for download updates such as maintenance releases.
The J2EE platform provides access to a host of enterprise services using well-defined and standard Java Enterprise APIs that are listed below.
• Enterprise JavaBeans (EJB)
• extensible Markup Language (XML)
• Servlets
• Java Server Pages (JSP)
• Java Messaging Service (JMS)
• Java Database Connectivity (JDBC)
• JavaMail
• JavaIDL
• Java Naming and Directory Interface (JNDI)
• Java RMI/IIOP
· Java Transaction Services (JTS) and Java Transaction API (JTA)
Q-4: Use of callable statements & prepared with example
Following is the example which makes use of CallableStatement along with the following getEmpName()MySQL stored procedure:
Make sure you have created this stored procedure in your EMP Database. You can use MySQL Query Browser to get it done.
DELIMITER $$
DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$
CREATE PROCEDURE `EMP`.`getEmpName`
(IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END $$
DELIMITER ;
This sample code has been written based on the environment and database setup done in previous chapters.
Copy and past following example in JDBCExample.java, compile and run as follows:
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
CallableStatement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
String sql = "{call getEmpName (?, ?)}";
stmt = conn.prepareCall(sql);
//Bind IN parameter first, then bind OUT parameter
int empID = 102;
stmt.setInt(1, empID); // This would set ID as 102
// Because second parameter is OUT so register it
stmt.registerOutParameter(2, java.sql.Types.VARCHAR);
//Use execute method to run stored procedure.
System.out.println("Executing stored procedure..." );
stmt.execute();
//Retrieve employee name with getXXX method
String empName = stmt.getString(2);
System.out.println("Emp Name with ID:" +
empID + " is " + empName);
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
Now let us compile above example as follows:
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces following result:
C:\>java JDBCExample
Connecting to database...
Creating statement...
Executing stored procedure...
Emp Name with ID:102 is Zaid
Goodbye!
C:\>
Prepared statements:
Overview of Prepared Statements
Sometimes it is more convenient to use a PreparedStatement
object for sending SQL statements to the database. This special type of statement is derived from the more general class, Statement
, that you already know.If you want to execute a
Statement
object many times, it usually reduces execution time to use a PreparedStatement
object instead.The main feature of a
PreparedStatement
object is that, unlike a Statement
object, it is given a SQL statement when it is created. The advantage to this is that in most cases, this SQL statement is sent to the DBMS right away, where it is compiled. As a result, the PreparedStatement
object contains not just a SQL statement, but a SQL statement that has been precompiled. This means that when the PreparedStatement
is executed, the DBMS can just run the PreparedStatement
SQL statement without having to compile it first.Although
PreparedStatement
objects can be used for SQL statements with no parameters, you probably use them most often for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it. Examples of this are in the following sections.Q-5: How do RMI clients contact remote RMI servers? Explain with detailed architecture of RMI.
The RMI application comprises of the two separate programs, a server and a client. A typical server program creates some remote objects, makes references to these objects accessible, and waits for clients to invoke methods on these objects. The RMI application provides the mechanism by which the server and the client communicate and pass information back and forth. The RMI distributed application uses the RMI Registry to obtain a reference to a remote object. The server calls the registry to associate a name with a remote object. The client looks up the remote object by its name in the server’s registry and then invokes a method on it.
Program-description:
In this section, you will learn how to send massage from RmiClient to the RmiServer. Here, we are going to create "ReceiveMessageInterface" interface. The interface defines the methods that can be invoked from the client. Essentially, the interface defines the client's view of the remote object. After that, we will create a class named "RMIServer". The RMI Server accepts tasks from clients, runs the tasks, and returns any result. The server code consists of an interface and a class.
In this section, you will learn how to send massage from RmiClient to the RmiServer. Here, we are going to create "ReceiveMessageInterface" interface. The interface defines the methods that can be invoked from the client. Essentially, the interface defines the client's view of the remote object. After that, we will create a class named "RMIServer". The RMI Server accepts tasks from clients, runs the tasks, and returns any result. The server code consists of an interface and a class.
In this class, the receiveMessage()method, which is called from the remote client, is defined. This class is the implementation of the RMI interface. The RmiServer creates the registry. This is a kind of directory. Its key is a name (which is the ID of a remote object) and its content is an object. This object is looked up from a remote program by the name. This registry is accessed from a remote object by the IP address or host name and the port number.
createRegistry(): This is the method creates and exports a registry on the local host that accepts requests on the specified port.
createRegistry(): This is the method creates and exports a registry on the local host that accepts requests on the specified port.
RMI Architecture:
The RMI Architecture (System) has a FOUR layer,
(1) Application Layer
(2) Proxy Layer
(3) Remote Reference Layer
(4) Transport Layer
RMI Architecture Diagram:
(1) Application Layer:
It’s a responsible for the actual logic (implementation) of the client and server applications. Generally at the server side class contain implementation logic and also apply the reference to the appropriate object as per the requirement of the logic in application.
(2) Proxy Layer:
It’s also called the “Stub/Skeleton layer”. A Stub class is a client side proxy handles the remote objects which are getting from the reference. A Skeleton class is a server side proxy that set the reference to the objects which are communicates with the Stub.
(3) Remote Reference Layer (RRL):
It’s a responsible for manage the references made by the client to the remote object on the server so it is available on both JVM (Client and Server).
The Client side RRL receives the request for methods from the Stub that is transferred into byte stream process called serialization (Marshaling) and then these data are send to the Server side RRL. The Server side RRL doing reverse process and convert the binary data into object. This process called deserialization or unmarshaling and then sent to the Skeleton class.
(4) Transport Layer:
It’s also called the “Connection layer”. It’s a responsible for the managing the existing connection and also setting up new connections. So it is a work like a link between the RRL on the Client side and the RRL on the Server side.
Q: 6) Discuss Servlet life cycle methods. Explain role of web container.
A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet
The servlet is initialized by calling the init() method. The servlet calls service() method to process a client's request. The servlet is terminated by calling the destroy() method. Finally, servlet is garbage collected by the garbage collector of the JVM. Now let us discuss the life cycle methods in details.
The init() method :
The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.
The init method definition looks like this:
public void init() throws ServletException {
// Initialization code...
}
The service() method :
The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method:
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException{
}
The service () method is called by the container and service method invokes doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here is the signature of these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The destroy() method :
The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this:
public void destroy() {
// Finalization code...
}
Architecture Digram:
The following figure depicts a typical servlet life-cycle scenario. First the HTTP requests coming to the server are delegated to the servlet container. The servlet container loads the servlet before invoking the service() method. Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet.
Role of web container
Web container (also known as a Servlet container) is the component of a web server that interacts with Java servlets. A web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights. A web container implements the web component contract of the Java EE architecture, specifying a runtime environment for web components that includes security, concurrency, lifecycle management, transaction, deployment, and other services. A web container provides the same services as a JSP container as well as a federated view of the Java EE platform APIs
Non-commercial Web containers
- Apache Tomcat (formerly Jakarta Tomcat) is an open source web container available under the Apache Software License.
- Apache Geronimo is a full Java EE implementation by Apache.
- GlassFish (open source), from Oracle
- JBoss Application Server (open source) is a full Java EE implementation by Red Hat inc., division JBoss.
Commercial Web containers
· Sun GlassFish Server, from Sun Microsystems
· Sun Java System Web Server, from Sun Microsystems
· Sun Java System Application Server (is an Application Server, but includes a web container)
Q-7) Explain Socket, ServerSocket, InetAddress classes. Write a java program to find an IP address of the machine on which the program runs.
Sockets
A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.
Sockets are means to establish a communication link between machines over the network. The java.net package provides 4 kinds of Sockets:
- Socket is a TCP client API, and will typically be used to connect to a remote host.
- ServerSocket is a TCP server API, and will typically accept connections from client sockets.
- DatagramSocket is a UDP endpoint API and is used to send and receive datagram packets.
- MulticastSocket is a subclass of DatagramSocket used when dealing with multicast groups.
InetAddress Class
This class represents an Internet address, and is used when creating DatagramPacket or Socket objects. The class does not have a public constructor function, but instead supports three static methods which return one or more instances of InetAddress. getLocalHost() returns an InetAddress for the local host. getByName() returns the InetAddress of a host specified by name. getAllByName() returns an array ofInetAddress that represents all of the available addresses for a host specified by name. Instance methods are getHostName(), which returns the hostname of an InetAddress, and getAddress(), which returns the Internet IP address as an array of bytes, with the highest-order byte as the first element of the array.
public final class InetAddress extends Object implements Serializable {
// No Constructor
// Class Methods
public static InetAddress[] getAllByName(String host) throws UnknownHostException;
public static InetAddress getByName(String host) throws UnknownHostException;
public static InetAddress getLocalHost() throws UnknownHostException;
// Public Instance Methods
public boolean equals(Object obj); // Overrides Object
public byte[] getAddress();
public String getHostAddress();
public String getHostName();
public int hashCode(); // Overrides Object
public boolean isMulticastAddress();
public String toString(); // Overrides Object
}
Passed To:
DatagramPacket(), DatagramPacket.setAddress(), DatagramSocket(), DatagramSocketImpl.bind(), DatagramSocketImpl.join(), DatagramSocketImpl.leave(), DatagramSocketImpl.peek(), MulticastSocket.joinGroup(), MulticastSocket.leaveGroup(), MulticastSocket.setInterface(), SecurityManager.checkMulticast(), ServerSocket(), Socket(), SocketImpl.bind(), SocketImpl.connect()
Returned By:
DatagramPacket.getAddress(), DatagramSocket.getLocalAddress(), InetAddress.getAllByName(), InetAddress.getByName(), InetAddress.getLocalHost(), MulticastSocket.getInterface(), ServerSocket.getInetAddress(), Socket.getInetAddress(), Socket.getLocalAddress(), SocketImpl.getInetAddress()
Serversocket class
This class is used by servers to listen for connection requests from clients. When you create a ServerSocket, you specify the port to listen on. The accept() method begins listening on that port, and blocks until a client requests a connection on that port. At that point, accept() accepts the connection, creating and returning a Socket that the server can use to communicate with the client.
public class ServerSocket extends Object {
// Public Constructors
public ServerSocket(int port) throws IOException;
public ServerSocket(int port, int backlog) throws IOException;
public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException;
// Class Methods
public static synchronized void setSocketFactory(SocketImplFactory fac) throws IOException;
// Public Instance Methods
public Socket accept() throws IOException;
public void close() throws IOException;
public InetAddress getInetAddress();
public int getLocalPort();
public synchronized int getSoTimeout() throws IOException;
public synchronized void setSoTimeout(int timeout) throws SocketException;
public String toString(); // Overrides Object
// Protected Instance Methods
protected final void implAccept(Socket s) throws IOException;
}
Program that finds IP address:
import java.net.UnknownHostException;
public class IPTest {
public static void main(String args[]) throws UnknownHostException {
InetAddress addr = InetAddress.getLocalHost();
//Getting IPAddress of localhost - getHostAddress return IP Address
public class IPTest {
public static void main(String args[]) throws UnknownHostException {
InetAddress addr = InetAddress.getLocalHost();
//Getting IPAddress of localhost - getHostAddress return IP Address
// in textual format
String ipAddress = addr.getHostAddress();
System.out.println("IP address of localhost from Java Program: " + ipAddress);
//Hostname
String hostname = addr.getHostName();
System.out.println("Name of hostname : " + hostname);
}}
String ipAddress = addr.getHostAddress();
System.out.println("IP address of localhost from Java Program: " + ipAddress);
//Hostname
String hostname = addr.getHostName();
System.out.println("Name of hostname : " + hostname);
}}
Output:
IP address of localhost from Java Program: 190.12.209.123
Name of hostname : PCLOND3433
Q-8) List and explain various swing layouts and components with examples. Several AWT and Swing classes provide layout managers for general use:
Every content pane is initialized to use a BorderLayout. (As Using Top-Level Containers explains, the content pane is the main container in all frames, applets, and dialogs.) ABorderLayout places components in up to five areas: top, bottom, left, right, and center. All extra space is placed in the center area. Tool bars that are created using JToolBarmust be created within a BorderLayout container, if you want to be able to drag and drop the bars away from their starting positions.
The BoxLayout class puts components in a single row or column. It respects the components' requested maximum sizes and also lets you align components. For further details, see How to Use BoxLayout.
The CardLayout class lets you implement an area that contains different components at different times. A CardLayout is often controlled by a combo box, with the state of the combo box determining which panel (group of components) the CardLayout displays. An alternative to using CardLayout is using a tabbed pane, which provides similar functionality but with a pre-defined GUI. For further details, see How to Use CardLayout.
FlowLayout is the default layout manager for every JPanel. It simply lays out components in a single row, starting a new row if its container is not sufficiently wide. Both panels in CardLayoutDemo, shown previously, use FlowLayout. For further details, see How to Use FlowLayout.
GridBagLayout is a sophisticated, flexible layout manager. It aligns components by placing them within a grid of cells, allowing components to span more than one cell. The rows in the grid can have different heights, and grid columns can have different widths. For further details, see How to Use GridBagLayout.
GridLayout simply makes a bunch of components equal in size and displays them in the requested number of rows and columns. For further details, see How to Use GridLayout.
GroupLayout is a layout manager that was developed for use by GUI builder tools, but it can also be used manually. GroupLayout works with the horizontal and vertical layouts separately. The layout is defined for each dimension independently. Consequently, however, each component needs to be defined twice in the layout. The Find window shown above is an example of a GroupLayout. For further details, see How to Use GroupLayout.
SpringLayout is a flexible layout manager designed for use by GUI builders. It lets you specify precise relationships between the edges of components under its control. For example, you might define that the left edge of one component is a certain distance (which can be dynamically calculated) from the right edge of a second component.SpringLayout lays out the children of its associated container according to a set of constraints,
For program you can refer any example from class notebook or material.
Q-9) Explain JSP tag library with examples.
The JavaServer Pages API allows you to define custom JSP tags that look like HTML or XML tags and a tag library is a set of user-defined tags that implement custom behavior.
The taglib directive declares that your JSP page uses a set of custom tags, identifies the location of the library, and provides a means for identifying the custom tags in your JSP page.
The taglib directive follows the following syntax:
<%@ taglib uri="uri" prefix="prefixOfTag" >
Where the uri attribute value resolves to a location the container understands and the prefix attribute informs a container what bits of markup are custom actions.
You can write XML equivalent of the above syntax as follows:
<jsp:directive.taglib uri="uri" prefix="prefixOfTag" />
When you use a custom tag, it is typically of the form <prefix:tagname>. The prefix is the same as the prefix you specify in the taglib directive, and the tagname is the name of a tag implemented in the tag library
Example:
For example, suppose the custlib tag library contains a tag called hello. If you wanted to use the hello tag with a prefix of mytag, your tag would be <mytag:hello> and it will be used in your JSP file as follows:
<%@ taglib uri="http://www.example.com/custlib" prefix="mytag" %>
<html>
<body>
<mytag:hello/>
</body>
</html>
Q-10) Explain object serialization in detail with example
Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.
The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out:
public final void writeObject(Object x) throws IOException
The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object:
public final Object readObject() throws IOException,
ClassNotFoundException
This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type.
To demonstrate how serialization works in Java, I am going to use the Employee class that we discussed early on in the book. Suppose that we have the following Employee class, which implements the Serializable interface:
public class Employee implements java.io.Serializable
{
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck()
{
System.out.println("Mailing a check to " + name
+ " " + address);
}
}
Notice that for a class to be serialized successfully, two conditions must be met:
The class must implement the java.io.Serializable interface.
All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.
If you are curious to know if a Java Standard Class is serializable or not, check the documentation for the class. The test is simple: If the class implements java.io.Serializable, then it is serializable; otherwise, it's not.
Serializing an Object:
The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee object and serializes it to a file.
When the program is done executing, a file named employee.ser is created. The program does not generate any output, but study the code and try to determine what the program is doing.
Note: When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.
import java.io.*;
public class SerializeDemo
{
public static void main(String [] args)
{
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try
{
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
}catch(IOException i)
{
i.printStackTrace();
}
}
}
Deserializing an Object:
The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. Study the program and try to determine its output:
import java.io.*;
public class DeserializeDemo
{
public static void main(String [] args)
{
Employee e = null;
try
{
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}
This would produce the following result:
Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101
Here are following important points to be noted:
The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can't find a class during the deserialization of an object, it throws a ClassNotFoundException.
Notice that the return value of readObject() is cast to an Employee reference.
The value of the SSN field was 11122333 when the object was serialized, but because the field is transient, this value was not sent to the output stream. The SSN field of the deserialized Employee object is 0.
Q-11) Give the advantages of n-tier architecture and discuss the objectives of the Enterprise applications.
Advantages: there are following general advantages:
1. Scalable: this is due to its capability of multiple tier deployment and the tier decoupling it brought. For example, the data tier can be scaled up by database clustering without other tiers involving. The web client side can be scaled up by load-balancer easily without affecting other tiers. Windows server can be clustered easily for load balancing and failover. In addition, business tier server can also be clustered to scale up the application, such as Weblogic cluster in J2EE.
2. Better and finer security control to the whole system: we can enforce the security differently for each tier if the security requirement is different for each tier. For example, business tier and data tier usually need higher security level than presentation tier does, then we can put these two high security tiers behind firewall for protection. 1 or 2 tiers architecture cannot fully achieve this purpose because of a limited number of tiers. Also, for N-Tier architecture, users cannot access business layer and data layer directly, all requests from users are routed by client presenter layer to business layer, then to data layer. Therefore, client presenter layer also serves as a proxy-like layer for business layer, and business layer serves as a proxy-like layer for data layer. These proxy-like layers provides further protection for their layers below.
3. Better fault tolerance ability: for example, the databases in data layer can be clustered for failover or load balance purpose without affecting other layers.
4. Independent tier upgrading and changing without affecting other tiers: in object-oriented world, Interface-dependency implementation can decouples all layers very well so that each layer can change individually without affecting other layers too much. Interface-dependency means a layer depends on another layer by interfaces only, not concrete classes. Also, the dependency of a layer only on its directly-below layer also minimizes the side effect of a layer’s change on the whole system. For example, if keep the interfaces unchanged, we can update or replace the implementation of any layer independently without affecting the whole system. Due to the changing of business requirement and technology, changing the implementation of a layer to another totally different one does happen often. For example, originally we use Windows Form mainly, now we use WPF mainly. If our original system is implemented as the decoupled layer structure, then we will only need to update the client side from Windows Form to WPF without the need to change the server side layers.
5. Friendly and efficient for development: the decoupled layers are logic software component groups mainly by functionality, they are very software development friendly and efficient. Each layer can be assigned individually to a team who specializes in the specific functional area; a specialized team can handle the relevant task better and more efficiently.
6. Friendly for maintenance: N-Tier architecture groups different things together mainly by functionality and then makes things clear, easily understandable and manageable.
7. Friendly for new feature addition: due to the logical grouped components and the decoupling brought by N-Tier architecture, new features can be added easily without affecting too much on the whole system.
8. Better reusability: this is due to the logically grouped components and the loose couplings among layers. Loosely-coupled component groups are usually implemented in more general ways, so they can be reused by more other applications.
Objectives of enterprise application
Overview of Enterprise Applications
This section describes enterprise applications and how they are designed and developed.
As stated above, the Java EE platform is designed to help developers create large-scale, multi-tiered, scalable, reliable, and secure network applications. A shorthand name for such applications is “enterprise applications,” so called because these applications are designed to solve the problems encountered by large enterprises. Enterprise applications are not only useful for large corporations, agencies, and governments, however. The benefits of an enterprise application are helpful, even essential, for individual developers and small organizations in an increasingly networked world.The features that make enterprise applications powerful, like security and reliability, often make these applications complex. The Java EE platform is designed to reduce the complexity of enterprise application development by providing a development model, API, and runtime environment that allows developers to concentrate on functionality.
Tiered Applications
In a multi-tiered application, the functionality of the application is separated into isolated functional areas, called tiers. Typically, multi-tiered applications have a client tier, a middle tier, and a data tier (often called the enterprise information systems tier). The client tier consists of a client program that makes requests to the middle tier. The middle tier's business functions handle client requests and process application data, storing it in a permanent datastore in the data tier.
Java EE application development concentrates on the middle tier to make enterprise application management easier, more robust, and more secure.The Client Tier
The client tier consists of application clients that access a Java EE server and that are usually located on a different machine from the server. The clients make requests to the server. The server processes the requests and returns a response back to the client. Many different types of applications can be Java EE clients, and they are not always, or even often Java applications. Clients can be a web browser, a standalone application, or other servers, and they run on a different machine from the Java EE server.
The Web Tier
The web tier consists of components that handle the interaction between clients and the business tier. Its primary tasks are the following:
· Dynamically generate content in various formats for the client.
· Collect input from users of the client interface and return appropriate results from the components in the business tier.
· Control the flow of screens or pages on the client.
· Maintain the state of data for a user's session.
· Perform some basic logic and hold some data temporarily in JavaBeans components.
Q-12) Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes:
To intercept requests from a client before they access a resource at back end.
To manipulate responses from server before they are sent back to the client. There are are various types of filters suggested by the specifications:
Authentication Filters.
Data compression Filters.
Encryption Filters.
Filters that trigger resource access events.
Image Conversion Filters.
Logging and Auditing Filters.
MIME-TYPE Chain Filters.
Tokenizing Filters .
XSL/T Filters That Transform XML Content.
Filters are deployed in the deployment descriptor file web.xml and then map to either servlet names or URL patterns in your application's deployment descriptor.
When the web container starts up your web application, it creates an instance of each filter that you have declared in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.
Servlet Filter Methods:
A filter is simply a Java class that implements the javax.servlet.Filter interface. The javax.servlet.Filter interface defines three methods:
S.N. | Method & Description |
1 | public void doFilter (ServletRequest, ServletResponse, FilterChain) This method is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. |
2 | public void init(FilterConfig filterConfig) This method is called by the web container to indicate to a filter that it is being placed into service. |
3 | public void destroy() This method is called by the web container to indicate to a filter that it is being taken out of service. |
Q-13) JSP Implicit objects are created by the web container. These implicit objects are Java objects that implement interfaces in the Servlet and JSP API. Scripting elements in a JSP page can make use of these JSP implicit objects. There are nine (9) JSP implicit objects available.
JSP Implicit Objects are as follows:
1. request implicit object
The JSP implicit request object is an instance of a java class that implements the javax.servlet.http.HttpServletRequest interface. It represents the request made by the client. The request implicit object is generally used to get request parameters, request attributes, header information and query string values.
2. response implicit object
The JSP implicit response object is an instance of a java class that implements the javax.servlet.http.HttpServletResponse interface. It represents the response to be given to the client. The response implicit object is generally used to set the response content type, add cookie and redirect the response.
3. out implicit object
The JSP implicit out object is an instance of the javax.servlet.jsp.JspWriter class. It represents the output content to be sent to the client. The out implicit object is used to write the output content.
4. session implicit object
The JSP implicit session object is an instance of a java class that implements the javax.servlet.http.HttpSession interface. It represents a client specific conversation. The session implicit object is used to store session state for a single user.
5. application implicit object
The JSP implicit application object is an instance of a java class that implements the javax.servlet.ServletContext interface. It gives facility for a JSP page to obtain and set information about the web application in which it is running.
6. exception implicit object
The JSP implicit exception object is an instance of the java.lang.Throwable class. It is available in JSP error pages only. It represents the occured exception that caused the control to pass to the JSP error page.
7. config implicit object
The JSP implicit config object is an instance of the java class that implements javax.servlet.ServletConfig interface. It gives facility for a JSP page to obtain the initialization parameters available.
8. page implicit object
The JSP implicit page object is an instance of the java.lang.Object class. It represents the current JSP page. That is, it serves as a reference to the java servlet object that implements the JSP page on which it is accessed. It is not advisable to use this page implict object often as it consumes large memory.
9. pageContext implicit object
The JSP implicit pageContext object is an instance of the javax.servlet.jsp.PageContext abstract class. It provides useful context information. That is it provides methods to get and set attributes in different scopes and for transfering requests to other resources. Also it contains the reference to to implicit objects.
Q-14) What are cookies? Write a servlet that reads and prints all the previous cookiesand add a cookie with your name.
Cookies
Web applications are typically a series of Hypertext Transfer Protocol (HTTP) requests and responses. As HTTP is a stateless protocol, information is not automatically saved between HTTP requests. Web applications use cookies to store state information on the client. Cookies can be used to store information about the user, the user's shopping cart, and so on.Types of Cookies
The two types of cookies follow:- Session cookies – Session cookies are stored in memory and are accessible as long as the user is using the web application. Session cookies are lost when the user exits the web application. Such cookies are identified by a session ID and are most commonly used to store details of a shopping cart.
- Permanent cookies – Permanent cookies are used to store long-term information such as user preferences and user identification information. Permanent cookies are stored in persistent storage and are not lost when the user exits the application. Permanent cookies are lost when they expire.
Example from class notebook or from given material
q-15) The Hibernate architecture is layered to keep you isolated from having to know the underlying APIs. Hibernate makes use of the database and configuration data to provide persistence services (and persistent objects) to the application.
Following is a very high level view of the Hibernate Application Architecture.
Following is a detailed view of the Hibernate Application Architecture with few important core classes.
Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming and Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction of functionality common to relational databases, allowing almost any database with a JDBC driver to be supported by Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application servers.
Following section gives brief description of each of the class objects involved in Hibernate Application Architecture.
Configuration Object:
The Configuration object is the first Hibernate object you create in any Hibernate application and usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate. The Configuration object provides two keys components:
· Database Connection: This is handled through one or more configuration files supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml.
· Class Mapping Setup
This component creates the connection between the Java classes and database tables..
This component creates the connection between the Java classes and database tables..
SessionFactory Object:
Configuration object is used to create a SessionFactory object which inturn configures Hibernate for the application using the supplied configuration file and allows for a Session object to be instantiated. The SessionFactory is a thread safe object and used by all the threads of an application.
The SessionFactory is heavyweight object so usually it is created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file. So if you are using multiple databases then you would have to create multiple SessionFactory objects.
Session Object:
A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.
The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed.
Transaction Object:
A Transaction represents a unit of work with the database and most of the RDBMS supports transaction functionality. Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA).
This is an optional object and Hibernate applications may choose not to use this interface, instead managing transactions in their own application code.
Query Object:
Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.
Criteria Object:
Criteria object are used to create and execute object oriented criteria queries to retrieve objects.
Q-16) Enlist and explain need of JNDI with diagram. Explain J2EE architecture with diagram.
JNDI is an API specified in Java technology that provides naming and directory functionality to applications written in the Java programming language. It is designed especially for the Java platform using Java's object model. Using JNDI, applications based on Java technology can store and retrieve named Java objects of any type. In addition, JNDI provides methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes.
JNDI is also defined independent of any specific naming or directory service implementation. It enables applications to access different, possibly multiple, naming and directory services using a common API. Different naming and directory service providers can be plugged in seamlessly behind this common API. This enables Java technology-based applications to take advantage of information in a variety of existing naming and directory services, such as LDAP, NDS, DNS, and NIS(YP), as well as enabling the applications to coexist with legacy software and systems.
Using JNDI as a tool, you can build new powerful and portable applications that not only take advantage of Java's object model but are also well-integrated with the environment in which they are deployed.
Q-17) Explain the use of the PreparedStatement object of the JDBC with an
appropriate example.
As mentioned in Q-4)
Q-18) Write a client-server program using TCP sockets to echo the message send by the client.
/* Implementation of Echo Server and Client Using TCP */
// EchoServer.java : A Simple Echo Server Program
import java.io.*;
import java.net.*;
public class EchoServer
{
public static void main(String args[]) throws Exception
{
try
{
int Port;
BufferedReader Buf =new BufferedReader(new
InputStreamReader(System.in));
System.out.print(" Enter the Port Address : " );
Port=Integer.parseInt(Buf.readLine());
ServerSocket sok =new ServerSocket(Port);
System.out.println(" Server is Ready To Receive a Message. ");
System.out.println(" Waiting ..... ");
Socket so=sok.accept();
if(so.isConnected()==true)
System.out.println(" Client Socket is Connected Succecfully. ");
InputStream in=so.getInputStream();
OutputStream ou=so.getOutputStream();
PrintWriter pr=new PrintWriter(ou);
BufferedReader buf=new BufferedReader(new
InputStreamReader(in));
String str=buf.readLine();
System.out.println(" Message Received From Client : " + str);
System.out.println(" This Message is Forwarded To Client. ");
pr.println(str);
pr.flush();
}
catch(Exception e)
{
System.out.println(" Error : " + e.getMessage());
}
}
}
// EchoClient.java: A Simple Echo Client Program
import java.io.*;
import java.net.*;
public class EchoClient
{
public static void main(String args[]) throws Exception
{
try {
int Port;
BufferedReader Buf =new BufferedReader(new
InputStreamReader(System.in));
System.out.print(" Enter the Port Address : " );
Port=Integer.parseInt(Buf.readLine());
Socket sok=new Socket("localhost",Port);
if(sok.isConnected()==true)
System.out.println(" Server Socket is Connected Succecfully. ");
InputStream in=sok.getInputStream();
OutputStream ou=sok.getOutputStream();
PrintWriter pr=new PrintWriter(ou);
BufferedReader buf1=new BufferedReader(new
InputStreamReader(System.in));
BufferedReader buf2=new BufferedReader(new
InputStreamReader(in));
String str1,str2;
System.out.print(" Enter the Message : ");
str1=buf1.readLine();
pr.println(str1);
pr.flush();
System.out.println(" Message Send Successfully. ");
str2=buf2.readLine();
System.out.println(" Message From Server : " + str2);
}
catch(Exception e)
{
System.out.println(" Error : " + e.getMessage());
}
}
}
OUTPUT :
EchoServer.java :
javac EchoServer.java
java EchoServer
Enter the Port Address : 1234
Server is Ready To Receive a Message.
Waiting .....
Client Socket is Connected Succecfully.
Message Received From Client : Welcome To JCE
This Message is Forwarded To Client.
Q-19) Describe the following.
1. Remote reference layer in RMI architecture.
2. Use of the URL class.
RRL
The Remote Reference Layers defines and supports the invocation semantics of the RMIconnection.This layer provides a
RemoteRef
object that represents the link to the remote service implementation object.The stub objects use the
invoke()
method in RemoteRef
to forward the method call. The RemoteRef
object understands the invocation semantics for remote services.The JDK 1.1 implementation of RMI provides only one way for clients to connect to remote service implementations: a unicast, point-to-point connection. Before a client can use a remote service, the remote service must be instantiated on the server and exported to the RMI system. (If it is the primary service, it must also be named and registered in the RMI Registry).
The Java 2 SDK implementation of RMI adds a new semantic for the client-server connection. In this version, RMI supports activatable remote objects. When a method call is made to the proxy for an activatable object, RMI determines if the remote service implementation object is dormant. If it is dormant, RMI will instantiate the object and restore its state from a disk file. Once an activatable object is in memory, it behaves just like JDK 1.1 remote service implementation objects.
Other types of connection semantics are possible. For example, with multicast, a single proxy could send a method request to multiple implementations simultaneously and accept the first reply (this improves response time and possibly improves availability). In the future, Sun may add additional invocation semantics to RMI.
URL class
URL stands for Uniform Resource Locator and represents a resource on the World Wide Web, such as a Web page or FTP directory.
This section shows you how to write Java programs that communicate with a URL. A URL can be broken down into parts, as follows:
protocol://host:port/path?query#ref
Examples of protocols include HTTP, HTTPS, FTP, and File. The path is also referred to as the filename, and the host is also called the authority.
The following is a URL to a Web page whose protocol is HTTP:
http://www.amrood.com/index.htm?language=en#j2se
Notice that this URL does not specify a port, in which case the default port for the protocol is used. With HTTP, the default port is 80.
URL Class Methods:
The java.net.URL class represents a URL and has complete set of methods to manipulate URL in Java.
The URL class has several constructors for creating URLs, including the following:
SN | Methods with Description |
1 | public URL(String protocol, String host, int port, String file) throws MalformedURLException. Creates a URL by putting together the given parts. |
2 | public URL(String protocol, String host, String file) throws MalformedURLException Identical to the previous constructor, except that the default port for the given protocol is used. |
3 | public URL(String url) throws MalformedURLException Creates a URL from the given String |
4 | public URL(URL context, String url) throws MalformedURLException Creates a URL by parsing the together the URL and String arguments |
The URL class contains many methods for accessing the various parts of the URL being represented. Some of the methods in the URL class include the following:
SN | Methods with Description |
1 | public String getPath() Returns the path of the URL. |
2 | public String getQuery() Returns the query part of the URL. |
3 | public String getAuthority() Returns the authority of the URL. |
4 | public int getPort() Returns the port of the URL. |
5 | public int getDefaultPort() Returns the default port for the protocol of the URL. |
6 | public String getProtocol() Returns the protocol of the URL. |
7 | public String getHost() Returns the host of the URL. |
8 | public String getHost() Returns the host of the URL. |
9 | public String getFile() Returns the filename of the URL. |
10 | public String getRef() Returns the reference part of the URL. |
11 | public URLConnection openConnection() throws IOException Opens a connection to the URL, allowing a client to communicate with the resource. |
Example:
The following URLDemo program demonstrates the various parts of a URL. A URL is entered on the command line, and the URLDemo program outputs each part of the given URL.
// File Name : URLDemo.java
import java.net.*;
import java.io.*;
public class URLDemo
{
public static void main(String [] args)
{
try
{
URL url = new URL("http://www.amrood.com/index.htm?language=en#j2se");
System.out.println("URL is " + url.toString());
System.out.println("protocol is "
+ url.getProtocol());
System.out.println("authority is "
+ url.getAuthority());
System.out.println("file name is " + url.getFile());
System.out.println("host is " + url.getHost());
System.out.println("path is " + url.getPath());
System.out.println("port is " + url.getPort());
System.out.println("default port is "
+ url.getDefaultPort());
System.out.println("query is " + url.getQuery());
System.out.println("ref is " + url.getRef());
}catch(IOException e)
{
e.printStackTrace();
}
}
}
Solutions to Find Appropriate Packers and Movers in Pune
ReplyDeletepackers and movers pune
Welcome to here, a premium online tool helping consumers relocate from one place to another with household belongings or commercial commodities. We have made it easy to find right services, right moving companies and other related information in different major cities and towns of India packers and movers in pune.
movers and packers in pune