Advanced Java
Advanced Java
Contents
POJO class.........................................................................................................................................................3
JDBC..................................................................................................................................................................4
JAR files in Java.............................................................................................................................................4
Java Database Connectivity with 5 steps.......................................................................................................4
JDBC Driver...................................................................................................................................................4
JDBC Connection...........................................................................................................................................5
Program 1.......................................................................................................................................................5
Prepare Statement...........................................................................................................................................7
Why use Prepared Statement.....................................................................................................................7
Methods......................................................................................................................................................7
Program 2.......................................................................................................................................................7
Program 3.......................................................................................................................................................8
Program 4.......................................................................................................................................................9
Servlet..............................................................................................................................................................10
What is Servlet?...........................................................................................................................................10
Web Terminology.........................................................................................................................................10
XML Syntax.................................................................................................................................................11
Why study XML?.....................................................................................................................................11
JSON Object Example.................................................................................................................................12
Servlet API...................................................................................................................................................12
Interfaces in [Link] package..........................................................................................................12
interfaces in [Link] package...................................................................................................13
Classes in [Link] package.......................................................................................................13
Servlet Interface...........................................................................................................................................13
Methods of Servlet interface....................................................................................................................13
Servlet Example by implementing Servlet interface....................................................................................14
Life Cycle of a Servlet.................................................................................................................................14
Creating Servlet Example in Eclipse............................................................................................................15
1) Create the dynamic web project:.........................................................................................................15
2) Create the servlet in eclipse IDE:........................................................................................................18
3) add jar file in eclipse IDE:...................................................................................................................21
4) Start the server and deploy the project:...............................................................................................24
Login............................................................................................................................................................27
Difference between GET – POST................................................................................................................28
JSP....................................................................................................................................................................29
JSP (Jakarta Server Pages) (formerly Java Server Pages)............................................................................29
1
Advantages of JSP over Servlet...................................................................................................................29
The Lifecycle of a JSP Page.........................................................................................................................29
The Directory structure of JSP.....................................................................................................................30
JSP API.....................................................................................................................................................30
Creating JSP in Eclipse IDE with Tomcat server.........................................................................................31
JSP Scriptlet tag (Scripting elements)..........................................................................................................31
JSP Scripting elements.............................................................................................................................31
JSP scriptlet tag........................................................................................................................................31
JSP expression tag....................................................................................................................................31
JSP Declaration Tag.................................................................................................................................32
Difference between JSP Scriptlet tag and Declaration tag.......................................................................32
To display the current time.......................................................................................................................33
JSP Implicit Objects.....................................................................................................................................33
JSTL (JSP Standard Tag Library).................................................................................................................33
Advantage of JSTL..................................................................................................................................33
JSTL Tags.................................................................................................................................................33
JSTL Core Tags............................................................................................................................................34
Core tags...................................................................................................................................................34
JSTL Core <c:out> tag.............................................................................................................................34
<c:set> tag................................................................................................................................................34
<c:if> tag..................................................................................................................................................34
<c:choose>, <c:when>, <c:otherwise> tags.............................................................................................35
<c:forEach> tag........................................................................................................................................35
<c:redirect> Tag.......................................................................................................................................36
<c:forTokens> Tag...................................................................................................................................36
<c:url> Tag...............................................................................................................................................36
JSTL Function Tags......................................................................................................................................36
JSTL Function Tags List..........................................................................................................................36
Formatting tags.............................................................................................................................................37
JSP Directives..............................................................................................................................................37
Syntax of JSP directive............................................................................................................................37
JSP page directive....................................................................................................................................37
JSP Taglib directive..................................................................................................................................37
JSTL fn:escapeXml() Function....................................................................................................................38
2
POJO class
POJO in Java stands for Plain Old Java Object. It refers to a simple Java object that is not bound by any
special restrictions or requirements. A POJO class does not require any specific classpath or framework
dependencies. It enhances the readability and reusability of a Java program.
Typically, a POJO class contains variables (fields) along with their corresponding getters and setters.
Short cut: alt+shift+s getters and setters or right click source getters and setters
package [Link];
package [Link];
Output:
101
Test
Hyd
3
JDBC
JAR files in Java
A JAR (Java Archive) is a package file format typically used to aggregate many Java class files along with
associated metadata and resources (such as text, images, and audio) into a single file. It is commonly used to
distribute application software or libraries on the Java platform.
In simple terms, a JAR file is a container that holds a compressed collection of .class files, images, audio
files, or directories.
For connecting the oracle database we use [Link] file.
For connecting the mysqk database we use [Link] file.
JDBC Driver
A JDBC driver is a software component that enables a Java application to interact with a database. There are
four types of JDBC drivers:
1. JDBC-ODBC Bridge Driver
2. Native-API Driver (partially java driver)
3. Network Protocol Driver (fully java driver)
4. Thin Driver (fully Java Driver)
1) a JDBC bridge is used to access ODBC drivers installed on each client machine. For example, JDBC-
ODBC Bridge driver in JDK 1.2.
2) JDBC API calls are converted into native C/C++ API calls, which are unique to the database. These APIs
are vendor specific and vendor provided driver is required to be installed. It is also called JDBC Native API.
For example, Oracle Call Interface (OCI) driver.
3) 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. It is also called JDBC-Net Pure Java driver.
4) Thin Driver
The Thin Driver converts JDBC calls directly into the vendor-specific database protocol. This is why
it is called a "thin" driver. It is fully written in the Java programming language, making it platform-
independent and easy to deploy.
4
Advantages:
Better performance than all other drivers.
No software is required at client side or server side.
Disadvantages:
Drivers depend on the Database.
JDBC Connection
1. [Link]("[Link]");
2. Connection con =
[Link]("jdbc:mysql://localhost:3306/amazon", "root",
"root");
5. [Link]();
Program 1
For below Program creating database Commands:
create database amazon;
CREATE TABLE [Link] (
id INT PRIMARY KEY,
name VARCHAR(100),
price DOUBLE,
category VARCHAR(100),
rating DOUBLE
5
);
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
}
}
Output:
6
Loading class `[Link]'. This is deprecated. The new driver class is
`[Link]'. The driver is automatically registered via the SPI and
manual loading of the driver class is generally unnecessary.
1 Wireless Mouse 25.99 Electronics 4.5
2 Bluetooth Headphones 59.49 Electronics 4.3
3 Coffee Maker 89.99 Home Appliances 4.0
4 Yoga Mat 15.75 Fitness 4.6
5 LED Desk Lamp 32.1 Home Decor 4.2
Connection established successfully
Prepare Statement
The prepared statement interface is a subinterface of statement. If is used to executed parameterized query.
Ex:-
String s1 = “insert into emp values(?,?,?)”;
As you can see, we are passing paremeter (?) for the values. If value will be set by calling the setter methods
of prepareStatement.
Why use Prepared Statement
Improves performance: The performance of the application will be faster if you use PreparedStatement
because query is compiled only once.
Methods
public void setInt(int paramIndex, int value);
public void setString(int paramIndex, String value);
public void setDouble(int paramIndex, double value);
public void setFloat(int paramIndex, Float value);
public int executeUpdate( );
public ResultSet executeQuery( );
Program 2
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
7
[Link](QUERY);
int a = [Link]();
if(a>0) {
[Link]("Sucessfully Registerd");
}
} catch(Exception e) {
[Link]();
}
finally {
try {
[Link]();
[Link]();
} catch (SQLException e) {
// TODO Auto-generated catch block
[Link]();
}
}
}
}
Program 3
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
8
[Link]("Failed Login");
}
}
} catch(Exception e) {
[Link]();
}
finally {
try {
[Link]();
} catch (SQLException e) {
// TODO Auto-generated catch block
[Link]();
}
}
Program 4
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
9
[Link]();
}
}
10
Servlet
Servlet technology is used to create web applications that reside on the server side and generate
dynamic web pages. It is considered robust and scalable because it is based on the Java programming
language. Before servlets, CGI (Common Gateway Interface) was commonly used as a server-side
programming technology. However, CGI had many disadvantages.
There are many interfaces and classes in the Servlet API, such as Servlet, GenericServlet, and
HttpServlet.
What is Servlet?
Servlet can be described in many ways.
Servlet is a technology which is used to create a web application.
Servlet is an API that provides many interfaces and classes including documentation.
Servlet is an interface that must be implemented for creating any servlet.
Servlet is a class that extends the capabilities of the servers and responds to the incoming requests. It
can respond to any requests.
Servlet is web component that is deployed on the server to create a dynamic web pages.
Web Terminology
Servlet Terminology Description
Get vs Post It gives the difference between GET and POST request.
11
Container It is used in java for dynamically generating the web
pages on the server side.
XML Syntax
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
XML stands for extensible Markup Language.
XML was designed to store and transport data.
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
12
<price>$4</price>
<author>nithin1</author>
</book>
</books>
“employees”
{
“employee”:{
“name”: “sonoo”;
“salary”: 56000;
“married”: true;
};
“employee”:{
“name”: “nithin”;
“salary”: 56000;
“married”: false;
}
}
Servlet API
The [Link] and [Link] packages represent interfaces and classes for servlet api.
The [Link] package contains many interfaces and classes that are used by the servlet or web
container. These are not specific to any protocol.
The [Link] package contains interfaces and classes that are responsible for http requests only.
Interfaces in [Link] package
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
13
11. UnavilableException
interfaces in [Link] package
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
Classes in [Link] package
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)
Servlet Interface
commonbehaviorto all the [Link] interface defines methods that all servlets must implement.
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
14
public String getServletInfo() returns information about servlet such as
writer, copyright, version etc.
import [Link].*;
import [Link].*;
PrintWriter out=[Link]();
[Link]("<html><body>");
[Link]("<b>hello simple servlet</b>");
[Link]("</body></html>");
}
public void destroy(){
[Link]("servlet is destroyed");
}
public ServletConfig getServletConfig(){
return config;
}
public String getServletInfo(){
return "copyright 2007-1010";
}
15
Creating Servlet Example in Eclipse
Create a Dynamic web project
create a servlet
add [Link] file
Run the servlet
1) Create the dynamic web project:
For creating a dynamic web project click on File Menu -> New -> Project..-> Web ->
dynamic web project -> write your project name e.g. first -> Finish.
16
17
18
2) Create the servlet in eclipse IDE:
For creating a servlet, explore the project by clicking the + icon -> explore the
Java Resources -> right click on src -> New -> servlet -> write your servlet
name e.g. Hello -> uncheck all the checkboxes except doGet() -> next -> Finish.
19
20
21
3) add jar file in eclipse IDE:
For adding a jar file, right click on your project -> Build Path -> Configure Build
Path -> click on Libraries tab in Java Build Path -> click on Add External JARs
button -> select the [Link] file under tomcat/lib -> ok.
22
23
24
Now servlet has been created, Let's write the first servlet code.
25
26
27
Now tomcat server has been started and project is deployed. To access the servlet write the url pattern name
in the URL bar of the browser. In this case Hello then enter.
Login
<form action="FirstServlet" method="post">
Name:<input type="text" name="username"/><br><br>
Password:<input type="password" name="password"/><br>
<input type="submit" value="Login"/>
</form>
package ServletPrograms;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/**
* Servlet implementation class FirstServlet
*/
28
@WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String URL = "jdbc:mysql://localhost:3306/amazon";
private static final String USER_NAME = "root";
private static final String PASSWORD = "root";
private static final String QUERY = "select * from [Link] where
username=? and password=?;";
} catch (Exception e) {
[Link]();
} finally {
try {
if (pstmt != null) {
[Link]();
}
if (con != null) {
[Link]();
}
} catch (SQLException e) { // TODO Auto-generated catch block
[Link]();
}
}
}
29
exposed in URL bar. exposed in URL bar.
[Link] request can be book marked. 3. POST request cannot be book marked.
4. Get request is idempotent. It means second 4. POST request is non-idempotent.
request will ignored until request of first request is
deliverd.
5. GET request is more efficient and used more 5. POST request is less efficient and used less than
than POST. GET.
30
JSP
Business Logic - backend Logic.
Persistence Logic – database Logic.
Presentation Logic(frontend logic) – Frontend/UI – Frontend developer/UI developer
Full Stack – backend + UI + devops
JDBC – Persistence Logic, Servlet – Persistence + Business Logic HTML/JSP – Presentation Logic.
31
As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP translator. The 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.
JSP API
JSP API consists of two packages.
1. [Link]
2. [Link]
32
Creating JSP in Eclipse IDE with Tomcat server
1. Create a Dynamic web project
2. create a jsp
3. start tomcat server and deploy the project
[Link]
<form action = "[Link]" >
UNAME : <input type = "text" name="username"><br>
<input type= "submit" value="Login">
</form>
[Link]
33
<html>
<body>
<%="welcome " + [Link]("username")%>
</body>
</html>
The jsp scriptlet tag can only declare The jsp declaration tag can declare
variables not methods. variables as well as methods.
The declaration of scriptlet tag is placed The declaration of jsp declaration tag is
inside the _jspService() method. placed outside the _jspService() method.
1. [Link]
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
2. [Link]
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
35
Core tags
The JSTL core tag provide variable support, URL management, flow control, etc. The URL for the core tag
is “[Link] .The prefix of core tag is “c”.
Download 2 jars for JSTL tags
1) [Link] (build path)
2) [Link] (lib)
<c:set> tag
It is used to set the result of an expression evaluated in a 'scope'. The <c:set> tag is helpful because it
evaluates the expression and use the result to set a value of [Link] or JavaBean.
[Link]
<%@ taglib uri="[Link] prefix="c"%>
<c:set var="x" value="100"></c:set>
<c:out value="x value : ${x}"></c:out>
<c:set var="Income" scope="session" value="${4000*4}"></c:set>
<br>
<c:out value="Income = ${Income}"></c:out>
<br>
Output:
x value : 100
Income = 16000
<c:if> tag
The < c:if > tag is used for testing the condition and it display the body content, if the expression evaluated
is true.
[Link]
<c:if test="${Income >= 16000 }">
<c:out value="Income is morethan 15000"></c:out>
</c:if>
<c:forEach> tag
The <c:for each > is an iteration tag used for repeating the nested body content for fixed number of times or
over the collection.
These tag used as a good alternative for embedding a Java while, do-while, or for loop via a scriptlet. The <
c:for each > tag is most commonly used tag because it iterates over a collection of object.
[Link]
<c:forEach var="j" begin="1" end="5">
<c:out value="j value = ${j }"></c:out>
<br>
</c:forEach>
for list
<c:forEach items="${productslist}" var="product">
37
<c:out value=" ${[Link]}"></c:out><br>
${[Link]}<br>
${[Link]}<br>
</c:forEach>
<c:redirect> Tag
The < c:redirect > tag redirects the browser to a new URL. It supports the context-relative URLs, and the <
c:param > tag.
[Link]
<c:redirect url="[Link]
<c:forTokens> Tag
<c:forTokens items="Rahul-Nakul-Rajesh" delims="-" var="name">
<c:out value="${name }" />
<br>
</c:forTokens>
<c:url> Tag
<c:url var="testurl" value="[Link]
<c:out value="${testurl }"></c:out>
38
15) fn:replace()
Formatting tags
The formatting tags provide support for message formatting, number and date formatting etc. The url for the
formatting tags is [Link] and prefix is fmt.
<%@ taglib uri="[Link] prefix="fmt" %>
1) fmt:parseDate()
2) fmt:timeZone()
3) fmt:formatDate()
JSP Directives
The jsp directives are messages that tells the web container how to translate a JSP page into the
corresponding servlet.
There are three types of directives:
1. page directive
2. include directive
3. taglib directive
Syntax of JSP directive
<%@ directive attribute="value" %>
Output:
With escapeXml() Function:
string-1 : It is first String.
string-2 : It is <xyz>second String.</xyz>
Without escapeXml() Function:
string-1 : It is first String.
string-2 : It is second String.
40