0% found this document useful (0 votes)
10 views40 pages

Advanced Java

The document provides an overview of advanced Java concepts, including POJO classes, JDBC, Servlets, and JSP. It covers the structure and usage of JDBC for database connectivity, the role of Servlets in web applications, and the functionality of JSP and JSTL. Additionally, it includes code examples and explanations for creating and managing database connections and web components in Java.

Uploaded by

Vineeth Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views40 pages

Advanced Java

The document provides an overview of advanced Java concepts, including POJO classes, JDBC, Servlets, and JSP. It covers the structure and usage of JDBC for database connectivity, the role of Servlets in web applications, and the functionality of JSP and JSTL. Additionally, it includes code examples and explanations for creating and managing database connections and web components in Java.

Uploaded by

Vineeth Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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];

public class Customer {


int customerId;
String customerName;
String customerAddress;
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
[Link] = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
[Link] = customerName;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(String customerAddress) {
[Link] = customerAddress;
}
}

package [Link];

public class CustomerMain {

public static void main(String[] args) {


Customer cust = new Customer();
[Link](101);
[Link]("Test");
[Link]("Hyd");
[Link]([Link]());
[Link]([Link]());
[Link]([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.

Java Database Connectivity with 5 steps


There are 5 steps to connect any java application with the database using JDBC. These are folloes:
1. Register the Driver class
2. Create connection
3. Create Statement
4. Execute quires
5. Close connection

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");

3. Statement stmt = [Link]();

4. ResultSet rs = [Link]("Select * from [Link]");


while ([Link]()) {
[Link]([Link](1) + "\t" + [Link](2) + "\t\t" +
[Link](3) + "\t"
+ [Link](4) + "\t" + [Link](5))
}

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
);

INSERT INTO [Link] (id, name, price, category, rating) VALUES


(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.10, 'Home Decor', 4.2);

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class FirstJDBCClass {


public static void main(String[] args) {
Connection con = null;
try {
[Link]("[Link]");
con =
[Link]("jdbc:mysql://localhost:3306/amazon", "root",
"root");
if (![Link]()) {
Statement stmt = [Link]();
ResultSet rs = [Link]("Select * from
[Link]");
while ([Link]()) {
[Link]([Link](1) + "\t" +
[Link](2) + "\t\t" + [Link](3) + "\t" + [Link](4) + "\t" +
[Link](5));
}
[Link]("Connection established
successfully");
}
} catch (Exception e) {
[Link]();
} finally {
try {
[Link]();
} catch (SQLException e) {
[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];

public class SecondJDBCProgram {


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 = "insert into
[Link](username,password) values(?,?);";
public static void main(String[] args) {
Connection con = null;
PreparedStatement pstmt = null;
try {
[Link]("[Link]");
con = [Link](URL,USER_NAME,PASSWORD);
pstmt = [Link](QUERY);
[Link](1, "test");
[Link](2, "Hi");

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];

public class ThirdJDBCClass {


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];";
public static void main(String[] args) {
String uname = "Hari";
String pwd = "Hah";
Connection con = null;
try {
[Link]("[Link]");
con = [Link](URL,USER_NAME,PASSWORD);
PreparedStatement pstmt = [Link](QUERY);
//[Link](1, uname);
//[Link](2, pwd);
[Link](QUERY);
ResultSet rs = [Link]();

//[Link]([Link](1) + " " + [Link](2));


while([Link]()) {
[Link]([Link](1) + " "+
[Link](2));
}
if([Link]()) {
if([Link](1).equalsIgnoreCase(uname) &&
[Link](2).equalsIgnoreCase(pwd)) {
[Link]("Successfully login");
}
else {

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];

public class FourthJDBC {

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
userId=?";
public static void main(String[] args) {
int id=1;
Connection con = null;
PreparedStatement pstmt = null;
try {
[Link]("[Link]");
con = [Link](URL, USER_NAME, PASSWORD);
pstmt = [Link](QUERY);
[Link](1, id);
[Link](QUERY);
ResultSet rs = [Link]();
while ([Link]()) {
[Link]([Link](1) + "\t" + [Link](2)
+ "\t" + [Link](3));
}
} catch (Exception e) {
[Link]();
} finally {
try {
[Link]();
[Link]();
} catch (SQLException e) {
// TODO Auto-generated catch block

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

Website: static vs It is a collection of related web pages that may contain


dynamic text, images, audio and video.

HTTP It is the data communication protocol used to establish


communication between client and server.

HTTP Requests It is the request send by the computer to a web server


that contains all sorts of potentially interesting
information.

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.

Server: Web vs It is used to manage the network resources and for


Application running the program or software that provides services.

Content Type It is HTTP header that provides the description about


what are you sending to the browser.

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>

Why study XML?


XML plays an important role in many different IT systems XML is often used for distributing data over the
Internet.
<books>
<book>
<id>1234</id>
<name>test</name>
<price>$4</price>
<author>nithin</author>
</book>
<book>
<id>1236</id>
<name>test1</name>

12
<price>$4</price>
<author>nithin1</author>
</book>
</books>

JSON Object Example


A JSON object contains data in the form of key/value pair. The keys are strings and the values are seperated
by colon. Each entry (Key/Value pair) is generated by comma.

“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

public void init(ServletConfig initializes the servlet. It is the life cycle


config) method of servlet and invoked by the web
container only once.

public void provides response for the incoming request.


service(ServletRequest It is invoked at each request by the web
request,ServletResponse container.
response)

public void destroy() is invoked only once and indicates that


servlet is being destroyed.

public ServletConfig returns the object of ServletConfig.


getServletConfig()

14
public String getServletInfo() returns information about servlet such as
writer, copyright, version etc.

Servlet Example by implementing Servlet interface

import [Link].*;
import [Link].*;

public class First implements Servlet{


ServletConfig config=null;

public void init(ServletConfig config){


[Link]=config;
[Link]("servlet is initialized");
}

public void service(ServletRequest req,ServletResponse res) throws IOExcept


ion,ServletException{
[Link]("text/html");

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";
}

Life Cycle of a 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.

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.

4) Start the server and deploy the project:


For starting the server and deploying the project in one step, Right click on your
project -> Run As -> Run on Server -> choose tomcat server -> next -> addAll -
> finish.

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=?;";

protected void doPost(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
String uname = [Link]("username");
String pwd = [Link]("password");
Connection con = null;
PreparedStatement pstmt = null;
try {
[Link]("[Link]");
con = [Link](URL, USER_NAME, PASSWORD);
pstmt = [Link](QUERY);
[Link](1, uname);
[Link](2, pwd);
[Link](QUERY);
[Link]("Hi");
ResultSet rs = [Link]();
if ([Link]()) {
[Link]("Successfully login");
} else {
[Link]("Failed login");
}

} catch (Exception e) {
[Link]();
} finally {
try {
if (pstmt != null) {
[Link]();
}
if (con != null) {
[Link]();
}
} catch (SQLException e) { // TODO Auto-generated catch block
[Link]();
}
}
}

Difference between GET – POST


GET POST
1. In case of GET request, only limited amount of 1. In case of POST request, large amount of data
data can be sent because data is sent is header. can be sent because data is sent in body.
[Link] request is not secured because data is 2. POST request is secured because data is not

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.

JSP file change – No need to compile and deployment.


Java file change – Need to Compile and deployment.
XML file chage – Only restart the server.

JSP (Jakarta Server Pages) (formerly Java Server Pages)


JSP technology is used to create web applilcation just like servlet technology. It can be thought of as an
extension to servlet because it provides more functionality than servlet such as expression language, JSTL,
etc.
A JSP pages consists of HTML tags and JSP tags. The JSP pages are easier to maintain than servlet
because we can separate designing and deployment. It provides some additional features such as Expression
language, Custom Tags, etc.

Advantages of JSP over Servlet


1. Extension Servlet
2. Easy to maintain
3. Fast Development, No need to recompile & redeploy.
4. Less code than servlet.
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the code. Moreover,
we can use EL, implicit objects, etc.

The Lifecycle of a JSP Page


The JSP pages follow these phases:
 Translation of JSP Page
 Compilation of JSP Page
 Classloading (the classloader loads class file)
 Instantiation (Object of the Generated Servlet is created).
 Initialization ( the container invokes jspInit() method).
 Request processing ( the container invokes _jspService() method).
 Destroy ( the container invokes jspDestroy() method).
Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.

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.

The Directory structure of JSP


The directory structure of JSP page is same as Servlet. We contain the JSP page outside the WEB-INF folder
or in any directory.

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

JSP Scriptlet tag (Scripting elements)


In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are the scripting
elements first.
JSP Scripting elements
The scripting elements provides the ability to insert java code inside the jsp. There are three types of
scripting elements:
 scriptlet tag
 expression tag
 declaration tag
JSP scriptlet tag
A scriptlet tag is used to execute java source code in JSP.
<% java source code %>

Example of JSP scriptlet tag


[Link]
<% [Link]("welcome to jsp"); %>

JSP expression tag


The code placed within JSP expression tag is written to the output stream of the response. So you need not
write [Link]() to write data. It is mainly used to print the values of variable or method.
Syntax:
<%= statement %>
Example:
[Link]
<% [Link](“Welcome to second JSP”);%>
</br>
<%= “Welcome to jsp”%>

[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>

JSP Declaration Tag


The JSP declaration tag is used to declare fields and methods.
The code written inside the jsp declaration tag is placed outside the service() method of auto generated
servlet.
So it doesn't get memory at each request.
Syntax:
<%! field or method declaration %>

Difference between JSP Scriptlet tag and Declaration tag


Jsp Scriptlet Tag Jsp Declaration Tag

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>

To display the current time


[Link]().getTime();
34
<% [Link]("Today is:" + [Link]()); %>

JSP Implicit Objects


There are 9 jsp implicit objects. These objects are created by the web container that are available to all the
jsp pages.
The available implicit objects are out, request, config, session, application etc.

Object Type

out JspWriter

request HttpServletRequest

response HttpServletResponse

config ServletConfig

application ServletContext

session HttpSession

pageContext PageContext

page Object

exception Throwable

JSTL (JSP Standard Tag Library)


The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP development.
Advantage of JSTL
1. Fast Development JSTL provides many tags that simplify the JSP.
2. Code Reusability We can use the JSTL tags on various pages.
3. No need to use scriptlet tag It avoids the use of scriptlet tag.
JSTL Tags
 Core tags
 Function tags
 Formatting tags
 XML tags

JSTL Core Tags


The JSTL core tag provides variable support, URL management, flow control etc.
<%@ taglib uri="[Link] prefix="c" %>
1) c:out 2) c:import 3) c:set 4) c:remove 5) c:catch
6) c:if 7) c:choose, c:when, c:otherwise 8) c:forEach 9) c:forTokens 10) c:param
11) c:redirect 12) c:url

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)

JSTL Core <c:out> tag


The <c:out> tag is similar to JSP expression tag, but it can only be used with expression. It will display the
result of an expression, similar to the way < %=...% > work.
The < c:out > tag automatically escape the XML tags. Hence they aren't evaluated as actual tags.
[Link]
<%@ taglib uri="[Link] prefix="c" %>
<c:out value="Welcome to JSP world "/>

<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:choose>, <c:when>, <c:otherwise> tags


The < c:choose > tag is a conditional tag that establish a context for mutually exclusive conditional
operations. It works like a Java switch statement in which we choose between a numbers of alternatives.
36
The <c:when > is subtag of <choose > that will include its body if the condition evaluated be 'true'.
The < c:otherwise > is also subtag of < choose > it follows &l;twhen > tags and runs only if all the prior
condition evaluated is 'false'.
The c:when and c:otherwise works like if-else statement. But it must be placed inside c:choose tag.
[Link]
<c:set var="Income" scope="session" value="${4000*4}"></c:set>
<c:choose>
<c:when test="${Income < 5000 }">
<c:out value="He is very very poor"></c:out>
</c:when>
<c:when test="${Income > 5000 && Income<10000 }">
<c:out value="He is very poor"></c:out>
</c:when>
<c:when test="${Income > 10000 && Income<100000 }">
<c:out value="He is poor"></c:out>
</c:when>
<c:otherwise>
<c:out value="He is rich"></c:out>
</c:otherwise>
</c:choose>

Even/odd example using c:when and c:otherwise


<c:set var="num" value="${3 }"></c:set>
<c:choose>
<c:when test="${num%2 ==0 }">
<c:out value="Even number"></c:out>
</c:when>
<c:otherwise>
<c:out value="Odd number"></c:out>
</c:otherwise>
</c:choose>

<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>

JSTL Function Tags


The JSTL function provides a number of standard functions, most of these functions are common string
manipulation functions. The syntax used for including JSTL function library in your JSP is:
<%@ taglib uri="[Link] prefix="fn" %>

JSTL Function Tags List


1) fn:contains()
2) fn:containsIgnoreCase()
3) fn:endsWith()
4) fn:escapeXml()
5) fn:indexOf()
6) fn:trin()
7) fn:startsWith()
8) fn:split()
9) fn:toLowerCase()
10) fn:toUpperCase()
11) fn:subString()
12) fn:subStringAfter()
13) fn:subStringBefore()
14) fn:length()

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" %>

JSP page directive


The page directive defines attributes that apply to an entire JSP page
Ex:- import directive
<%@ page import="[Link]" %>
Today is: <%= new Date() %>

JSP Taglib directive


The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD (Tag Library
Descriptor) file to define the tags. In the custom tag section we will use this tag so it will be better to learn it
in custom tag.
Syntax:
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
Example:
<%@ taglib uri="[Link] prefix="mytag" %>
<mytag:currentDate/>

JSTL fn:escapeXml() Function


The fn:escapeXml() function escapes the characters that would be interpreted as XML markup. It is used for
escaping the character in XML markup language.
39
Syntax:
${fn:escapeXml(String inputString)}

<%@ taglib uri="[Link] prefix="c" %>


<%@ taglib uri="[Link] prefix="fn" %>

<c:set var="string1" value="It is first String."/>


<c:set var="string2" value="It is <xyz>second String.</xyz>"/>

<p>With escapeXml() Function:</p>


<p>string-1 : ${fn:escapeXml(string1)}</p>
<p>string-2 : ${fn:escapeXml(string2)}</p>

<p>Without escapeXml() Function:</p>


<p>string-1 : ${string1}</p>
<p>string-2 : ${string2}</p>

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

You might also like