Now comes the most important part i.e executing the query. Query here is an SQL Query . Now we know we can have multiple types of queries. Some of them are as follows: Query for updating / inserting table in a database. Query for retrieving data . The executeQuery() method of Statement interface is used to execute queries of retrieving values from the database. This method returns the object of ResultSet that can be used to get all the records of a table. The executeUpdate(sql query) method ofStatement interface is used to execute queries of updating/inserting . Example: int m = st.executeUpdate(sql); if (m==1) System.out.println(\"inserted successfully : \"+sql); else System.out.println(\"insertion failed\"); Here sql is sql query of the type String 5. Close the connections So finally we have sent the data to the specified location and now we are at the verge of completion of our task . By closing connection, objects of Statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection. Example : importjava.sql.*; importjava.util.*; class Main { public static void main(String a[]) { //Creating the connection String url = \"jdbc:oracle:thin:@localhost:1521:xe\"; String user = \"system\"; CU IDOL SELF LEARNING MATERIAL (SLM) 301
String pass = \"12345\"; //Entering the data Scanner k = new Scanner(System.in); System.out.println(\"enter name\"); String name = k.next(); System.out.println(\"enter roll no\"); int roll = k.nextInt(); System.out.println(\"enter class\"); String cls = k.next(); //Inserting data using SQL query String sql = \"insert into student1 values('\"+name+\"',\"+roll+\",'\"+cls+\"')\"; Connection con=null; try { DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); //Reference to connection interface con = DriverManager.getConnection(url,user,pass); Statement st = con.createStatement(); int m = st.executeUpdate(sql); if (m == 1) System.out.println(\"inserted successfully : \"+sql); else System.out.println(\"insertion failed\"); con.close(); } catch(Exception ex) CU IDOL SELF LEARNING MATERIAL (SLM) 302
{ System.err.println(ex); } } } con.close(); Output: Figure 13.1: Output of establishing a connection 13.4 TRANSACTIONS WITH DATABASE A database transaction (DB transaction) is a unit of work that is either completed as a unit or undone as a unit. Proper database transaction processing is critical to maintaining the integrity of your databases. Suppose you are entering new customer records into your database and are entering the 99th customer record. If your machine goes down, are the first 98 records you entered lost? No, because WebSpeed: Keeps the first 98 records in the database Discards the partial 99th record This is just one simple scenario. Suppose the procedure was updating multiple tables. You want to make sure that WebSpeed saves any completed changes and discards partial changes in all tables. CU IDOL SELF LEARNING MATERIAL (SLM) 303
System failures are just one kind of error. There are other kinds of errors that can occur while a procedure is running. Regardless of the kind of error you are dealing with, data integrity is all important. Data integrity means that WebSpeed only stores completed data in the database. WebSpeed uses database transactions to automatically handle this processing. For any WebSpeed application that updates a database, you must consider at what point you want a database transaction to begin and how many page requests you need it to last. In other words, how much of a database update do you want to roll back at one time in the event of an error, exception, or incorrect data input. 13.5 SUMMARY JDBC or Java Database Connectivity is a specification from Sun microsystems that provides a standard abstraction (that is API or Protocol) for java applications to communicate with various databases. It provides the language with java database connectivity standard. It is used to write programs required to access databases. Enterprise applications that are created using the JAVA EE technology need to interact with databases to store application-specific information. So, interacting with a database requires efficient database connectivity which can be achieved by using the ODBC(Open database connectivity) driver. JDBC is an acronym for Java Database Connectivity. It’s advancement for ODBC JDBC is an standard API specification developed in order to move data from frontend to backend. This API consists of classes and interfaces written in Java. A database transaction (DB transaction) is a unit of work that is either completed as a unit or undone as a unit. Proper database transaction processing is critical to maintaining the integrity of your databases. JDBC is an API(Application programming interface) which is used in java programming to interact with databases. 13.6 KEYWORDS JDBC: The Java Database Connectivity (JDBC) API provides universal data access from the Java programming language. Using the JDBC API, you can access virtually any data source, from relational databases to spreadsheets and flat files. ODBC: ODBC stands for Open Database Connectivity which literally means that it is compatible with all types of languages such as C, C++, Java, etc. JDBC Stands for Java database connectivity i.e only compatible with java language. 2. Introduction. ODBC was introduced by Microsoft prior to JDBC in 1992 CU IDOL SELF LEARNING MATERIAL (SLM) 304
Blob class: An SQL BLOB is a built-in type that stores a Binary Large Object as a column value in a row of a database table. ... Methods in the interfaces ResultSet , CallableStatement , and PreparedStatement , such as getBlob and setBlob allow a programmer to access an SQL BLOB value. Thin driver: It is a pure Java driver used on the client-side, without an Oracle client installation. It can be used with both applets and applications. Oracle Call Interface (OCI) driver. It is used on the client-side with an Oracle client installation. Native Driver: The Native API driver uses the client -side libraries of the database. This driver converts JDBC method calls into native calls of the database API. In order to interact with different database, this driver needs their local API, that's why data transfer is much more secure as compared to type-1 driver. 13.7 LEARNING ACTIVITY 1. Discuss the topic JDBC. ________________________________________________________________________ __________________________________________________________________ 2. Conduct a seminar on establishing a connection. ________________________________________________________________________ __________________________________________________________________ 13.8 UNIT END QUESTIONS A. Descriptive Questions Short Questions: 1. What is JDBC? 2. What is the return type of Class.forName() method? 3. What do you mean by events source? 4. What is transaction with database? 5. List the types of JDBC drivers. Long Questions: 1. What is JDBC Driver? Explain in detail. 2. What are the steps to connect to the database in java? 3. What are swing components? Explain. 4. Explain database connectivity. CU IDOL SELF LEARNING MATERIAL (SLM) 305
5. Explain transaction with database. B. Multiple Choice Questions 1. What are the major components of the JDBC? a. DriverManager, Driver, Connection, Statement, and ResultSet b. DriverManager, Driver, Connection, and Statement c. DriverManager, Statement, and ResultSet d. DriverManager, Connection, Statement, and ResultSet 2. Select the packages in which JDBC classes are defined? a. jdbc and javax.jdbc b. rdb and javax.rdb c. jdbc and java.jdbc.sql d. sql and javax.sql 3. What is Thin driver also known as? a. Type 3 Driver b. Type-2 Driver c. Type-4 Driver d. Type-1 Driver 4. Which of the following method is used to perform DML statements in JDBC? a. ExecuteResult() b. ExecuteQuery() c. ExecuteUpdate() d. Execute() 5. Which of the following is not a valid statement in JDBC? a. Statement b. PreparedStatement c. QueryStatement d. CallableStatement CU IDOL SELF LEARNING MATERIAL (SLM) 306
Answers 1-a, 2-d, 3-c, 4-c, 5-c 13.9 REFERENCES References Fowler, Amy (1994). \"Mixing heavy and light components\". Sun Microsystems. Torre, Mario (2 March 2008). \"FINAL PROPOSAL: Portable GUI backends\". Kennke, Roman (3 September 2008). \"Cacio Swing AWT peers\". Textbooks Kennke, Roman (28 July 2011). \"JDK7 and Cacio coolness\". Retrieved 8 August 2011. Eisserer, Clemens. \"HTML5/Canvas backend for Caciocavallo (GNU-Classpath)\". John Zukowski, Java AWT Reference, O'Reilly, 1997. Website https://www.mygreatlearning.com https://www.w3schools.com https://beginnersbook.com CU IDOL SELF LEARNING MATERIAL (SLM) 307
UNIT – 14: AN OVERVIEW OF RMI APPLICATIONS STRUCTURE 14.0 Learning Objectives 14.1 Introduction 14.2 An Overview of RMI Applications 14.3Remote Classes and Interfaces 14.3.1 Remote Interface 14.3.2 Remote Class 14.4 RMI Architecture 14.5 RMI Object Hierarchy 14.6Security 14.7 Summary 14.8 Keywords 14.9 Learning Activity 14.10Unit End Questions 14.11 References 14.0 LEARNING OBJECTIVES After studying this unit, you will be able to: Explain remote classes and interfaces Decsibe the RMI architecture Illustrate RMI object hierarchyand security 14.1 INTRODUCTION Java RMI is a specification for how Java Object can be accessed remotely. Java RMI allows programmers to execute remote function class using the same semantics as local functions calls. The implementation of RMI is within the Java Remote Method Protocol library. The main Drawback of RMI is that it is a Java to Java Communication only. A Remote Object is an object that resides on another computer and can be invoked remotely. Remote methods must include in their signature the throws RemoteException. CU IDOL SELF LEARNING MATERIAL (SLM) 308
The Simple scenario for RMI is as follows: The server must first bind its name to the registry The client lookup the server’s name in the registry to establish remote references 14.2 AN OVERVIEW OF RMI APPLICATIONS RMI applications often comprise 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. A typical client program obtains a remote reference to one or more remote objects on a server and then invokes methods on them. RMI provides the mechanism by which the server and the client communicate and pass information back and forth. Such an application is sometimes referred to as a distributed object application. Distributed object applications need to do the following: Locate remote objects. Applications can use various mechanisms to obtain references to remote objects. For example, an application can register its remote objects with RMI's simple naming facility, the RMI registry. Alternatively, an application can pass and return remote object references as part of other remote invocations. Communicate with remote objects. Details of communication between remote objects are handled by RMI. To the programmer, remote communication looks similar to regular Java method invocations. Load class definitions for objects that are passed around. Because RMI enables objects to be passed back and forth, it provides mechanisms for loading an object's class definitions as well as for transmitting an object's data. The following illustration depicts an RMI distributed application that uses the RMI registry to obtain a reference to a remote object. The server calls the registry to associate (or bind) 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. The illustration also shows that the RMI system uses an existing web server to load class definitions, from server to client and from client to server, for objects when needed. 14.3 REMOTE CLASS AND INTERFACE A Remote interface is available in the java.rmi package it is a marking/tagging interface, it is used with remote method invocation(RMI). RMI is a mechanism that allows an object residing in one system (JVM) to access/invoke an object running on another JVM. CU IDOL SELF LEARNING MATERIAL (SLM) 309
To it is a marking interface, to mark an object of a class remote, you need to implement this interface. To create a remote interface − Create an interface that extends the predefined interface Remote which belongs to the package or, implement the Remote interface with the class, which you need to make remote. Declare all the business methods that can be invoked by the client in this interface. Since there is a chance of network issues during remote calls, an exception named RemoteException may occur; throw it. Example: import java.rmi.Remote; import java.rmi.RemoteException; // Creating Remote class for our application public class RemoteExample implements Remote { } Or, import java.rmi.Remote; import java.rmi.RemoteException; // Creating Remote interface for our application public interface Hello extends Remote { void printMsg() throws RemoteException; } 14.4 RMI ARCHITECTURE RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in one system (JVM) to access/invoke an object running on another JVM. RMI is used to build distributed applications; it provides remote communication between Java programs. It is provided in the package java.rmi. Architecture of an RMI Application In an RMI application, we write two programs, a server program (resides on the server) and a client program (resides on the client). CU IDOL SELF LEARNING MATERIAL (SLM) 310
Inside the server program, a remote object is created and reference of that object is made available for the client (using the registry). The client program requests the remote objects on the server and tries to invoke its methods. The following diagram shows the architecture of an RMI application. Figure 14.1: Architecture of an RMI application. Let us now discuss the components of this architecture. Transport Layer − this layer connects the client and the server. It manages the existing connection and also sets up new connections. Stub − A stub is a representation (proxy) of the remote object at client. It resides in the client system; it acts as a gateway for the client program. Skeleton − this is the object which resides on the server side. Stub communicates with this skeleton to pass request to the remote object. RRL(Remote Reference Layer) − It is the layer which manages the references made by the client to the remote object. Working of an RMI Application The following points summarize how an RMI application works − When the client makes a call to the remote object, it is received by the stub which eventually passes this request to the RRL. When the client-side RRL receives the request, it invokes a method called invoke() of the object remoteRef. It passes the request to the RRL on the server side. The RRL on the server side passes the request to the Skeleton (proxy on the server) which finally invokes the required object on the server. CU IDOL SELF LEARNING MATERIAL (SLM) 311
The result is passed all the way back to the client. 14.5 RMI OBJECT HIERARCHY class java.lang.Object class java.io.InputStream class java.io.ObjectInputStream (implements java.io.ObjectInput, java.io.ObjectStreamConstants) java.io.ObjectOutput, class sun.rmi.server.MarshalInputStream class java.rmi.MarshalledObject.MarshalledObjectInputStream class java.rmi.MarshalledObject (implements java.io.Serializable) class java.rmi.Naming class java.rmi.Naming.ParsedNamingURL class java.io.OutputStream class java.io.ObjectOutputStream (implements java.io.ObjectStreamConstants) class sun.rmi.server.MarshalOutputStream class java.rmi.MarshalledObject.MarshalledObjectOutputStream class java.lang.SecurityManager class java.rmi.RMISecurityManager class java.lang.Throwable (implements java.io.Serializable) class java.lang.Exception class java.rmi.AlreadyBoundException class java.io.IOException class java.rmi.RemoteException class java.rmi.AccessException class java.rmi.ConnectException class java.rmi.ConnectIOException class java.rmi.MarshalException class java.rmi.NoSuchObjectException class java.rmi.ServerError CU IDOL SELF LEARNING MATERIAL (SLM) 312
class java.rmi.ServerException class java.rmi.ServerRuntimeException class java.rmi.StubNotFoundException class java.rmi.UnexpectedException class java.rmi.UnknownHostException class java.rmi.UnmarshalException class java.rmi.NotBoundException class java.lang.RuntimeException class java.lang.SecurityException class java.rmi.RMISecurityException 14.6 SECURITY Improve the security of your RMI applications by following these recommendations: Follow Secure Coding Guidelines for Java SE. Always run a security manager when using RMI, either on a client or server. See The Security Manager in The Java Tutorials. Establish a reasonable security policy. For example, grant SocketPermission and allow listen, accept, connect, and resolve actions only among hosts communicating with RMI. Do not have the security policy grant AllPermission. See Permissions in the JDK and Default Policy Implementation and Policy File Syntax. If RMI is being used only for communication among JVMs on the local host, restrict communications to be local only. Accomplish this by specifying the appropriate socket permissions in the security policy file as described previously. Alternatively, you can use RMI APIs directly to restrict connections only to the local host. See an example of this in the documentation for the RMISocketFactory class. Ensure that the value of the java.rmi.server.useCodebaseOnly property is true (which is the default value). Setting this property to false enables remote code loading, which increases the level of security risk to the system. See java.rmi Properties. Run RMI over SSL/TLS, and require authentication for both server and client. For further information, see the following: o The SslRMIClientSocketFactory class o The SslRMIServerSocketFactory class CU IDOL SELF LEARNING MATERIAL (SLM) 313
o Using Java RMI with SSL o Java Secure Socket Extension (JSSE) Reference Guide o JSSE Sample Code 14.7 SUMMARY Java RMI is a specification for how Java Object can be accessed Remotely. Java RMI allows programmers to execute remote function class using the same semantics as local functions calls. The implementation of RMI is within the Java Remote Method Protocol library. The main Drawback of RMI is that it is a Java to Java Communication only. RMI applications often comprise 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. A Remote interface is available in the java.rmi package it is a marking/tagging interface, it is used with remote method invocation(RMI). RMI is used to build distributed applications; it provides remote communication between Java programs. It is provided in the package java.rmi. Communicate with remote objects. Details of communication between remote objects are handled by RMI. To the programmer, remote communication looks similar to regular Java method invocations. 14.8 KEYWORDS RMI:RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in one system (JVM) to access/invoke an object running on another JVM. RMI is used to build distributed applications; it provides remote communication between Java programs. It is provided in the package java. Remote interface:In RMI, a remote interface is an interface that declares a set of methods that may be invoked from a remote Java virtual machine. ... A remote interface must at least extend, either directly or indirectly, the interface java. rmi. Stub:A stub is a controllable replacement for an existing dependency (or collaborator) in the system. By using a stub, you can test your code without dealing with the dependency directly. A mock object is a fake object in the system that decides whether the unit test has passed or failed. Skeleton: In the Java remote method invocation (Java RMI) nomenclature, a stub communicates on the client-side with a skeleton on the server-side. A class skeleton is CU IDOL SELF LEARNING MATERIAL (SLM) 314
an outline of a class that is used in software engineering.The class is later implemented from the skeleton. RRL(Remote Reference Layer): It is the layer which manages the references made by the client to the remote object. 14.9 LEARNING ACTIVITY 1. Conduct a seminar on an overview of RMI application. ________________________________________________________________________ __________________________________________________________________ 2. Discuss the topic RMI architecture. ________________________________________________________________________ __________________________________________________________________ 14.10 UNIT END QUESTIONS A. Descriptive Questions Short Questions: 1. What is Java Remote Method Invocation (RMI)? 2. What is RMI remote object? 3. List the Different layers of RMI architecture. 4. What is remote interface in RMI? 5. What do you mean by RMI architecture? Long Questions: 1. What is Java Remote Method Invocation (RMI)? Explain. 2. List and explain Different layers of RMI architecture. 3. What is RMI architecture? Explain. 4. Explain remote class and interface? 5. How an RMI application works? Explain. B. Multiple Choice Questions 1. What is Remote method invocation (RMI)? a. RMI allows us to invoke a method of java object that executes on another machine CU IDOL SELF LEARNING MATERIAL (SLM) 315
b. RMI allows us to invoke a method of java object that executes on another Thread in multithreaded programming c. RMI allows us to invoke a method of java object that executes parallely in same machine d. None of these 2. Which of these package is used for remote method invocation? a. Java.applet b. Java.rmi c. Java.lang.rmi d. Java.lang.reflect 3. Which of these methods are member of Remote class? a. CheckIP() b. AddLocation() c. AddServer() d. None of these 4. Which of these Exceptions is thrown by remote method? a. RemoteException b. InputOutputException c. RemoteAccessException d. RemoteInputOutputException 5. Which of these package is used for all the text related modifications? a. Java.text b. Java.awt c. Java.lang.text d. Java.text.modify Answers 1-a, 2-b, 3-d, 4-a, 5-a CU IDOL SELF LEARNING MATERIAL (SLM) 316
14.11 REFERENCES References Wilson, M. Jeff (November 10, 2000). \"Get smart with proxies and RMI\". Taylor, Ian J (2005). From P2P to Web Services and Grids : Peers in a Client/Server World. Computer Communications and Networks. London: Springer-Verlag Kennke, Roman (3 September 2008). \"Cacio Swing AWT peers\". Archived from the original on 13 March 2012. Retrieved 7 September 2008. Textbooks Kennke, Roman (28 July 2011). \"JDK7 and Cacio coolness\". Retrieved 8 August 2011. Eisserer, Clemens. \"HTML5/Canvas backend for Caciocavallo (GNU-Classpath)\". Archived from the original on 21 March 2012. Retrieved 8 August 2011. John Zukowski, Java AWT Reference, O'Reilly, 1997. Website https://www.mygreatlearning.com https://www.w3schools.com https://beginnersbook.com CU IDOL SELF LEARNING MATERIAL (SLM) 317
UNIT – 15: JAVA SERVLETS STRUCTURE 15.0 Learning Objectives 15.1 Introduction 15.2 Java Servlets 15.3 Servlet Life Cycle 15.4 Get and Post Methods 15.4.1 Get Method 15.4.2 Post Method 15.4.3 Difference between GET and POST method 15.5 Session Handling 15.6 Java Beans 15.6.1 Advantages of Java Beans 15.6.2 Introspection 15.6.3 Bound and Constrained Properties 15.6.4 Persistence 15.6.5 Customizers 15.6.6 The Java Beans API 15.6.7 A Bean Example 15.6 Security 15.7 Summary 15.8 Keywords 15.9 Learning Activity 15.10 Unit End Questions 15.11 References 15.0 LEARNING OBJECTIVES After studying this unit, you will be able to: Illustrate Java Servletsand Life Cycle CU IDOL SELF LEARNING MATERIAL (SLM) 318
Describe Get and Post Methods Explain Session Handlingand Java Beans 15.1 INTRODUCTION Servlets provide a component-based, platform-independent method for building Webbased applications, without the performance limitations of CGI programs. Servlets have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps. Why to Learn Servlet? Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically. Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface. But Servlets offer several advantages in comparison with the CGI. Performance is significantly better. Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request. Servlets are platform-independent because they are written in Java. Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted. The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already. 15.2 JAVA SERVLETS Java Servlets are programs that run on a Web or Application server and act as a middle layer between a requests coming from a Web browser or other HTTP client and databases or applications on the HTTP server. Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically. Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI. Performance is significantly better. CU IDOL SELF LEARNING MATERIAL (SLM) 319
Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request. Servlets are platform-independent because they are written in Java. Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted. The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already. Servlets Tasks Servlets perform the following major tasks − Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program. Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth. Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly. Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc. Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other client’s what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks. 15.3 SERVLET LIFE CYCLE 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 detail. The init () Method CU IDOL SELF LEARNING MATERIAL (SLM) 320
The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards. 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 doGet, 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. CU IDOL SELF LEARNING MATERIAL (SLM) 321
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... } 15.4 GET AND POST METHODS GET and POST method in HTTP and HTTPS are two most popular methods used to transfer data from client to server using HTTP(HyperText Transfer Protocol) protocol. Both GET and POST can be used to send requests and receive response but there are significant differences between them. The difference between GET and POST in HTTP or HTTPS is also a popular interview question in JSP and any web programming interview. Since HTML is independent of any web server technology like Java, ASP or PHP and HTTP is core protocol in space of the internet, the importance of a clear understanding of GET and POST method cannot be ignored. 15.4.1 Get Method HTTP protocol supports several request methods you can use while sending requests using HTTP or HTTPS protocol. GET is one of them. As the name suggests the GET method is to CU IDOL SELF LEARNING MATERIAL (SLM) 322
retrieve a page from the HTTP Server. You can identify a GET request by looking method attribute on the HTTP Request part. If you are using Netbeans IDE for Java web development you can enable HTTP Server monitor which can capture HTTP requests and show details of request parameters, headers, and other useful information. for GET HTTP request method will be GET for example almost all the URL which is accessible using link are accessed using HTTP Request. One important property of GET request is that any request parameter or query parameter is passed as URL encoded string, appended using \"?\" character which makes it non-secure because whatever information you pass in URL String is visible to everybody. Though GET method has some very interesting and powerful use cases which we will see in the next section: When to use HTTP GET request As I said GET method is not secure and hence not a suitable choice for transferring confidential data but GET method is extremely useful for retrieving static content from web server. Here are some examples where a using GET method makes sense: There is no side effect of repeated request. For example clicking a link which points to another page. it doesn't matter if you click the link twice or thrice , This also gives chance browser of the server to catch the response for faster retrieval. You are not passing any sensitive and confidential information. instead you just passing some configuration data or session id. You want URL pointed by HTTP GET request to be bookmark-able. Data requires to be sent to Server is not large and can safely accommodate in the maximum length of URL supported by all browsers. In general different browser has a different character limit for URL length but having it under the limit is a good choice. 15.4.2 Post Method POST HTTP request is denoted by the method: POST in the HTTP request. In POST method data is not sent as part of a URL string to server instead in POST, data is sent as part of message body. Almost all authentication requests is sent via POST method in HTTP world. POST method is secure because data is not visible in URL String and can be safely encrypted using HTTPS for further security. All sensitive and confidential information sent to be server must go on POST request and via HTTPS (HTTP with SSL). POST method is also used for submitting information to server, any information which can alter state of application like adding item into shopping cart, CU IDOL SELF LEARNING MATERIAL (SLM) 323
making payments etc. here are some examples where you should consider using POST method in HTTP request: Use POST if you are sending large data which cannot be fit into URL in case of GET. Use the POST method if you are passing sensitive and confidential information to server e.g. user_id, password, account number etc. Use the POST method if you are submitting data that can alter the state of application e.g. adding items into cart for passing that cart for payment processing. Use POST if you are writing a secure application and don't want to show query parameters in the URL. You can further see these Servlet and JSP courses to learn more about the POST method and how they are processed in Java. 15.4.3 Difference between GET and POST method Most of the difference between GET and POST has been already discussed in their respective sections. It all depends upon requirement when you want to choose GET and POST and knowledge of these differences help you to make that decision. GET method passes request parameter in URL String while POST method passes the request parameter in request body. GET request can only pass limited amount of data while POST method can pass large amount of data to server. GET requests can be bookmarked and cached unlike POST requests. GET is mostly used for view purpose (e.g. SQL SELECT) while POST is mainly use for update purpose (e.g. SQL INSERT or UPDATE). 15.5 SESSION HANDLING Session tracking or Session management is an important feature of modern web applications which allows the server to remember its clients. By keeping a session for each user, the Server can serve the client better. It also helps in safety, security, and personalization and must for certain kinds of web applications like e-commerce sites like Amazon or e-bay which stores items selected by the user for purchase in a shopping cart, even after the user is logged out. Since HTTP is a stateless protocol, there are no ways to know that two HTTP requests are related to each other i.e. they are coming from the same client or they are part of the same process. Session tracking is a mechanism that Servlets and Java Web applications use to maintain a state about a series of requests from the same user across some period of time. CU IDOL SELF LEARNING MATERIAL (SLM) 324
By keeping a session, an e-commerce site can maintain add to card facility and also keep track of how you interact with the application. Since HTTP doesn't provide a default way to track Sessions, there are some non-standard ways to manage Sessions in Servlet JSP-based applications. Let's have a close look at them. 15.6 JAVA BEANS JavaBeans is a portable, platform-independent model written in Java Programming Language. Its components are referred to as beans. In simple terms, JavaBeans are classes which encapsulate several objects into a single object. It helps in accessing these objects from multiple places. JavaBeans contains several elements like Constructors, Getter/Setter Methods and much more. JavaBeans has several conventions that should be followed: Beans should have a default constructor (no arguments) Beans should provide getter and setter methods o A getter method is used to read the value of a readable property o To update the value, a setter method should be called Beans should implement java.io.serializable, as it allows to save, store and restore the state of a JavaBean you are working on 15.6.1 Advantages of Java Beans There are various advantages of a JavaBean that are as follows. 1. Exposure to other applications One of the most important advantages of a JavaBean is, the events properties and the methods of a bean can be exposed directly to another application. 2. Registration to receive events A JavaBean can be registered to receive events from other objects. However, we can also generate events that can be sent to other objects. 3. Ease of configuration We can easily use auxiliary software to configure the JavaBean. However, we can also save the configuration setting of a JavaBean to persistent storage. 4. Portable As JavaBeans are built in Java, we can easily port them to any other platform that contains JRE. CU IDOL SELF LEARNING MATERIAL (SLM) 325
5. Lightweight JavaBeans are light weighted, I.e., we don't need to fulfill any special requirement to use it. Also, it is very easy to create them. However, it doesn't need a complex system to register components with JRE. The other advantages of JavaBeans include reusability, deployment, and customization that can be archived using JavaBeans. However, there are a few disadvantages of JavaBeans, which are its mutability, which makes it not working with Immutable Objects. Also, creating a setter and getter for each property in a class may lead to a boilerplate code. 15.6.2 Introspection At the core of Java Beans is introspection. This is the process of analyzing a Bean to determine its capabilities. This is an essential feature of the Java Beans API because it allows another application, such as a design tool, to obtain information about a component. Without introspection, the Java Beans technology could not operate. There are two ways in which the developer of a Bean can indicate which of its properties, events, and methods should be exposed. With the first method, simple naming conventions are used. These allow the introspection mechanisms to infer information about a Bean. In the second way, an additional class that extends the BeanInfo interface is provided that explicitly supplies this information. Both approaches are examined here. 15.6.3 Bound and Constrained Properties A Bean that has a bound property generates an event when the property is changed. The event is of type PropertyChangeEvent and is sent to objects that previously registered an interest in receiving such notifications. A class that handles this event must implement the PropertyChangeListener interface. A Bean that has a constrained property generates an event when an attempt is made to change its value. It also generates an event of type PropertyChangeEvent. It too is sent to objects that previously registered an interest in receiving such notifications. However, those other objects have the ability to veto the proposed change by throwing a PropertyVetoException. This capability allows a Bean to operate differently according to its run-time environment. A class that handles this event must implement the VetoableChangeListener interface. 15.6.4 Persistence Persistence is the ability to save the current state of a Bean, including the values of a Bean’s properties and instance variables, to nonvolatile storage and to retrieve them at a later time. The object serialization capabilities provided by the Java class libraries are used to provide persistence for Beans. CU IDOL SELF LEARNING MATERIAL (SLM) 326
The easiest way to serialize a Bean is to have it implement the java.io.Serializable interface, which is simply a marker interface. Implementing java.io.Serializable makes serialization automatic. Your Bean need take no other action. Automatic serialization can also be inherited. Therefore, if any superclass of a Bean implements java.io.Serializable, then automatic serialization is obtained. When using automatic serialization, you can selectively prevent a field from being saved through the use of the transient keyword. Thus, data members of a Bean specified as transient will not be serialized. If a Bean does not implement java.io.Serializable, you must provide serialization yourself, such as by implementing java.io.Externalizable. Otherwise, containers cannot save the configuration of your component. 15.6.5 Customizers A Bean developer can provide a customizer that helps another developer configure the Bean. A customizer can provide a step-by-step guide through the process that must be followed to use the component in a specific context. Online documentation can also be provided. A Bean developer has great flexibility to develop a customizer that can differentiate his or her product in the marketplace. Figure: 15.1 the interfaces in java 15.6.6 The Java Beans API The Java Beans functionality is provided by a set of classes and interfaces in the java.beans package. This section provides a brief overview of its contents. Figure 15.1 lists the interfaces CU IDOL SELF LEARNING MATERIAL (SLM) 327
in java.beans and provides a brief description of their functionality. Figure 15.2 lists the classes in java.beans. CU IDOL SELF LEARNING MATERIAL (SLM) 328
Figure 15.2: The classes in java beans 15.6.7 A Bean Example According to Java white paper, it is a reusable software component. A bean encapsulates many objects into one object so that we can access this object from multiple places. Moreover, it provides easy maintenance. //Employee.java package mypack; public class Employee implements java.io.Serializable{ private int id; private String name; public Employee(){} public void setId(int id){this.id=id;} public int getId(){return id;} public void setName(String name){this.name=name;} public String getName(){return name;} } To access the JavaBean class, we should use getter and setter methods. package mypack; public class Test{ public static void main(String args[]){ Employee e=new Employee();//object is created e.setName(\"Arjun\");//setting value to the object System.out.println(e.getName()); }} 15.7 SECURITY Most enterprise applications are designed to serve a large number of clients, and users are not necessarily equal in terms of their access rights. An administrator might require hooks into the configuration of the system, whereas unknown guests may be allowed a read-only view of data. CU IDOL SELF LEARNING MATERIAL (SLM) 329
It’s bad practice, however, to hardcode users’ access directly into your application’s logic. We shouldn’t have to rebuild an EJB each time a new employee comes into the company or an existing one is promoted to a new position with greater privileges. This technique is called role-based security. As we’ve seen before, embedding such rules within business logic tangles up concerns, so we’re best off enforcing these constraints at another level. The Java EE and EJB specifications provide a core set of security services that application developers can integrate declaratively and programmatically. These include: Authentication This is the process of validating the identity of a user who is trying to access a secured system. When authenticating, the application server verifies that the user actually exists in the system and has provided the correct credentials, such as a password. Authorization Once a user is authenticated in a system, he will want to interact with the application. Authorization involves determining whether a user is allowed to execute a certain action. Authorization can police a user’s access to subsystems, data, and business objects, or it can monitor more general behavior. Certain users, for example, may be allowed to update information, whereas others are allowed only to view the data. For web applications, maybe only certain users are permitted to access certain URLs. For EJB applications, the user can be authorized on a per-method basis. Although a small programmatic API is available for interacting with Java EE security services, users rarely have to write any code to secure their applications, because setting up security is usually a static, declarative process. Only session beans can be secured in EJB. This topic focuses on how to set up authentication and authorization for your session beans. 15.8 SUMMARY Servlets provide a component-based, platform-independent method for building Webbased applications, without the performance limitations of CGI programs. Servlets have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps. Java Servlets are programs that run on a Web or Application server and act as a middle layer between a requests coming from a Web browser or other HTTP client and databases or applications on the HTTP server. CU IDOL SELF LEARNING MATERIAL (SLM) 330
The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards. So, it is used for one-time initializations, just as with the init method of applets. HTTP protocol supports several request methods you can use while sending requests using HTTP or HTTPS protocol. GET is one of them. As the name suggests the GET method is to retrieve a page from the HTTP Server. You can identify a GET request by looking method attribute on the HTTP Request part. JavaBeans is a portable, platform-independent model written in Java Programming Language. Its components are referred to as beans. 15.9 KEYWORDS Servlet: A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. ... All servlets must implement the Servlet interface, which defines life-cycle methods. Get method: The get() method of Dictionary class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. Parameters: The method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched. POST: POST is a method that is supported by HTTP and. depicts that a web server accepts the data included in the body of the message. POST is often used by World Wide Web to send user generated data to the web server or when you upload file. Java beans:In computing based on the Java Platform, JavaBeans are classes that encapsulate many objects into a single object (the bean). They are serializable, have a zero-argument constructor, and allow access to properties using getter and setter methods. Persistence: Persistence simply means to Store Permanently. In JAVA we work with Objects and try to store Object's values into database (RDBMS mostly). JPA provides implementation for Object Relation Mapping (ORM) ,so that we can directly store Object into Database as a new Tuple. 15.10 LEARNING ACTIVITY 1. Discuss the topic java servlet. ________________________________________________________________________ __________________________________________________________________ CU IDOL SELF LEARNING MATERIAL (SLM) 331
2. Conduct a seminar on java beans. ________________________________________________________________________ __________________________________________________________________ 15.11 UNIT END QUESTIONS A. Descriptive Questions Short Questions: 1. What are Servlets? 2. When init () method of servlet gets called? 3. When doGet () method of servlet to be called? 4. When doPost () method of servlet to be called? 5. What are java beans? Long Questions: 1. What are the advantages of servlets over CGI? 2. What are the major tasks of servlets? 3. What the differences are between get and post method? 4. Explain java bean API. 5. Explain servlet life cycle. B. Multiple Choice Questions 1. How constructor can be used for a servlet? a. Initialization b. Constructor function c. Initialization and Constructor function d. Setup() method 2. Which of the following code is used to get an attribute in a HTTP Session object in servlets? a. Session.getAttribute(String name) b. Session.alterAttribute(String name) c. Session.updateAttribute(String name) d. Session.setAttribute(String name) CU IDOL SELF LEARNING MATERIAL (SLM) 332
3. Which method is used to get three-letter abbreviation for locale’s country in servlets? a. Request.getISO3Country() b. Locale.getISO3Country() c. Response.getISO3Country() d. Local.retrieveISO3Country() 4. How is the dynamic interception of requests and responses to transform the information done? a. Servlet container b. Servlet config c. Servlet context d. Servlet filter 5. When destroy() method of a filter is called? a. The destroy() method is called only once at the end of the life cycle of a filter b. The destroy() method is called after the filter has executed doFilter method c. The destroy() method is called only once at the begining of the life cycle of a filter d. The destroyer() method is called after the filter has executed 15.12 REFERENCES References Wilson, M. Jeff (November 10, 2000). \"Get smart with proxies and RMI\". Taylor, Ian J (2005). From P2P to Web Services and Grids : Peers in a Client/Server World. Computer Communications and Networks. London: Springer-Verlag Hunter, J. and W. Crawford (1998) Java Servlet Programming, O'Reilly and Associates , Sebastopol, CA. Textbooks Stephen T. Albin. The Art of Software Architecture: Design Methods and Techniques, Wiley 2003 Eric Giguère, C. Enrique Ortiz . Mobile Information Device Profile for Java 2 Micro Edition: Professional Developer's Guide, Willey 2001 Williamson, A.R. (1998) Java Servlets by Example, Manning Publications. CU IDOL SELF LEARNING MATERIAL (SLM) 333
Website https://www.mygreatlearning.com https://www.w3schools.com https://beginnersbook.co CU IDOL SELF LEARNING MATERIAL (SLM) 334
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334