Advanced Java Tutorial- A Complete Guide for Advanced Java

Last updated on Mar 29,2022 171.2K Views
A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop. A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop.

Advanced Java Tutorial- A Complete Guide for Advanced Java

edureka.co

Most of us already know that normal applications can be easily built using core Java concepts. But, when it comes to developing web applications, advanced Java fundamentals, like JSP, Servlets, JDBC etc., can add on to the capabilities and features of the application and thus are essential for developers. Through the medium of this blog on Advanced Java Tutorial, I will be giving you a complete insight into the fundamental concepts of Advance Java.

You may also go through this recording of Advanced Java Tutorial where you can understand the topics in a detailed manner with examples.

Advance Java Tutorial | J2EE, Java Servlets, JSP, JDBC | Java Certification Training | Edureka

This Edureka tutorial on “Advanced Java” will talk about 3 main concepts i.e. JAVA Database Connectivity, Servlets, and Java Server Pages.

Advanced Java Tutorial: Introduction to Advanced Java

Advanced Java is everything that goes beyond Core Java – most importantly the APIs defined in Java Enterprise Edition, includes Servlet programming, Web Services, the Persistence API, etc. It is a Web & Enterprise application development platform which basically follows client & server architecture.

Advanced Java Tutorial: Need for Advance Java

Below I have listed down few major advantages of Advance Java:

  1. Advance Java i.e. JEE (Java Enterprise Edition) gives you the library to understand the Client-Server architecture for Web Application Development which Core Java doesn’t support.
  2. J2EE is platform Independent, Java Centric environment for developing, building & deploying Web-based applications online. It also consists of a set of services, APIs, and protocols, which provides the functionality that is necessary for developing multi-tiered, web-based applications.
  3. You will be able to work with Web and Application Servers like Apache Tomcat, Glassfish etc and understand the communication over HTTP protocol. But, in Core Java, it is not possible.
  4. There are a lot of Advance Java frameworks like Spring, JSF, Struts etc. which enable you to develop a secure transaction based web apps for the domains like E-Commerce, Banking, Legal, Financial, Healthcare, Inventory etc.
  5. To work and understand the hot technologies like Hadoop and Cloud services, you should be prepared with core and advanced Java concepts.

I hope you understood why Advanced Java is essential. For your better understanding, I have divided this article into three sections. Each of these section deals with one of the most important concepts of advanced Java:

  1. JDBC (Java DataBase Connectivity)
  2. Java Servlets
  3. JSP (Java Servlet Pages)

So, now let’s begin our discussion and understand the concept of Java Database Connectivity, a helpful tool to interact with the database.

Advanced Java Tutorial: Introduction to JDBC

JDBC is a standard Java API for a database-independent connectivity between the Java programming language and a wide range of databases. This application program interface lets you encode the access request statements, in Structured Query Language (SQL). They are then passed to the program that manages the database. It mainly involves opening a connection, creating a SQL Database, executing SQL queries and then arriving at the output.

We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC API, we can save, update, delete and fetch data from the databases. It is similar to the Open Database Connectivity (ODBC) provided by Microsoft.

For a better understanding of working of JDBC, let’s dive deeper into the topic and understand the architecture that lies behind Java Database Connectivity.

Advanced Java Tutorial: 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 −

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.

Advanced Java Tutorial: Common JDBC Components

The JDBC API provides the following interfaces and classes −

Now let’s move on to the next topic and look at the steps required to create a JDBC Application.

Advanced Java Tutorial: Steps to create JDBC Application

In order to create JDBC Application, we need to follow few steps. Let’s see what are they.

  1. Import the packages: You need to include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
  2. Register the JDBC driver: Here you have to initialize a driver so that you can open a communication channel with the database.
  3. Open a connection: Here, you can use the getConnection() method to create a Connection object, which represents a physical connection with the database.
  4. Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to the database.
  5. Extract data from result set: Requires that you use the appropriate getXXX() method to retrieve the data from the result set.
  6. Clean up the environment: Requires explicitly closing all database resources versus relying on the JVM’s garbage collection.

Now as you have seen various steps involved to create a JDBC Application, let’s see an example code to create a database and establish a connection.

package Edureka;
import java.sql.*;
import java.sql.DriverManager;
public class Example {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/emp";
//  Database credentials
static final String USER = "root";
static final String PASS = "";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,"root","");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id  = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close()
}catch(SQLException se2){
}// nothing can be done
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
} // end Example

Above code creates a table in your localhost database. To insert the values in the created database, you can refer to the below code. I will be writing the code only for step 4. Rest of the code remains the same as above.

//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE EMPLOYEES " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
System.out.println("Inserting records into the table...");
stmt =conn.createStatement();
String sql ="INSERT INTO Employees VALUES (100, 'Kriss', 'Kurian', 18)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Employees VALUES (101, 'Enrique', 'John', 25)";
stmt.executeUpdate(sql);
sql= "INSERT INTO Employees  (102, 'Taylor', 'Swift', 30)";
stmt.executeUpdate(sql);
sql= "INSERT INTO  Employees VALUES(103, 'Linkin', 'Park', 28)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");

So this is how you can establish a connection to the database and insert values in the tables. Now let’s move further and understand various JDBC Driver Types

Get Certified With Industry Level Projects & Fast Track Your Career

Advanced Java Tutorial: JDBC Driver Types

JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your database server. Essentially, a JDBC driver makes it possible to do three things:
1. Establish a connection with a data source.
2. Send queries and update statements to the data source.
3. Process the results.

For example, the use of JDBC drivers enables you to open a database connection to interact with it by sending SQL or database commands.

There are 4 types of drivers, namely:

Type 1: JDBC-ODBC Bridge Diver

In Type 1 driver, a JDBC bridge accesses ODBC drivers installed on each client machine. Further, ODBC configures 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.

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.

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. 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 drivers to communicate with the database.

Type 4: 100% Pure Java

In a Type 4 driver, a pure Java-based driver communicates directly with the vendor’s database through a 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 have to install special software on the client or server. Further, these drivers can be downloaded dynamically.

MySQL’s Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols, database vendors usually supply type 4 drivers.

Subscribe to our youtube channel to get new updates..!

So here comes the question, which Driver should be used?

Now, let’s jump into the last topic of JDBC and understand various types of connections.

Advanced Java Tutorial: JDBC Connections

You should use the registerDriver() method if you are using a non-JDK compliant JVM, such as the one provided by Microsoft.

Here each form requires a database URL. A database URL is an address that points to your database.

A table lists down the popular JDBC driver names and database URL.

RDBMSJDBC Driver NameURL
   1. MYSQL       com.mysql.jdbc.Driver     jdbc:mysql://hostname/ databaseName
   2. Oracle       oracle.jdbc.driver.OracleDriver   jdbc:oracle:thin:@hostname:port Number:databaseName
   3. Sybase       com.Sybase.jdbc.SybDriver   jdbc:sybase:Tds:hostname: port Number/databaseName

You can simply create or open a connection using database url, username, and password and also using properties object. A Properties object holds a set of keyword-value pairs. It is used to pass the driver properties to the driver during a call to the getConnection() method.

At the end of your JDBC program, we have to close all the database connections to end each database session. However, if you forget, Java’s garbage collector will close the connection when it cleans up stale objects.

conn.close();// Used to close the connection

That was all about Java Database Connectivity.  If you wish to know more about JDBC, you can refer these interview questions. Now move ahead and learn Servlets.

Advanced Java Tutorial: Introduction to Servlets

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. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers.
Servlet can be described as follows:

Advanced Java Tutorial: Servlet Life Cycle

The entire life cycle of a Servlet is managed by the Servlet container which uses the javax.servlet.Servlet interface to understand the Servlet object and manage it.

Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through four stages,

Let’s look at each of these stages in details:

  1. Loading a Servlet: The first stage of the Servlet life cycle involves loading and initializing the Servlet by the Servlet container. The Web container or Servlet Container can load the Servlet at either of the following two stages :
    • Initializing the context, on configuring the Servlet with a zero or positive integer value.
    • If the Servlet is not preceding the stage, it may delay the loading process until the Web container determines that this Servlet is needed to service a request.
  2. Initializing a Servlet: After the Servlet is instantiated successfully, the Servlet container initializes the instantiated Servlet object. The container initializes the Servlet object by invoking the init(ServletConfig) method which accepts ServletConfig object reference as a parameter.
  3. Handling request: After initialization, the Servlet instance is ready to serve the client requests. The Servlet container performs the following operations when the Servlet instance is located to service a request :
    • It creates the ServletRequest and ServletResponse. In this case, if this is an HTTP request then the Web container creates HttpServletRequest and HttpServletResponse objects which are subtypes of the ServletRequest and ServletResponse objects respectively.
  4.   Destroying a Servlet: When a Servlet container decides to destroy the Servlet, it performs the following operations,
    • It allows all the threads currently running in the service method of the Servlet instance to complete their jobs and get released.
    • After currently running threads have completed their jobs, the Servlet container calls the destroy() method on the Servlet instance.

After the destroy() method is executed, the Servlet container releases all the references of this Servlet instance so that it becomes eligible for garbage collection.

Now that you have understood the basics of a servlet, let’s move further and understand what are the steps involved to create a Servlet application.

Advanced Java Tutorial: Steps to create Servlet

  1. Create a directory structure
  2. Create a Servlet
  3. Compile the Servlet
  4. Add mappings to web.xml file
  5. Start the server and deploy the project
  6. Access the servlet

 Now, based on the above steps let’s write a program and understand how servlet works.

Step 1: To run a servlet program, we should have Apache tomcat server installed and configured. Once the server is configured, you can start with your program.  

Step 2: For a servlet program, you need 3 files – index.html file, Java class file, and web.xml file. The very first step is to create Dynamic Web Project and then proceed further

Step 3: Now let’s see how to add 2 numbers using servlets and display the output in the browser.

First,  I will write index.html file

<!DOCTYPE html>
<html>
<body>


<form action ="add">
&nbsp; Enter 1st number: <input type="text" name="num1">
&nbsp;&nbsp;Enter 2nd number: <input type="text" name="num2">
<input type ="submit">&nbsp;&nbsp;&nbsp; 
</form>


</body>
</html>

Above program creates a form to enter the numbers for the addition operation.

Step 4: Now without the Java class file, you can’t perform addition on 2 numbers. So let’s write a class file.

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Add extends HttpServlet{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void service(HttpServletRequest req, HttpServletResponse res) throws IOException
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int i = Integer.parseInt(req.getParameter("num1"));
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int j = Integer.parseInt(req.getParameter("num2");
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;   int k= i+j;
              PrintWriter out = res.getWriter();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; out.println("Result is"+k);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
}

Step 5: After writing the Java class file, the last step is to add mappings to the web.xml file. Let’s see how to do that.

Step 6: web.xml file will be present in the WEB-INF folder of your web content. If it is not present, then you can click on Deployment Descriptor and click on Generate Deployment Descriptor Stub.

Step 7: After that, you can proceed further and add the mappings to it.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns=<"http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"</em> version=<em>"3.0"</em>>
&nbsp; <display-name>Basic</display-name>
&nbsp; <servlet>
&nbsp;&nbsp; <servlet-name>Addition</servlet-name>
&nbsp;&nbsp; <servlet-class>edureka.Add</servlet-class>
  </servlet>
  <servlet-mapping>
&nbsp;&nbsp; <servlet-name>Addition</servlet-name>
&nbsp;&nbsp; <url-pattern>/add</url-pattern>
</servlet-mapping>
<welcome-file-list>
&nbsp;&nbsp;&nbsp; <welcome-file>index.html</welcome-file>
 </welcome-file-list>
</web-app>

Step 8: After all this, you can run the program by starting the server. You will get the desired output on the browser.

Basically, this is how servlet should be configured. Now let’s move further and understand the concept of session tracking.

Session Tracking

Session simply means a particular interval of time. And session tracking is a way to maintain state (data) of a user. It is also known as session management in servlet. We know that the Http protocol is stateless, so we need to maintain state using session tracking techniques. Each time user requests to the server, the server treats the request as the new request. So we need to maintain the state of a user to recognize a particular user.

You can see in the figure when you send a request it is considered as a new request.

In order to recognize the particular user, we need session tracking. So this was all about Servlets.

Now, let’s dive into the last section of our blog and understand what is JSP.

Advanced Java Tutorial: Java Server Pages

JSP or Java Server Pages is a technology that is used to create web application just like Servlet technology. It is an extension to Servlet – as it provides more functionality than servlet such as expression language, JSTL, etc. A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than Servlet because we can separate designing and development. It provides some additional features such as Expression Language, Custom Tags, etc.

Now let’s see various features of JSP with the help of below figure.

Now that you understood what is JSP, let’s see how JSP and Servlets differ from each other and why JSP is better than Servlets with the help of below table.

JSPServlets
Extension to ServletNot an extension to servlet
Easy to MaintainBit complicated
No need to recompile or redeployThe code needs to be recompiled
Less code than a servletMore code compared to JSP

Now let’s dig deeper into Java Server Pages and understand Life Cycle of JSP.

Advanced Java Tutorial: Life Cycle of JSP

The JSP pages follow these phases:

  1. Translation of JSP Page
  2. Compilation of JSP Page
  3. Classloading (the classloader loads class file)
  4. Instantiation (Object of the Generated Servlet is created)
  5. Initialization ( the container invokes jspInit())
  6. Request processing ( the container invokes _jspService())
  7. Destroy ( the container invokes jspDestroy())

As depicted in the above diagram, a JSP page is translated into Servlet by the help of JSP translator. And then, JSP translator is a part of the web server which is responsible for translating the JSP page into Servlet. After that, Servlet page is compiled by the compiler and gets converted into the class file. Moreover, all the processes that happen in Servlet are performed on JSP later, like initialization, committing response to the browser and destroy.

Advanced Java Tutorial: JSP Scripting Elements:

The scripting elements provide the ability to insert java code inside the JSP. There are three types of scripting elements:

If you wish to know more about JSP, you can refer these interview questions.

This brings us to the end of our blog on Advanced Java Tutorial.  I hope you found this blog informative and added value to your knowledge.
Check out the Java Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Advanced Java” blog and we will get back to you as soon as possible or you can also join our Java Training in Al Jubayl.

Upcoming Batches For Java Certification Training Course
Course NameDateDetails
Java Certification Training Course

Class Starts on 4th May,2024

4th May

SAT&SUN (Weekend Batch)
View Details
Java Certification Training Course

Class Starts on 25th May,2024

25th May

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR UiPath Selectors Tutorial