SlideShare a Scribd company logo
Java server pages
(jsp)
SN.Bhurt
Java Server Pages (JSP)
• JSP (Java Server Pages) is a standard for developing interactive Web
applications (pages containing dynamic content).
• A JSP web page (recognizable by the .jsp extension) may display
different content based on certain parameters.
• JSPs are integrated in a web page in HTML using special tags which will
notify the Web server that the code included within these tags are to be
interpreted.
• The result (HTML codes) will be returned to the client browser .
Java Server Pages (JSP)
• JSP is a server-side programming technology
• Enables the creation of dynamic, platform-independent method for
building Web-based applications.
• JSP have access to the entire family of Java APIs, including the JDBC
API to access enterprise databases.
• JSP support dynamic content which helps developers insert java code in
HTML pages by making use of special JSP tags, most of which start with
<% and end with %>.
Advantage of JSP
• Easy to maintain
• High Performance and Scalability.
• JSP is built on Java technology, so it is platform independent.
• JSPs are multithreaded.
• JSPs are portable.
• JSPs are object-oriented.
• JSPs are secure.
JSP Processing:
Web Server: Tomcat
• Apache Tomcat is an open source software implementation of the JSP
and Servlet technologies and can act as a standalone server for testing
JSP and Servlets and can be integrated with the Apache Web Server.
• The JSP container is responsible for intercepting requests for JSP
pages.
• JSP container works with the Web server to provide the runtime
environment and other services a JSP needs.
• Container knows how to understand the special elements that are part of
JSPs.
JSP Life Cycle
• JSP life cycle can be defined as the entire process from its creation till
the destruction.
• A JSP page is converted into Servlet in order to service requests. The
translation of a JSP page to a Servlet is called Lifecycle of JSP. JSP
Lifecycle consists of following steps.
1. Translation of JSP to Servlet code.
2. Compilation of Servlet to bytecode.
3. Loading Servlet class.
4. Creating servlet instance.
5. Initialization by calling
jspInit() method
6. Request Processing by calling
_jspService() method
7. Destroying by calling jspDestroy() method
JSP Project Stucture
JSP Compilation
• JSP pages are converted into Servlet by the Web Container.
• The Container translates a JSP page into servlet class source(.java) file and then
compiles into a Java Servlet class.
Elements of a JSP page
• A JSP page can contain four types elements (excluding the HTML
code):
 Statements: To declare methods and attributes
 Scriptlets: Java code that will be translated into code in the
service() method
 Expressions: To easily send dynamically created string to the
browser
 Directives: Comprehensive information on the page
JSP Declarations Tag
• A declaration is a block of code to define methods and class variables to
be used throughout the page.
• The syntax for a declaration is as follows:
Syntax:
<%! declaration %>
Example:
<%!String str = "Hi every one…..";
int Number = 10;
public static int add(int a, int b) {
return a+b;
}%>
JSP Expressions Tag:
• Expression is used to print all Literals, Method return values, & variable
values.
• Whatever u like to print, same thing we can keep inside a Expression
• The code placed within expression tag is written to the output stream of
the response. So you need not write out.print() to write data. It is mainly
used to print the values of variable or method.
• Whatever statements we're keeping inside a Scriptlet, those should not
end with a semicolon (;)
JSP Expressions Tag
• JSP expressions can insert strings (dynamically generated) in HTML
page. The syntax of a JSP expression is as follows:
• It can be used instead of the following scriptlet:
Syntax:
<%= Expression %>
Example:
<%= "Welcome to Hidaya Institute of Science
and Technology" %>
Syntax:
<% Statement %>
Example:
<%out.println(showData());%>
Scriptlet Tag:
• Inside Scriptlet, we're keeping the java statements.
• Scriptlets are almost look like a statements which are inside a method.
• Whatever statements we're keeping inside a method, same statements,
we can keep inside a Scriptlet.
• Whatever statements we're keeping inside a Scriptlet, those should end
with a semicolon (;)
Syntax :
<% java source code; %>
Example:
<% out.println("Welcome in JSP"); %>
JSP comments
• With JSP you can add comments in two ways.
 Generate a comment visible in the HTML source code (HTML
comment) of the client with the following syntax:
 Create a comment in the JSP code for the purpose of
documentation (not visible to the client) with the following syntax:
<!-- comments [<%= expression %>] -->
<%-- comments --%>
JSP Directives
• Directives control the processing of an entire JSP page. It gives
directions to the server regarding processing of a page.
• Directive Tag gives special instruction to Web Container at the
time of page translation.
Directive Description
<%@ page ... %>
Defines page dependent properties such as language,
session, errorPage etc.
<%@ include ... %> Defines file to be included.
<%@ taglib ... %> Declares tag library used in the page
Page Directive
Attribut Possible values Description
language java
Specifies the language to be used to
process to the instructions of the page.
import pakage.*
Allows you to import a list of classes or
packages
errorPage URL
Allows you to specify a JSP page to
manage unhandled exceptions.
contentType
text/html;charset=I
SO-8859-1
Indicates the MIME type of the page as
well as the character set used
• There are several attributes, which are used along with Page
Directives like
The import Attribute:
• The import attribute serves the same function as, and behaves like, the
Java import statement. The value for the import option is the name of the
package you want to import.
• To import java.sql.*, use the following page directive:
Syntax :
<%@ page import="java.sql.*" %>
Example:
<%@page import="java.util.Random" %>
<%@page import="java.util.Random" %>
<h1><%= "Hello World!"%></h1>
<% out.print("Welcome in JSP page");%><br />
<%
int radius = 7;
double pi = 3.1415;
out.print("Result: " + (radius + pi));
%>
<br />
<% Random rand = new Random();
int a = rand.nextInt();
out.print(a);
%>
Include Directive
• Used to copy the content of one JSP page to another. It’s like
including the code of one file into another.
• For merging external files to the current JSP page during
translation phase (The phase where JSP gets converted into the
equivalent Servlet).
Syntax:
<%@ include file="URL of the file" %>
Example:
<%@ include file=“header.html" %>
Deployment Descriptor: web.xml
• Java web applications use a deployment descriptor file to determine how
URLs map to servlets, which URLs require authentication, and other
information.
• This file is named web.xml, and resides in WEB-INF/ directory.
• web.xml is part of the servlet standard for web applications.
• IT describes the classes, resources and configuration of the application
and how the web server uses them to serve web requests.
• When the web server receives a request for the application, it uses the
deployment descriptor to map the URL of the request to the code that
ought to handle the request.
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>controller.MyServlet</servlet-
class>
</servlet>
<error-page>
<error-code>404</error-code>
<location>/error-404.jsp</location>
</error-page>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<display-name>MyTestingApp</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
</web-app>
• <form action="response.jsp" method="POST">
• <table width="350" border="1">
• <tr>
• <td><label>Enter Your Name</label></td>
• <td><input name="first_name"
type="text"></td>
• </tr>
• <tr>
• <td>Enter Father Name</td>
• <td><input name="last_name"
type="text"></td>
• </tr>
• <tr>
• <td>Gender</td>
• <td>
• <input type="radio" name="sex"
value="male" checked>Male
• <input type="radio" name="sex"
value="female">Female
• </td>
• </tr>
• <tr>
• <td>Your Course</td>
• <td>
• <select name="course">
• <option value="Not Selected"
selected>Select course</option>
• <option value="Java">Java</option>
• <option value="PHP">PHP</option>
• <option value="ASP">ASP</option>
• <option
value="System">System</option>
• <option
value="Networking">Network</option>
• </select>
• </td>
• </tr>
• <tr>
• <td colspan="2"><center><input name=""
type="submit" value="Send Value"></center></td>
• </tr>
• </table>
• </form>
• <h2>Using GET/POST Method to Read Form Data</h2>
• <ul>
• <li><p><b>First Name:</b>
• <%= request.getParameter("first_name")%>
• </p></li>
• <li><p><b>Last Name:</b>
• <%= request.getParameter("last_name")%>
• </p></li>
• <li><p><b>Gender:</b>
• <%= request.getParameter("sex")%>
• </p></li>
• <li><p><b>Course:</b>
• <%= request.getParameter("course")%>
• </p></li>
• </ul>
session
• Java have an HttpSession object which you can use to store state
information for a user.
• The session is managed on the client by a cookie (JSESSIONID) or can
be done using URL rewrites.
• The session timeout describes how long the server will wait after the last
request before deleting the state information stored in a HttpSession.
session.setAttribute("name", name);
session.getAttribute("name")
<%
session.setAttribute("username", request.getParameter("first_name"));
if (session.getAttribute("username") == "" ||
session.getAttribute("username") == null) {
%>
<h3>invalid data</h3>
<%
}
%>
DataBase
<%@ page contentType="text/html; charset=utf-8" language="java"
import="java.sql.*" errorPage="" %>
<%@page import="java.util.*" %>
<!doctype html>
<%!
public class Bean{
public int Id;
public String Name;
public String Fname;
public String Surname;
}
public Vector<Bean> getStudent()throws SQLException{
Statement stat = null;
ResultSet result = null;
Vector<Bean> vect = new Vector<Bean>();
String query = "Select StudentId, StudentName, FatherName, surname from student";
try{
stat = con.createStatement();
result=stat.executeQuery(query);
while(result.next()){
Bean std = new Bean();
std.Id = result.getInt("StudentId");
std.Name = result.getString("StudentName");
std.Fname = result.getString("FatherName");
std.Surname = result.getString("FatherName");
vect.addElement(std);
}//end loop
}finally{
if(stat!=null) stat.close();
}
return vect;
}//end getStudent
Add Method
public int addStudent(String name, String fname, String surname)throws
SQLException{
Statement stat = null;
int rows=0;
String query = "insert into student (StudentName, FatherName,
surname) VALUES ('"+name+"','"+fname+"','"+surname+"')";
try{
stat = con.createStatement();
rows = stat.executeUpdate(query);
return rows;
}finally{
if(stat!=null) stat.close();
}
}//end insert
}//end class
%>
Simple Form
html>
<body>
<form action="#" method="post">
<table width="350" border="1">
<tr>
<td><label>Enter Your Name</label></td>
<td><input name="first_name" type="text">&nbsp;</td>
</tr>
<tr>
<td>Enter Father Name</td>
<td><input name="last_name" type="text"></td>
</tr>
<tr>
<td>Enter Surname</td>
<td><input name="sur_name" type="text"></td>
</tr>
<tr>
<td colspan="2"><center><input name=""
type="submit"></center></td>
</tr>
</table>
</form>
<h2>Using GET/POST Method to Read Form Data</h2>
<%
Database db = new Database();
db.init();
if(request.getMethod().equalsIgnoreCase("POST") ){
try{
String Id = request.getParameter("stdId");
String name =
request.getParameter("first_name").trim();
String fname =
request.getParameter("last_name").trim();
String surname =
request.getParameter("sur_name").trim()
if(name.length() !=0 && fname.length() !=0){
db.addStudent(name, fname, surname);
}
Vector<Bean> vect = db.getStudent();
%>
<table width="350" border="1">
<tr>
<th>Id</th>
<th>Name</th>
<th>Father Name</th>
<th>Surname</th>
</tr>
<% for(Bean std : vect){ %>
<tr>
<td><%=std.Id%></td>
<td><%=std.Name%> </td>
<td><%=std.Fname%></td>
<td><%=std.Surname%></td>
</tr>
<% } %>
</table>
<%
}catch(Exception e){
out.println(e);
}
}//end if
else{
out.println("----------------------------"+);
}
%>
</body>
</html>

More Related Content

What's hot (20)

PPTX
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE AND JSP PROCESSING
Aaqib Hussain
 
PDF
Java Server Pages
Eleonora Ciceri
 
DOC
JSP Scope variable And Data Sharing
vikram singh
 
PDF
19servlets
Adil Jafri
 
PDF
20jsp
Adil Jafri
 
PPT
3.jsp tutorial
shiva404
 
PPT
Deploying java beans in jsp
Priyanka Pradhan
 
PPTX
Implementing jsp tag extensions
Soujanya V
 
PPTX
Jsp
chauhankapil
 
PPT
Jsp abes new
Ashwin Perti
 
PPTX
Jsp basic
Jaya Kumari
 
PPTX
Jsp presentation
Sher Singh Bardhan
 
PPT
Introduction to the Servlet / JSP course
JavaEE Trainers
 
PPT
Unified Expression Language
BG Java EE Course
 
PDF
Ch. 8 script free pages
Manolis Vavalis
 
PDF
Being a jsp
Manolis Vavalis
 
PDF
Ch. 9 jsp standard tag library
Manolis Vavalis
 
PPTX
HTL(Sightly) - All you need to know
Prabhdeep Singh
 
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE AND JSP PROCESSING
Aaqib Hussain
 
Java Server Pages
Eleonora Ciceri
 
JSP Scope variable And Data Sharing
vikram singh
 
19servlets
Adil Jafri
 
20jsp
Adil Jafri
 
3.jsp tutorial
shiva404
 
Deploying java beans in jsp
Priyanka Pradhan
 
Implementing jsp tag extensions
Soujanya V
 
Jsp abes new
Ashwin Perti
 
Jsp basic
Jaya Kumari
 
Jsp presentation
Sher Singh Bardhan
 
Introduction to the Servlet / JSP course
JavaEE Trainers
 
Unified Expression Language
BG Java EE Course
 
Ch. 8 script free pages
Manolis Vavalis
 
Being a jsp
Manolis Vavalis
 
Ch. 9 jsp standard tag library
Manolis Vavalis
 
HTL(Sightly) - All you need to know
Prabhdeep Singh
 

Viewers also liked (11)

PPTX
Jsp with mvc
vamsitricks
 
PPTX
Implicit object.pptx
chakrapani tripathi
 
PPS
Jsp element
kamal kotecha
 
PPTX
Implicit objects advance Java
Darshit Metaliya
 
DOCX
J2EE and layered architecture
Suman Behara
 
PDF
J2EE Introduction
Patroklos Papapetrou (Pat)
 
PPT
JSP
vikram singh
 
PPT
MVC ppt presentation
Bhavin Shah
 
PDF
Model View Controller (MVC)
Javier Antonio Humarán Peñuñuri
 
PPT
Mvc architecture
Surbhi Panhalkar
 
PPT
Cookies and sessions
Lena Petsenchuk
 
Jsp with mvc
vamsitricks
 
Implicit object.pptx
chakrapani tripathi
 
Jsp element
kamal kotecha
 
Implicit objects advance Java
Darshit Metaliya
 
J2EE and layered architecture
Suman Behara
 
J2EE Introduction
Patroklos Papapetrou (Pat)
 
MVC ppt presentation
Bhavin Shah
 
Model View Controller (MVC)
Javier Antonio Humarán Peñuñuri
 
Mvc architecture
Surbhi Panhalkar
 
Cookies and sessions
Lena Petsenchuk
 
Ad

Similar to Java Server Pages (20)

PPTX
Jsp
Pooja Verma
 
PPTX
JSP.pptx
NishaRohit6
 
PPTX
Introduction - Java Server Programming (JSP)
PadmavathiKPSGCAS
 
PPTX
JSP- JAVA SERVER PAGES
Yoga Raja
 
PPTX
WT Unit-Vuufvmjn dissimilating Dunkirk k
asta9578
 
PPT
Jsp sasidhar
Sasidhar Kothuru
 
PPT
Java serverpages
Amit Kumar
 
PDF
Java Web Programming [4/9] : JSP Basic
IMC Institute
 
PPT
Jsp ppt
Vikas Jagtap
 
PPT
Atul & shubha goswami jsp
Atul Giri
 
PPTX
JSP - Java Server Page
Vipin Yadav
 
PDF
JSP Components and Directives.pdf
Arumugam90
 
PPTX
SCWCD : Java server pages CHAP : 9
Ben Abdallah Helmi
 
PPTX
Web programming-Introduction to JSP.pptx
mcjaya2024
 
DOCX
Unit 4 1 web technology uptu
Abhishek Kesharwani
 
DOCX
Unit 4 web technology uptu
Abhishek Kesharwani
 
PPTX
JAVA SERVER PAGES
Kalpana T
 
PPTX
Introduction to JSP.pptx
ManishaPatil932723
 
PPT
Jsp intro
husnara mohammad
 
JSP.pptx
NishaRohit6
 
Introduction - Java Server Programming (JSP)
PadmavathiKPSGCAS
 
JSP- JAVA SERVER PAGES
Yoga Raja
 
WT Unit-Vuufvmjn dissimilating Dunkirk k
asta9578
 
Jsp sasidhar
Sasidhar Kothuru
 
Java serverpages
Amit Kumar
 
Java Web Programming [4/9] : JSP Basic
IMC Institute
 
Jsp ppt
Vikas Jagtap
 
Atul & shubha goswami jsp
Atul Giri
 
JSP - Java Server Page
Vipin Yadav
 
JSP Components and Directives.pdf
Arumugam90
 
SCWCD : Java server pages CHAP : 9
Ben Abdallah Helmi
 
Web programming-Introduction to JSP.pptx
mcjaya2024
 
Unit 4 1 web technology uptu
Abhishek Kesharwani
 
Unit 4 web technology uptu
Abhishek Kesharwani
 
JAVA SERVER PAGES
Kalpana T
 
Introduction to JSP.pptx
ManishaPatil932723
 
Jsp intro
husnara mohammad
 
Ad

Recently uploaded (20)

PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PPTX
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Dimensions of Societal Planning in Commonism
StefanMz
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 

Java Server Pages

  • 2. Java Server Pages (JSP) • JSP (Java Server Pages) is a standard for developing interactive Web applications (pages containing dynamic content). • A JSP web page (recognizable by the .jsp extension) may display different content based on certain parameters. • JSPs are integrated in a web page in HTML using special tags which will notify the Web server that the code included within these tags are to be interpreted. • The result (HTML codes) will be returned to the client browser .
  • 3. Java Server Pages (JSP) • JSP is a server-side programming technology • Enables the creation of dynamic, platform-independent method for building Web-based applications. • JSP have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. • JSP support dynamic content which helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>.
  • 4. Advantage of JSP • Easy to maintain • High Performance and Scalability. • JSP is built on Java technology, so it is platform independent. • JSPs are multithreaded. • JSPs are portable. • JSPs are object-oriented. • JSPs are secure.
  • 6. Web Server: Tomcat • Apache Tomcat is an open source software implementation of the JSP and Servlet technologies and can act as a standalone server for testing JSP and Servlets and can be integrated with the Apache Web Server. • The JSP container is responsible for intercepting requests for JSP pages. • JSP container works with the Web server to provide the runtime environment and other services a JSP needs. • Container knows how to understand the special elements that are part of JSPs.
  • 7. JSP Life Cycle • JSP life cycle can be defined as the entire process from its creation till the destruction. • A JSP page is converted into Servlet in order to service requests. The translation of a JSP page to a Servlet is called Lifecycle of JSP. JSP Lifecycle consists of following steps. 1. Translation of JSP to Servlet code. 2. Compilation of Servlet to bytecode. 3. Loading Servlet class. 4. Creating servlet instance. 5. Initialization by calling jspInit() method 6. Request Processing by calling _jspService() method 7. Destroying by calling jspDestroy() method
  • 9. JSP Compilation • JSP pages are converted into Servlet by the Web Container. • The Container translates a JSP page into servlet class source(.java) file and then compiles into a Java Servlet class.
  • 10. Elements of a JSP page • A JSP page can contain four types elements (excluding the HTML code):  Statements: To declare methods and attributes  Scriptlets: Java code that will be translated into code in the service() method  Expressions: To easily send dynamically created string to the browser  Directives: Comprehensive information on the page
  • 11. JSP Declarations Tag • A declaration is a block of code to define methods and class variables to be used throughout the page. • The syntax for a declaration is as follows: Syntax: <%! declaration %> Example: <%!String str = "Hi every one….."; int Number = 10; public static int add(int a, int b) { return a+b; }%>
  • 12. JSP Expressions Tag: • Expression is used to print all Literals, Method return values, & variable values. • Whatever u like to print, same thing we can keep inside a Expression • The code placed within expression tag is written to the output stream of the response. So you need not write out.print() to write data. It is mainly used to print the values of variable or method. • Whatever statements we're keeping inside a Scriptlet, those should not end with a semicolon (;)
  • 13. JSP Expressions Tag • JSP expressions can insert strings (dynamically generated) in HTML page. The syntax of a JSP expression is as follows: • It can be used instead of the following scriptlet: Syntax: <%= Expression %> Example: <%= "Welcome to Hidaya Institute of Science and Technology" %> Syntax: <% Statement %> Example: <%out.println(showData());%>
  • 14. Scriptlet Tag: • Inside Scriptlet, we're keeping the java statements. • Scriptlets are almost look like a statements which are inside a method. • Whatever statements we're keeping inside a method, same statements, we can keep inside a Scriptlet. • Whatever statements we're keeping inside a Scriptlet, those should end with a semicolon (;) Syntax : <% java source code; %> Example: <% out.println("Welcome in JSP"); %>
  • 15. JSP comments • With JSP you can add comments in two ways.  Generate a comment visible in the HTML source code (HTML comment) of the client with the following syntax:  Create a comment in the JSP code for the purpose of documentation (not visible to the client) with the following syntax: <!-- comments [<%= expression %>] --> <%-- comments --%>
  • 16. JSP Directives • Directives control the processing of an entire JSP page. It gives directions to the server regarding processing of a page. • Directive Tag gives special instruction to Web Container at the time of page translation. Directive Description <%@ page ... %> Defines page dependent properties such as language, session, errorPage etc. <%@ include ... %> Defines file to be included. <%@ taglib ... %> Declares tag library used in the page
  • 17. Page Directive Attribut Possible values Description language java Specifies the language to be used to process to the instructions of the page. import pakage.* Allows you to import a list of classes or packages errorPage URL Allows you to specify a JSP page to manage unhandled exceptions. contentType text/html;charset=I SO-8859-1 Indicates the MIME type of the page as well as the character set used • There are several attributes, which are used along with Page Directives like
  • 18. The import Attribute: • The import attribute serves the same function as, and behaves like, the Java import statement. The value for the import option is the name of the package you want to import. • To import java.sql.*, use the following page directive: Syntax : <%@ page import="java.sql.*" %> Example: <%@page import="java.util.Random" %>
  • 19. <%@page import="java.util.Random" %> <h1><%= "Hello World!"%></h1> <% out.print("Welcome in JSP page");%><br /> <% int radius = 7; double pi = 3.1415; out.print("Result: " + (radius + pi)); %> <br /> <% Random rand = new Random(); int a = rand.nextInt(); out.print(a); %>
  • 20. Include Directive • Used to copy the content of one JSP page to another. It’s like including the code of one file into another. • For merging external files to the current JSP page during translation phase (The phase where JSP gets converted into the equivalent Servlet). Syntax: <%@ include file="URL of the file" %> Example: <%@ include file=“header.html" %>
  • 21. Deployment Descriptor: web.xml • Java web applications use a deployment descriptor file to determine how URLs map to servlets, which URLs require authentication, and other information. • This file is named web.xml, and resides in WEB-INF/ directory. • web.xml is part of the servlet standard for web applications. • IT describes the classes, resources and configuration of the application and how the web server uses them to serve web requests. • When the web server receives a request for the application, it uses the deployment descriptor to map the URL of the request to the code that ought to handle the request.
  • 23. • <form action="response.jsp" method="POST"> • <table width="350" border="1"> • <tr> • <td><label>Enter Your Name</label></td> • <td><input name="first_name" type="text"></td> • </tr> • <tr> • <td>Enter Father Name</td> • <td><input name="last_name" type="text"></td> • </tr> • <tr> • <td>Gender</td> • <td> • <input type="radio" name="sex" value="male" checked>Male • <input type="radio" name="sex" value="female">Female • </td> • </tr> • <tr> • <td>Your Course</td> • <td> • <select name="course"> • <option value="Not Selected" selected>Select course</option> • <option value="Java">Java</option> • <option value="PHP">PHP</option> • <option value="ASP">ASP</option> • <option value="System">System</option> • <option value="Networking">Network</option> • </select> • </td> • </tr> • <tr> • <td colspan="2"><center><input name="" type="submit" value="Send Value"></center></td> • </tr> • </table> • </form>
  • 24. • <h2>Using GET/POST Method to Read Form Data</h2> • <ul> • <li><p><b>First Name:</b> • <%= request.getParameter("first_name")%> • </p></li> • <li><p><b>Last Name:</b> • <%= request.getParameter("last_name")%> • </p></li> • <li><p><b>Gender:</b> • <%= request.getParameter("sex")%> • </p></li> • <li><p><b>Course:</b> • <%= request.getParameter("course")%> • </p></li> • </ul>
  • 25. session • Java have an HttpSession object which you can use to store state information for a user. • The session is managed on the client by a cookie (JSESSIONID) or can be done using URL rewrites. • The session timeout describes how long the server will wait after the last request before deleting the state information stored in a HttpSession. session.setAttribute("name", name); session.getAttribute("name")
  • 26. <% session.setAttribute("username", request.getParameter("first_name")); if (session.getAttribute("username") == "" || session.getAttribute("username") == null) { %> <h3>invalid data</h3> <% } %>
  • 27. DataBase <%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %> <%@page import="java.util.*" %> <!doctype html> <%! public class Bean{ public int Id; public String Name; public String Fname; public String Surname; }
  • 28. public Vector<Bean> getStudent()throws SQLException{ Statement stat = null; ResultSet result = null; Vector<Bean> vect = new Vector<Bean>(); String query = "Select StudentId, StudentName, FatherName, surname from student"; try{ stat = con.createStatement(); result=stat.executeQuery(query); while(result.next()){ Bean std = new Bean(); std.Id = result.getInt("StudentId"); std.Name = result.getString("StudentName"); std.Fname = result.getString("FatherName"); std.Surname = result.getString("FatherName"); vect.addElement(std); }//end loop }finally{ if(stat!=null) stat.close(); } return vect; }//end getStudent
  • 29. Add Method public int addStudent(String name, String fname, String surname)throws SQLException{ Statement stat = null; int rows=0; String query = "insert into student (StudentName, FatherName, surname) VALUES ('"+name+"','"+fname+"','"+surname+"')"; try{ stat = con.createStatement(); rows = stat.executeUpdate(query); return rows; }finally{ if(stat!=null) stat.close(); } }//end insert }//end class %>
  • 30. Simple Form html> <body> <form action="#" method="post"> <table width="350" border="1"> <tr> <td><label>Enter Your Name</label></td> <td><input name="first_name" type="text">&nbsp;</td> </tr> <tr> <td>Enter Father Name</td> <td><input name="last_name" type="text"></td> </tr> <tr> <td>Enter Surname</td> <td><input name="sur_name" type="text"></td> </tr>
  • 31. <tr> <td colspan="2"><center><input name="" type="submit"></center></td> </tr> </table> </form> <h2>Using GET/POST Method to Read Form Data</h2> <% Database db = new Database(); db.init(); if(request.getMethod().equalsIgnoreCase("POST") ){ try{ String Id = request.getParameter("stdId"); String name = request.getParameter("first_name").trim(); String fname = request.getParameter("last_name").trim(); String surname = request.getParameter("sur_name").trim()
  • 32. if(name.length() !=0 && fname.length() !=0){ db.addStudent(name, fname, surname); } Vector<Bean> vect = db.getStudent(); %> <table width="350" border="1"> <tr> <th>Id</th> <th>Name</th> <th>Father Name</th> <th>Surname</th> </tr> <% for(Bean std : vect){ %> <tr> <td><%=std.Id%></td> <td><%=std.Name%> </td> <td><%=std.Fname%></td> <td><%=std.Surname%></td> </tr>
  • 33. <% } %> </table> <% }catch(Exception e){ out.println(e); } }//end if else{ out.println("----------------------------"+); } %> </body> </html>