Document Details

SuccessfulByzantineArt5967

Uploaded by SuccessfulByzantineArt5967

Tags

java programming servlet web application development enterprise java

Summary

This document provides an overview of Servlets in Java, covering what they are, advantages, and interfaces from the Java Servlet API package.

Full Transcript

**Servlet** **Servlet** technology is used to create web application (resides at server side and generates dynamic web page). **Servlet** technology is robust and scalable because of java language. Before Servlet, CGI (Common Gateway Interface) scripting language was popular as a server-side progr...

**Servlet** **Servlet** technology is used to create web application (resides at server side and generates dynamic web page). **Servlet** technology is robust and scalable because of java language. Before Servlet, CGI (Common Gateway Interface) scripting language was popular as a server-side programming language. But there was many disadvantages of this technology. We have discussed these disadvantages below. There are many interfaces and classes in the servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse etc. **What is a Servlet?** Servlet can be described in many ways, depending on the context. - Servlet is a technology i.e. used to create web application. - Servlet is an API that provides many interfaces and classes including documentations. - Servlet is an interface that must be implemented for creating any servlet. - Servlet is a class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests. - Servlet is a web component that is deployed on the server to create dynamic web page C:\\Documents and Settings\\Administrator\\Desktop\\Learn Servlet Tutorial - javatpoint\_files\\response.JPG **Advantages of Servlet:** 1. **better performance:** because it creates a thread for each request not process. 2. **Portability:** because it uses java language. 3. **Robust:** Servlets are managed by JVM so we don\'t need to worry about memory leak, garbage collection etc. 4. **Secure:** because it uses java language.. Servlet API =========== The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api. The **javax.servlet** package contains many interfaces and classes that are used by the servlet or web container. These are not specific to any protocol. The **javax.servlet.http** package contains interfaces and classes that are responsible for http requests only. Let\'s see what are the interfaces of javax.servlet package. ### Interfaces in javax.servlet package There are many interfaces in javax.servlet package. They are as follows: 1. Servlet 2. ServletRequest 3. ServletResponse 4. RequestDispatcher 5. ServletConfig 6. ServletContext 7. SingleThreadModel 8. Filter 9. FilterConfig 10. FilterChain 11. ServletRequestListener 12. ServletRequestAttributeListener 13. ServletContextListener 14. ServletContextAttributeListener ### Classes in javax.servlet package There are many classes in javax.servlet package. They are as follows: 1. GenericServlet 2. ServletInputStream 3. ServletOutputStream 4. ServletRequestWrapper 5. ServletResponseWrapper 6. ServletRequestEvent 7. ServletContextEvent 8. ServletRequestAttributeEvent 9. ServletContextAttributeEvent 10. ServletException 11. UnavailableException ### Interfaces in javax.servlet.http package There are many interfaces in javax.servlet.http package. They are as follows: 1. HttpServletRequest 2. HttpServletResponse 3. HttpSession 4. HttpSessionListener 5. HttpSessionAttributeListener 6. HttpSessionBindingListener 7. HttpSessionActivationListener 8. HttpSessionContext (deprecated now) ### Classes in javax.servlet.http package There are many classes in javax.servlet.http package. They are as follows: 1. HttpServlet 2. Cookie 3. HttpServletRequestWrapper 4. HttpServletResponseWrapper 5. HttpSessionEvent 6. HttpSessionBindingEvent 7. HttpUtils (deprecated now) Life Cycle of a Servlet (Servlet Life Cycle) ============================================ The web container maintains the life cycle of a servlet instance. Let\'s see the life cycle of the servlet: 1. Servlet class is loaded. 2. Servlet instance is created. 3. init method is invoked. 4. service method is invoked. 5. destroy method is invoked ![C:\\Documents and Settings\\Administrator\\Desktop\\Life cycle of a servlet - javatpoint\_files\\servletlife.jpg](media/image2.jpeg) As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet is in new state if servlet instance is created. After invoking the init() method, Servlet comes in the ready state. In the ready state, servlet performs all the tasks. When the web container invokes the destroy() method, it shifts to the end state. ### 1) Servlet class is loaded The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is received by the web container. ### 2) Servlet instance is created The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle. ### 3) init method is invoked --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The web container calls the init method only once after creating the servlet instance. The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below: --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1. public void init(ServletConfig config) throws ServletException   ### 4) service method is invoked The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given below: 1. public void service(ServletRequest request, ServletResponse response)    2.   throws ServletException, IOException   The doGet() Method: 3. public void doGet(HttpServletRequest request, HttpServletResponse response)    The doPost() Method: 4. public void doPost(HttpServletRequest request, HttpServletResponse response)    ### 5) destroy method is invoked The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy method of the Servlet interface is given below: 1. public void destroy()   **Steps to Creating a Simple Servlet:** Following are the steps to create web application using servlet in Netbeans. 1. Go to the file menu 2. Select new project 3. Select categories as java web 4. Provide project name and click on next button 5. Select framework which you want to work and click on finish button. **Servlet Life Cycle Code:** import java.io.IOException; import java.io.PrintWriter; import javax.servlet.\*; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; \@WebServlet(urlPatterns = {\"/ServletLifeCycle\"}) public class ServletLifeCycle extends HttpServlet { public ServletLifeCycle() { System.out.println(\"Am from default constructor\"); } public void init(ServletConfig config) { System.out.println(\"Am from Init method\...!\"); } public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { res.setContentType(\"text/html\"); PrintWriter pw = res.getWriter(); pw.println(\"I am from doGet method\"); pw.close(); } public void destroy() { System.out.println(\"Am from Destroy methods\"); } } Servlets Architecture --------------------- The following diagram shows the position of Servlets in a Web Application. C:\\Documents and Settings\\Administrator\\Desktop\\Servlets Overview\_files\\servlet-arch.jpg 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 clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks. Servlets Packages ----------------- Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet specification. Servlets can be created using the **javax.servlet** and **javax.servlet.http** packages, which are a standard part of the Java\'s enterprise edition, an expanded version of the Java class library that supports large-scale development projects. ### What is web application? A web application is an application accessible from the web. A web application is composed of web components like Servlet, JSP, Filter etc. and other components such as HTML. The web components typically execute in Web Server and respond to HTTP request. ### CGI(Commmon Gateway Interface) CGI technology enables the web server to call an external program and pass HTTP request information to the external program to process the request. For each request, it starts a new process. ![C:\\Documents and Settings\\Administrator\\Desktop\\Learn Servlet Tutorial - javatpoint\_files\\cgi.JPG](media/image4.jpeg) ### Disadvantages of CGI There are many problems in CGI technology: 1. If number of clients increases, it takes more time for sending response. 2. For each request, it starts a process and Web server is limited to start processes. 3. It uses platform dependent language e.g. C, C++, perl. ### ### ### ### Advantage of Servlet C:\\Documents and Settings\\Administrator\\Desktop\\Learn Servlet Tutorial - javatpoint\_files\\servlet.JPG There are many advantages of servlet over CGI. The web container creates threads for handling the multiple requests to the servlet. Threads have a lot of benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low. The basic benefits of servlet are as follows: 5. **better performance:** because it creates a thread for each request not process. 6. **Portability:** because it uses java language. 7. **Robust:** Servlets are managed by JVM so we don\'t need to worry about memory leak, garbage collection etc. 8. **Secure:** because it uses java language.. Website ======= Website is a collection of related web pages that may contain text, images, audio and video. The first page of a website is called home page. Each website has specific internet address (URL) that you need to enter in your browser to access a website. Website is hosted on one or more servers and can be accessed by visiting its homepage using a computer network. A website is managed by its owner that can be an individual, company or an organization. ![C:\\Documents and Settings\\Administrator\\Desktop\\Website Static vs Dynamic - javatpoint\_files\\website-static-vs-dynamic1.png](media/image6.png) A website can be of two types: - Static Website - Dynamic Website **Static website** Static website is the basic type of website that is easy to create. You don\'t need web programming and database design to create a static website. Its web pages are coded in HTML. The codes are fixed for each page so the information contained in the page does not change and it looks like a printed page. C:\\Documents and Settings\\Administrator\\Desktop\\Website Static vs Dynamic - javatpoint\_files\\website-static-vs-dynamic2.png Dynamic website --------------- Dynamic website is a collection of dynamic web pages whose content changes dynamically. It accesses content from a database or Content Management System (CMS). Therefore, when you alter or update the content of the database, the content of the website is also altered or updated. Dynamic website uses client-side scripting or server-side scripting, or both to generate dynamic content. Client side scripting generates content at the client computer on the basis of user input. The web browser downloads the web page from the server and processes the code within the page to render information to the user. In server side scripting, the software runs on the server and processing is completed in the server then plain pages are sent to the user. ![C:\\Documents and Settings\\Administrator\\Desktop\\Website Static vs Dynamic - javatpoint\_files\\website-static-vs-dynamic3.png](media/image8.png) **Static vs Dynamic website** **Static Website** **Dynamic Website** ------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------- Prebuilt content is same every time the page is loaded. Content is generated quickly and changes regularly. It uses the **HTML** code for developing a website. It uses the server side languages such as **PHP,SERVLET, JSP, and ASP.NET** etc. for developing a website. It sends exactly the same response for every request. It may generate different HTML for each of the request. The content is only changes when someone publishes and updates the file (sends it to the web server). The page contains \"server-side\" code it allows the server to generate the unique content when the page is loaded. Flexibility is the main advantage of static website. Content Management System (CMS) is the main advantage of dynamic website. HTTP (Hyper Text Transfer Protocol) =================================== The Hypertext Transfer Protocol (HTTP) is application-level protocol for collaborative, distributed, hypermedia information systems. It is the data communication protocol used to establish communication between client and server. HTTP is TCP/IP based communication protocol, which is used to deliver the data like image files, query results, HTML files etc on the World Wide Web (WWW) with the default port is TCP 80. It provides the standardized way for computers to communicate with each other. C:\\Documents and Settings\\Administrator\\Desktop\\HTTP - javatpoint\_files\\servlet-http4.png **The Basic Characteristics of HTTP (Hyper Text Transfer Protocol):** - It is the protocol that allows web servers and browsers to exchange data over the web. - It is a request response protocol. - It uses the reliable TCP connections by default on TCP port 80. - It is stateless means each request is considered as the new request. In other words, server doesn\'t recognize the user by default. **The Basic Features of HTTP (Hyper Text Transfer Protocol):** There are three fundamental features that make the HTTP a simple and powerful protocol used for communication: - **HTTP is media independent:** It refers to any type of media content can be sent by HTTP as long as both the server and the client can handle the data content. - **HTTP is connectionless:** It is a connectionless approach in which HTTP client i.e., a browser initiates the HTTP request and after the request is sends the client disconnects from server and waits for the response. - **HTTP is stateless:** The client and server are aware of each other during a current request only. Afterwards, both of them forget each other. Due to the stateless nature of protocol, neither the client nor the server can retain the information about different request across the web pages. **The Basic Architecture of HTTP (Hyper Text Transfer Protocol):** The below diagram represents the basic architecture of web application and depicts where HTTP stands: ![C:\\Documents and Settings\\Administrator\\Desktop\\HTTP - javatpoint\_files\\servlet-http5.png](media/image10.png) HTTP is request/response protocol which is based on client/server based architecture. In this web browser, search engines, etc behaves as a HTTP clients, and the Web server like Servlet behaves as a server. **HTTP Requests** The request sends by the computer to a web server that contains all sorts of potentially interesting information is known as HTTP requests. The HTTP client sends the request to the server in the form of request message which includes following information: - The Request-line - The analysis of source IP address, proxy and port - The analysis of destination IP address, protocol, port and host - The Requested URI (Uniform Resource Identifier) - The Request method and Content - The User-Agent header - The Connection control header - The Cache control header The HTTP request method indicates the method to be performed on the resource identified by the **Requested URI (Uniform Resource Identifier)**. This method is case-sensitive and should be used in uppercase. The HTTP request methods are: **HTTP Request** **Description** ------------------ ----------------------------------------------------------------------------------------------------------------- **GET** Asks to get the resource at the requested URL. **POST** Asks the server to accept the body info attached. It is like GET request with extra info sent with the request. **HEAD** Asks for only the header part of whatever a GET would return. Just like GET but with no body. **TRACE** Asks for the loopback of the request message, for testing or troubleshooting. **PUT** Says to put the enclosed info (the body) at the requested URL. **DELETE** Says to delete the resource at the requested URL. **OPTIONS** Asks for a list of the HTTP methods to which the thing at the request URL can respond **Get vs. Post** There are many differences between the Get and Post request. Let\'s see these differences: **GET** **POST** ------------------------------------------------------------------------- --------------------------------------------------------------------------------------------- 1\) In case of Get request, only **limited amount of data** can be sent In case of post request, **large amount of data** can be sent because data is sent in body. because data is sent in header. 2\) Get request is **not secured** because data is exposed in URL bar. Post request is **secured** because data is not exposed in URL bar. 3\) Get request **can be bookmarked.** Post request **cannot be bookmarked.** 4\) Get request is **idempotent**. It means second request will be Post request is **non-idempotent.** ignored until response of first request is delivered 5\) Get request is **more efficient** and used more than Post. Post request is **less efficient** and used less than get. **GET and POST** Two common methods for the request-response between a server and client are: - **GET**- It requests the data from a specified resource - **POST**- It submits the processed data to a specified resource **Anatomy of Get Request** The query string (name/value pairs) is sent inside the URL of a GET request: 1. GET /RegisterDao.jsp?name1=value1&name2=value2   As we know that data is sent in request header in case of get request. It is the default request type. Let\'s see what information is sent to the server. C:\\Documents and Settings\\Administrator\\Desktop\\Get vs Post - javatpoint\_files\\servlet-http-requests6.png Some other features of GET requests are: - It remains in the browser history - It can be bookmarked - It can be cached - It have length restrictions - It should never be used when dealing with sensitive data - It should only be used for retrieving the data **Anatomy of Post Request** The query string (name/value pairs) is sent in HTTP message body for a POST request: 1. POST/RegisterDao.jsp HTTP/1.1   2. Host: www. javatpoint.com   3. name1=value1&name2=value2   As we know, in case of post request original data is sent in message body. Let\'s see how information is passed to the server in case of post request. ![C:\\Documents and Settings\\Administrator\\Desktop\\Get vs Post - javatpoint\_files\\servlet-http-requests7.png](media/image12.png)Some other features of POST requests are: - This requests cannot be bookmarked - This requests have no restrictions on length of data - This requests are never cached - This requests do not remains in the browser history Servlet Container ================= It provides the runtime environment for JavaEE (j2ee) applications. The client/user can request only a static WebPages from the server. If the user wants to read the web pages as per input then the servlet container is used in java. The servlet container is used in java for dynamically generate the web pages on the server side. Therefore the servlet container is the part of a web server that interacts with the servlet for handling the dynamic web pages from the client. C:\\Documents and Settings\\Administrator\\Desktop\\Container - javatpoint\_files\\servlet-container1.png **Servlet Container States** The servlet container is the part of web server which can be run in a separate process. We can classify the servlet container states in three types: - **Standalone:** It is typical Java-based servers in which the servlet container and the web servers are the integral part of a single program. For example:- Tomcat running by itself - **In-process:** It is separated from the web server, because a different program is runs within the address space of the main server as a plug-in. For example:- Tomcat running inside the JBoss. - **Out-of-process:** The web server and servlet container are different programs which are run in a different process. For performing the communications between them, web server uses the plug-in provided by the servlet container. **The Servlet Container performs many operations that are given below:** - Life Cycle Management - Multithreaded support - Object Pooling - Security etc. **Server: Web vs. Application** Server is a device or a computer program that accepts and responds to the request made by other program, known as client. It is used to manage the network resources and for running the program or software that provides services. There are two types of servers: 1. Web Server 2. Application Server **Web Server** Web server contains only web or servlet container. It can be used for servlet, jsp, struts, jsf etc. It can\'t be used for EJB. It is a computer where the web content can be stored. In general web server can be used to host the web sites but there also used some other web servers also such as FTP, email, storage, gaming etc. Examples of Web Servers are: **Apache Tomcat** and **Resin**. **Web Server Working** It can respond to the client request in either of the following two possible ways: - Generating response by using the script and communicating with database. - Sending file to the client associated with the requested URL. The block diagram representation of Web Server is shown below: ![C:\\Documents and Settings\\Administrator\\Desktop\\Server Web vs Application - javatpoint\_files\\server-web-vs-application1.png](media/image14.png) **Important points** - If the requested web page at the client side is not found, then web server will sends the HTTP response: Error 404 Not found. - When the web server searching the requested page if requested page is found then it will send to the client with an HTTP response. - If the client requests some other resources then web server will contact to application server and data is store for constructing the HTTP response. **Application Server** Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf, ejb etc. It is a component based product that lies in the middle-tier of a server centric architecture. It provides the middleware services for state maintenance and security, along with persistence and data access. It is a type of server designed to install, operate and host associated services and applications for the IT services, end users and organizations. The block diagram representation of Application Server is shown below: C:\\Documents and Settings\\Administrator\\Desktop\\Server Web vs Application - javatpoint\_files\\server-web-vs-application2.png The Example of Application Servers are: 1. **JBoss:** Open-source server from JBoss community. 2. **Glassfish:** Provided by Sun Microsystem. Now acquired by Oracle. 3. **Weblogic:** Provided by Oracle. It more secured. 4. **Websphere:** Provided by IBM. Servlet Interface ================= 1. [Servlet Interface](https://www.javatpoint.com/Servlet-interface) 2. [Methods of Servlet interface](https://www.javatpoint.com/Servlet-interface#servletmethods) **Servlet interface** provides common behaviour to all the servlets. Servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life cycle methods. ### Methods of Servlet interface There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods of servlet. These are invoked by the web container. **Method** **Description** -------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------- **public void init(ServletConfig config)** initializes the servlet. It is the life cycle method of servlet and invoked by the web container only once. **public void service(ServletRequest request,ServletResponse response)** provides response for the incoming request. It is invoked at each request by the web container. **public void destroy()** is invoked only once and indicates that servlet is being destroyed. **public ServletConfig getServletConfig()** returns the object of ServletConfig. **public String getServletInfo()** returns information about servlet such as writer, copyright, version etc. ### Servlet Example by implementing Servlet interface import java.io.\*;   import javax.servlet.\*;      public class First implements Servlet {   ServletConfig config=null;      public void init(ServletConfig config) {   this.config=config;   System.out.println(\"servlet is initialized\");   }      public void service(ServletRequest req,ServletResponse res)   throws IOException,ServletException {      res.setContentType(\"text/html\");      PrintWriter out=res.getWriter();   out.print(\"\\\");   out.print(\"\hello simple servlet\\");   out.print(\"\\\");      }   public void destroy(){System.out.println(\"servlet is destroyed\");}   public ServletConfig getServletConfig(){return config;}   public String getServletInfo(){return \"copyright 2007-1010\";}  }  GenericServlet class ==================== **GenericServlet** class implements **Servlet**, **ServletConfig** and **Serializable** interfaces. It provides the implementation of all the methods of these interfaces except the service method. GenericServlet class can handle any type of request so it is protocol-independent. You may create a generic servlet by inheriting the GenericServlet class and providing the implementation of the service method. ### Methods of GenericServlet class There are many methods in GenericServlet class. They are as follows: 1. **public void init(ServletConfig config)** is used to initialize the servlet. 2. **public abstract void service(ServletRequest request, ServletResponse response)** provides service for the incoming request. It is invoked at each time when user requests for a servlet. 3. **public void destroy()** is invoked only once throughout the life cycle and indicates that servlet is being destroyed. 4. **public ServletConfig getServletConfig()** returns the object of ServletConfig. 5. **public String getServletInfo()** returns information about servlet such as writer, copyright, version etc. 6. **public void init()** it is a convenient method for the servlet programmers, now there is no need to call super.init(config) 7. **public ServletContext getServletContext()** returns the object of ServletContext. 8. **public String getInitParameter(String name)** returns the parameter value for the given parameter name. 9. **public Enumeration getInitParameterNames()** returns all the parameters defined in the web.xml file. 10. **public String getServletName()** returns the name of the servlet object. 11. **public void log(String msg)** writes the given message in the servlet log file. 12. **public void log(String msg,Throwable t)** writes the explanatory message in the servlet log file and a stack trace. ### Servlet Example by inheriting the GenericServlet class import java.io.\*;   import javax.servlet.\*;      public class First extends GenericServlet {   public void service(ServletRequest req,ServletResponse res)   throws IOException,ServletException {      res.setContentType(\"text/html\");      PrintWriter out=res.getWriter();   out.print(\"\\\");   out.print(\"\hello generic servlet\\");   out.print(\"\\\");   }  }  HttpServlet class ================= ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http specific methods such as doGet, doPost, doHead, doTrace etc. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### Methods of HttpServlet class There are many methods in HttpServlet class. They are as follows: 1. **public void service(ServletRequest req,ServletResponse res)** dispatches the request to the protected service method by converting the request and response object into http type. 2. **protected void service(HttpServletRequest req, HttpServletResponse res)** receives the request from the service method, and dispatches the request to the doXXX() method depending on the incoming http request type. 3. **protected void doGet(HttpServletRequest req, HttpServletResponse res)** handles the GET request. It is invoked by the web container. 4. **protected void doPost(HttpServletRequest req, HttpServletResponse res)** handles the POST request. It is invoked by the web container. 5. **protected void doHead(HttpServletRequest req, HttpServletResponse res)** handles the HEAD request. It is invoked by the web container. 6. **protected void doOptions(HttpServletRequest req, HttpServletResponse res)** handles the OPTIONS request. It is invoked by the web container. 7. **protected void doPut(HttpServletRequest req, HttpServletResponse res)** handles the PUT request. It is invoked by the web container. 8. **protected void doTrace(HttpServletRequest req, HttpServletResponse res)** handles the TRACE request. It is invoked by the web container. 9. **protected void doDelete(HttpServletRequest req, HttpServletResponse res)** handles the DELETE request. It is invoked by the web container. 10. **protected long getLastModified(HttpServletRequest req)** returns the time when HttpServletRequest was last modified since midnight January 1, 1970 GMT. import java.io.\*; import javax.servlet.\*; import javax.servlet.http.\*; // Extend HttpServlet class public class HelloWorld extends HttpServlet { private String message; public void init() throws ServletException { // Do required initialization message = \"Hello World\"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType(\"text/html\"); // Actual logic goes here. PrintWriter out = response.getWriter(); out.println(\"\\" + message + \"\\"); } public void destroy() { // do nothing. } } ServletConfig Interface ======================= An object of ServletConfig is created by the web container for each servlet. This object can be used to get configuration information from web.xml file. If the configuration information is modified from the web.xml file, we don\'t need to change the servlet. So it is easier to manage the web application if any specific content is modified from time to time. ### Advantage of ServletConfig The core advantage of ServletConfig is that you don\'t need to edit the servlet file if information is modified from the web.xml file. ### Methods of ServletConfig interface 1. **public String getInitParameter(String name):**Returns the parameter value for the specified parameter name. 2. **public Enumeration getInitParameterNames():**Returns an enumeration of all the initialization parameter names. 3. **public String getServletName():**Returns the name of the servlet. 4. **public ServletContext getServletContext():**Returns an object of ServletContext. ### How to get the object of ServletConfig 1. **getServletConfig() method** of Servlet interface returns the object of ServletConfig. #### Syntax of getServletConfig() method 1. public ServletConfig getServletConfig();   ### Example of getServletConfig() method 1. ServletConfig config=getServletConfig();   2. //Now we can call the methods of ServletConfig interface   ### Syntax to provide the initialization parameter for a servlet The init-param sub-element of servlet is used to specify the initialization parameter for a servlet. 1. \   2.   \   3.     \...\...   4.        5.     \   6.       \parametername\   7.       \parametervalue\   8.     \   9.     \...\...   10.   \   11. \   ### Example of ServletConfig to get initialization parameter In this example, we are getting the one initialization parameter from the web.xml file and printing this information in the servlet. **DemoServlet.java** **web.xml** ServletContext Interface ======================== An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application. If any information is shared to many servlet, it is better to provide it from the web.xml file using the **\** element. ### Advantage of ServletContext **Easy to maintain** if any information is shared to all the servlet, it is better to make it available for all the servlet. We provide this information from the web.xml file, so if the information is changed, we don\'t need to modify the servlet. Thus it removes maintenance problem. ### Usage of ServletContext Interface There can be a lot of usage of ServletContext object. Some of them are as follows: 1. The object of ServletContext provides an interface between the container and servlet. 2. The ServletContext object can be used to get configuration information from the web.xml file. 3. The ServletContext object can be used to set, get or remove attribute from the web.xml file. 4. The ServletContext object can be used to provide inter-application communication. ![C:\\Documents and Settings\\Administrator\\Desktop\\ServletContext Interface in Servlet - javatpoint\_files\\servletcontext.JPG](media/image16.jpeg) ### Commonly used methods of ServletContext interface +-----------------------------------------------------------------------+ | There is given some commonly used methods of ServletContext | | interface. | | | | 1. **public String getInitParameter(String name):**Returns the | | parameter value for the specified parameter name. | | | | 2. **public Enumeration getInitParameterNames():**Returns the names | | of the context\'s initialization parameters. | | | | 3. **public void setAttribute(String name,Object object):**sets the | | given object in the application scope. | | | | 4. **public Object getAttribute(String name):**Returns the attribute | | for the specified name. | | | | 5. **public Enumeration getInitParameterNames():**Returns the names | | of the context\'s initialization parameters as an Enumeration of | | String objects. | | | | 6. **public void removeAttribute(String name):**Removes the | | attribute with the given name from the servlet context. | +-----------------------------------------------------------------------+ ### How to get the object of ServletContext interface 1. **getServletContext() method** of ServletConfig interface returns the object of ServletContext. 2. **getServletContext() method** of GenericServlet class returns the object of ServletContext. #### Syntax of getServletContext() method #### Example of getServletContext() method ### Syntax to provide the initialization parameter in Context scope ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The **context-param** element, subelement of web-app, is used to define the initialization parameter in the application scope. The param-name and param-value are the sub-elements of the context-param. The param-name element defines parameter name and and param-value defines its value. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### Example of ServletContext to get the initialization parameter ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- In this example, we are getting the initialization parameter from the web.xml file and printing the value of the initialization parameter. Notice that the object of ServletContext represents the application scope. So if we change the value of the parameter from the web.xml file, all the servlet classes will get the changed value. So we don\'t need to modify the servlet. So it is better to have the common information for most of the servlets in the web.xml file by context-param element. Let\'s see the simple example: ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- **DemoServlet.java** **web.xml** **Deployment Descriptor:** **Web.xml file:** **Servlet annotation:** Annotation represents the meta data. If you use annotation , deployment descriptor(web.xml file) is not required. **package** *net.javatutorial.tutorials*; **import** *java.io.IOException*; **import** *javax.servlet.ServletException*; **import** *javax.servlet.annotation.WebServlet*; **import** *javax.servlet.http.HttpServlet*; **import** *javax.servlet.http.HttpServletRequest*; **import** *javax.servlet.http.HttpServletResponse*; \@WebServlet(name = \"simpleServlet\", urlPatterns = { \"/hello\" }) **public** **class** ServletWithAnnotations **extends** HttpServlet { **private** **static** **final** **long** serialVersionUID = -3462096228274971485L; \@Override **protected** **void** doGet(HttpServletRequest reqest, HttpServletResponse response) **throws** ServletException, IOException { response.getWriter().println(\"Hello World!\"); } }   **JDBC** What is JDBC? ------------- JDBC stands for **J**ava **D**ata**b**ase **C**onnectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases. The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with database usage. - Making a connection to a database. - Creating SQL or MySQL statements. - Executing SQL or MySQL queries in the database. - Viewing & Modifying the resulting records. Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable access to an underlying database. Java can be used to write different types of executables, such as − - Java Applications - Java Applets - Java Servlets - Java ServerPages (JSPs) - Enterprise JavaBeans (EJBs). All of these different executables are able to use a JDBC driver to access a database, and take advantage of the stored data. Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers to connect with the database. C:\\Documents and Settings\\Administrator\\Desktop\\Java JDBC Tutorial - javatpoint\_files\\jdbc.png ### Why use JDBC Before JDBC, ODBC API was the database API to connect and execute query with the database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language). What is API ----------- API (Application programming interface) is a document that contains description of all the features of a product or software. It represents classes and interfaces that software programs can follow to communicate with each other. An API can be created for applications, libraries, operating systems, etc JDBC Architecture ----------------- The JDBC API supports both two-tier and three-tier processing models for database access but in general, JDBC Architecture consists of two layers − - **JDBC API:** This provides the application-to-JDBC Manager connection. - **JDBC Driver API:** This supports the JDBC Manager-to-Driver Connection. The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. Following is the architectural diagram, which shows the location of the driver manager with respect to the JDBC drivers and the Java application − ![C:\\Documents and Settings\\Administrator\\Desktop\\JDBC 4.0 Introduction\_files\\jdbc-architecture.jpg](media/image18.jpeg) Common JDBC Components ---------------------- The JDBC API provides the following interfaces and classes − - **DriverManager:** This class manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication sub protocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection. - **Driver:** This interface handles the communications with the database server. You will interact directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages objects of this type. It also abstracts the details associated with working with Driver objects. - **Connection:** This interface with all methods for contacting a database. The connection object represents communication context, i.e., all communication with database is through connection object only. - **Statement:** You use objects created from this interface to submit the SQL statements to the database. Some derived interfaces accept parameters in addition to executing stored procedures. - **ResultSet:** These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data. - **SQLException:** This class handles any errors that occur in a database application. **Types of Drivers** What is JDBC 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. C:\\Documents and Settings\\Administrator\\Desktop\\JDBC - Driver Types\_files\\driver-type1.jpg 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 are 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. ![C:\\Documents and Settings\\Administrator\\Desktop\\JDBC - Driver Types\_files\\driver-type2.jpg](media/image20.jpeg) 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 access databases. The JDBC clients use standard network sockets to communicate with a 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. C:\\Documents and Settings\\Administrator\\Desktop\\JDBC - Driver Types\_files\\driver-type3.jpg 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 communicates directly with the 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. ![C:\\Documents and Settings\\Administrator\\Desktop\\JDBC - Driver Types\_files\\driver-type4.jpg](media/image22.jpeg) 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. Database Connectivity Steps: **5 Steps to connect to the database in java** +-----------------------------------------------------------------------+ | There are 5 steps to connect any java application with the database | | in java using JDBC. They are as follows: | | | | - Register the driver class | | | | - Creating connection | | | | - Creating statement | | | | - Executing queries | | | | - Closing connection | +-----------------------------------------------------------------------+ ### 1) Register the driver class ------------------------------------------------------------------------------------------------------------------------------------- The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class. ------------------------------------------------------------------------------------------------------------------------------------- ### Syntax of forName() method 1. public static void forName(String className)throws ClassNotFoundException   ### Example to register the OracleDriver class 1. Class.forName(\"oracle.jdbc.driver.OracleDriver\");   ### 2) Create the connection object ------------------------------------------------------------------------------------------------------ The getConnection() method of DriverManager class is used to establish connection with the database. ------------------------------------------------------------------------------------------------------ ### Syntax of getConnection() method 1. 1) public static Connection getConnection(String url)throws SQLException   2. 2) public static Connection getConnection(String url,String name,String password)   3. throws SQLException   ### Example to establish connection with the Oracle database 1. Connection con=DriverManager.getConnection(   2. \"jdbc:oracle:thin:\@localhost:1521:xe\",\"system\",\"password\");   ### 3) Create the Statement object ---------------------------------------------------------------------------------------------------------------------------------------------------------------- The createStatement() method of Connection interface is used to create statement. The object of statement is responsible to execute queries with the database. ---------------------------------------------------------------------------------------------------------------------------------------------------------------- ### Syntax of createStatement() method 1. public Statement createStatement()throws SQLException   ### Example to create the statement object 1. Statement stmt=con.createStatement();   ### 4) Execute the query ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the object of ResultSet that can be used to get all the records of a table. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### Syntax of executeQuery() method 1. public ResultSet executeQuery(String sql)throws SQLException   ### Example to execute query 1. ResultSet rs=stmt.executeQuery(\"select \* from emp\");   2.    3. while(rs.next()){   4. System.out.println(rs.getInt(1)+\" \"+rs.getString(2));   5. }   ### 5) Close the connection object ---------------------------------------------------------------------------------------------------------------------------------------------------------------- By closing connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection. ---------------------------------------------------------------------------------------------------------------------------------------------------------------- ### Syntax of close() method 1. public void close()throws SQLException   ### Example to close connection 1. con.close();   Example to connect to the Oracle database in java ================================================= +-----------------------------------------------------------------------+ | For connecting java application with the oracle database, you need to | | follow 5 steps to perform database connectivity. In this example we | | are using Oracle10g as the database. So we need to know following | | information for the oracle database: | | | | 1. **Driver class:** The driver class for the oracle database is | | **oracle.jdbc.driver.OracleDriver**. | | | | 2. **Connection URL:** The connection URL for the oracle10G database | | is **jdbc:oracle:thin:\@localhost:1521:xe** where jdbc is the | | API, oracle is the database, thin is the driver, localhost is the | | server name on which oracle is running, we may also use IP | | address, 1521 is the port number and XE is the Oracle service | | name. You may get all these information from the tnsnames.ora | | file. | | | | 3. **Username:** The default username for the oracle database is | | **system**. | | | | 4. **Password:** Password is given by the user at the time of | | installing the oracle database. | +-----------------------------------------------------------------------+ ------------------------------------------------- Let\'s first create a table in oracle database. ------------------------------------------------- 1. create table emp(id number(10),name varchar2(40),age number(3));   ### Example to Connect Java Application with Oracle database In this example, system is the username and oracle is the password of the Oracle database. import java.sql.\*;   class OracleCon{   public static void main(String args\[\]) {   try {   //step1 load the driver class   Class.forName(\"oracle.jdbc.driver.OracleDriver\");   //step2 create  the connection object   Connection con=DriverManager.getConnection(   \"jdbc:oracle:thin:\@localhost:1521:xe\",\"system\",\"oracle\");      //step3 create the statement object   Statement stmt=con.createStatement();      //step4 execute query   ResultSet rs=stmt.executeQuery(\"select \* from emp\");   while(rs.next())   System.out.println(rs.getInt(1)+\"  \"+rs.getString(2)+\"  \"+rs.getString(3));      //step5 close the connection object   con.close();      } catch(Exception e) {  System.out.println(e); }      }   }   Example to connect to the mysql database in java ================================================ For connecting java application with the mysql database, you need to follow 5 steps to perform database connectivity. In this example we are using MySql as the database. So we need to know following informations for the mysql database: 1. **Driver class:** The driver class for the mysql database is **com.mysql.jdbc.Driver**. 2. **Connection URL:** The connection URL for the mysql database is **jdbc:mysql://localhost:3306/sonoo** where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running, we may also use IP address, 3306 is the port number and sonoo is the database name. We may use any database, in such case, you need to replace the sonoo with your database name. 3. **Username:** The default username for the mysql database is **root**. 4. **Password:** Password is given by the user at the time of installing the mysql database. In this example, we are going to use root as the password. Let\'s first create a table in the mysql database, but before creating table, we need to create database first. 1. create database sonoo;   2. use sonoo;   3. create table emp(id int(10),name varchar(40),age int(3));   ### Example to Connect Java Application with mysql database In this example, sonoo is the database name, root is the username and password. import java.sql.\*;   class MysqlCon {   public static void main(String args\[\]) {   try {   Class.forName(\"com.mysql.jdbc.Driver\");   Connection con=DriverManager.getConnection(   \"jdbc:mysql://localhost:3306/sonoo\",\"root\",\"root\");   //here sonoo is database name, root is username and password   Statement stmt=con.createStatement();   ResultSet rs=stmt.executeQuery(\"select \* from emp\");   while(rs.next())   System.out.println(rs.getInt(1)+\"  \"+rs.getString(2)+\"  \"+rs.getString(3));   con.close();   } catch(Exception e) {  System.out.println(e); }   }   }   DriverManager class =================== The DriverManager class acts as an interface between user and drivers. It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. The DriverManager class maintains a list of Driver classes that have registered themselves by calling the method DriverManager.registerDriver(). ### Useful methods of DriverManager class **Method** **Description** -------------------------------------------------------------- -------------------------------------------------------------------------------------------- 1\) public static void registerDriver(Driver driver): is used to register the given driver with DriverManager. 2\) public static void deregisterDriver(Driver driver): is used to deregister the given driver (drop the driver from the list) with DriverManager. 3\) public static Connection getConnection(String url): is used to establish the connection with the specified url. 4\) public static Connection getConnection(String url,String is used to establish the connection with the specified url, username and password. userName,String password): Connection interface ==================== A Connection is the session between java application and database. The Connection interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be used to get the object of Statement and DatabaseMetaData. The Connection interface provide many methods for transaction management like commit(), rollback() etc. #### By default, connection commits the changes after executing queries. ### Commonly used methods of Connection interface: **1) public Statement createStatement():** creates a statement object that can be used to execute SQL queries. ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- **2) public Statement createStatement(int resultSetType,int resultSetConcurrency):** Creates a Statement object that will generate ResultSet objects with the given type and concurrency. **3) public void setAutoCommit(boolean status):** is used to set the commit status.By default it is true. **4) public void commit():** saves the changes made since the previous commit/rollback permanent. **5) public void rollback():** Drops all changes made since the previous commit/rollback. **6) public void close():** closes the connection and Releases a JDBC resources immediately. Statement interface =================== The **Statement interface** provides methods to execute queries with the database. The statement interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet. ### Commonly used methods of Statement interface: The important methods of Statement interface are as follows: **1) public ResultSet executeQuery(String sql):** is used to execute SELECT query. It returns the object of ResultSet. -------------------------------------------------------------------------------------------------------------------------------------- **2) public int executeUpdate(String sql):** is used to execute specified query, it may be create, drop, insert, update, delete etc. **3) public boolean execute(String sql):** is used to execute queries that may return multiple results. **4) public int\[\] executeBatch():** is used to execute batch of commands. ### Example of Statement interface Let's see the simple example of Statement interface to insert, update and delete the record. ResultSet interface =================== The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to before the first row. #### By default, ResultSet object can be moved forward only and it is not updatable. But we can make this object to move forward and backward direction by passing either TYPE\_SCROLL\_INSENSITIVE or TYPE\_SCROLL\_SENSITIVE in createStatement(int,int) method as well as we can make this object as updatable by: 1. Statement stmt = con.createStatement(ResultSet.TYPE\_SCROLL\_INSENSITIVE,   2.                      ResultSet.CONCUR\_UPDATABLE);   ### Commonly used methods of ResultSet interface **1) public boolean next():** is used to move the cursor to the one row next from the current position. ----------------------------------------------------- ---------------------------------------------------------------------------------------------------------------- **2) public boolean previous():** is used to move the cursor to the one row previous from the current position. **3) public boolean first():** is used to move the cursor to the first row in result set object. **4) public boolean last():** is used to move the cursor to the last row in result set object. **5) public boolean absolute(int row):** is used to move the cursor to the specified row number in the ResultSet object. **6) public boolean relative(int row):** is used to move the cursor to the relative row number in the ResultSet object, it may be positive or negative. **7) public int getInt(int columnIndex):** is used to return the data of specified column index of the current row as int. **8) public int getInt(String columnName):** is used to return the data of specified column name of the current row as int. **9) public String getString(int columnIndex):** is used to return the data of specified column index of the current row as String. **10) public String getString(String columnName):** is used to return the data of specified column name of the current row as String. ### Example of Scrollable ResultSet Let's see the simple example of ResultSet interface to retrieve the data of 3rd row. import java.sql.\*;   class FetchRecord {   public static void main(String args\[\])throws Exception {      Class.forName(\"oracle.jdbc.driver.OracleDriver\");   Connection con=DriverManager.getConnection(\"jdbc:oracle:thin:\@localhost:1521:xe\",\"system\", \"oracle\");   Statement stmt=con.createStatement(ResultSet.TYPE\_SCROLL\_SENSITIVE,ResultSet.CONCUR\_U PDATABLE);   ResultSet rs=stmt.executeQuery(\"select \* from emp765\");      //getting the record of 3rd row   rs.absolute(3);   System.out.println(rs.getString(1)+\" \"+rs.getString(2)+\" \"+rs.getString(3));      con.close();   } }   PreparedStatement interface =========================== The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query. Let\'s see the example of parameterized query: 1. String sql=\"insert into emp values(?,?,?)\";   As you can see, we are passing parameter (?) for the values. Its value will be set by calling the setter methods of PreparedStatement. ### Why use PreparedStatement? **Improves performance**: The performance of the application will be faster if you use PreparedStatement interface because query is compiled only once. #### How to get the instance of PreparedStatement? The prepareStatement() method of Connection interface is used to return the object of PreparedStatement. Syntax: 1. public PreparedStatement prepareStatement(String query)throws SQLException{}   ### Methods of PreparedStatement interface The important methods of PreparedStatement interface are given below: **Method** **Description** ----------------------------------------------------- ------------------------------------------------------------------------------ public void setInt(int paramIndex, int value) sets the integer value to the given parameter index. public void setString(int paramIndex, String value) sets the String value to the given parameter index. public void setFloat(int paramIndex, float value) sets the float value to the given parameter index. public void setDouble(int paramIndex, double value) sets the double value to the given parameter index. public int executeUpdate() executes the query. It is used for create, drop, insert, update, delete etc. public ResultSet executeQuery() executes the select query. It returns an instance of ResultSet. ### Example of PreparedStatement interface that inserts the record First of all create table as given below: 1. create table emp(id number(10),name varchar2(50));   Now insert records in this table by the code given below: import java.sql.\*;   class InsertPrepared {   public static void main(String args\[\]) {   try {   Class.forName(\"oracle.jdbc.driver.OracleDriver\");      Connection con=DriverManager.getConnection(\"jdbc:oracle:thin:\@localhost:1521:xe\",\"system\", \"oracle\");      PreparedStatement stmt=con.prepareStatement(\"insert into Emp values(?,?)\");   stmt.setInt(1,101);//1 specifies the first parameter in the query   stmt.setString(2,\"Ratan\");      int i=stmt.executeUpdate();   System.out.println(i+\" records inserted\");      con.close();      } catch(Exception e) {  System.out.println(e); }      }   }   Java ResultSetMetaData Interface ================================ The metadata means data about data i.e. we can get further information from the data. If you have to get metadata of a table like total number of column, column name, column type etc. , ResultSetMetaData interface is useful because it provides methods to get metadata from the ResultSet object. Commonly used methods of ResultSetMetaData interface ---------------------------------------------------- **Method** **Description** --------------------------------------------------------------- ----------------------------------------------------------------- public int getColumnCount()throws SQLException it returns the total number of columns in the ResultSet object. public String getColumnName(int index)throws SQLException it returns the column name of the specified column index. public String getColumnTypeName(int index)throws SQLException it returns the column type name for the specified index. public String getTableName(int index)throws SQLException it returns the table name for the specified column index. ### How to get the object of ResultSetMetaData: -------------------------------------------------------------------------------------------------- The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData. Syntax: -------------------------------------------------------------------------------------------------- 1. public ResultSetMetaData getMetaData()throws SQLException   ### Example of ResultSetMetaData interface : Output:Total columns: 2 Column Name of 1st column: ID Column Type Name of 1st column: NUMBER

Use Quizgecko on...
Browser
Browser