0% found this document useful (0 votes)
28 views

Java Server Pages

The document discusses JSP (Java Server Pages), which is a server-side technology for developing dynamic web pages with Java. It describes how JSP pages are processed by the web container and converted into servlets. The document also covers JSP scripting elements, implicit objects, and how to declare variables and methods in JSP.

Uploaded by

ramauppala17
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Java Server Pages

The document discusses JSP (Java Server Pages), which is a server-side technology for developing dynamic web pages with Java. It describes how JSP pages are processed by the web container and converted into servlets. The document also covers JSP scripting elements, implicit objects, and how to declare variables and methods in JSP.

Uploaded by

ramauppala17
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 56

JSP

(Java Server Pages)


Contents
• The Problem with Servlet
• The Anatomy of a JSP Page
• JSP Processing
• JSP Application Development
• Generating Dynamic Content
• Using Scripting Elements
• Implicit JSP Objects
• Declaring Variables and Methods
• Sharing Data Between JSP pages
• Users Passing Control and Data between Pages
• JSP application design with JDBC
• JSP Application Design with MVC.
The Problem with Servlet
• In many Java servlet-based applications, processing the request and
generating the response are both handled by a single servlet class
• Using servlets, Java programming is required to develop and maintain all
aspects of the application
• Changing the look and feel of the application by adding modifications to the
existing servlet requires the servlet code to be updated and recompiled.
• Both presentation layer and business logic layer put together in Servlets.
• Writing complex business logic makes the application difficult to
understand.
• web.xml is mandatory in Servlets.
• Incase of Servlets, the Programmer compiles manually a Servlet file and
deploys a .class file in server.
Introduction to JSP
• JSP is a server side technology for developing web pages that
include dynamic content
• JSP is used for creating dynamic web applications, using java as
programming language.
• A JSP page consists of HTML tags and JSP tags.
• JSP has both presentation logic as well as business logic.
• In JSP, you can embed Java code in HTML using JSP tags
• Most of which start with <% an ends with ( here java code)%>.
• Released in 1999 by Sun Microsystems,
Cont …
• JSP pages are opposite of Servlets as a servlet adds HTML code
inside Java code, while JSP adds Java code inside HTML using JSP
tags.
• Using JSP, you can collect input from users through Webpage forms,
present records from a database or another source, and create
Webpages dynamically.
• JSP tags can be used for a variety of purposes, such as
• retrieving information from a database
• accessing JavaBeans components,
• passing control between pages,
• and sharing information between requests, pages etc.
Why JSP is preferred over servlets?
• JSP provides an easier way to code dynamic web pages.
• JSP does not require additional files like, java class files, web.xml etc
• Any change in the JSP code is handled by Web Container(Application server
like tomcat), and doesn't require re-compilation.
• JSP needs no compilation by the Programmer.
• Both presentation layer and business logic layer put together in Servlets.
• In JSP, they can be separated with the usage of JavaBeans.
• JSP pages can be directly accessed, and web.xml mapping is not required like
in servlets.
• Programmer deploys directly a JSP source code file in server where as incase
of Servlets, the Programmer compiles manually a Servlet file and deploys
a .class file in server.
Example
<%-- JSP comment --%>
<HTML> <HEAD>
<TITLE>MESSAGE</TITLE> </HEAD>
<BODY>
<%out.print("Hello, Sample JSP code");%>
</BODY> </HTML>
JSP Processing
• The web server have JSP engine (container) to process JSP pages.
• All the requests for JSP Pages are handled by JSP Container.
• 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.
Cont …
1. Web browser sends an HTTP request to the web server requesting JSP page.
2. Web server recognizes that the HTTP request by checking the extension of the file
(i.e .jsp)
3. Web server forwards HTTP Request to JSP engine.
4. JSP engine loads the JSP page from disk and converts it into a servlet
5. JSP engine then compiles the servlet into an executable class and forward original
request to a servlet engine.
6. Servlet engine loads and executes the Servlet class.
7. Servlet produces an output in HTML format
8. Output produced by servlet engine is then passes to the web server inside an HTTP
response.
9. Web server sends the HTTP response to Web browser in the form of HTML content.
10. Web browser loads the page into the browser and thus user can view the
dynamically generated page.
Architecture of a JSP Application…
The Anatomy of a JSP Page
Cont …
• A JSP page is simply a regular web page with JSP elements for
generating the parts of the page that differ for each request
• Everything in the page that is not a JSP element is called template
text .
• Template text can really be any text: HTML, XML, or even plain text.
• When a JSP page request is processed, the template text and the
dynamic content generated by the JSP elements are merged, and the
result is sent as the response to the browser.
Cont …
• The jsp:useBean action instantiates an instance of the bean class
• The id is the access name of this bean.
• <jsp:setProperty is used to assign values to properties of a bean.
Ex:
<jsp:setProperty name="myBook" property="price" value=30 />
• jsp:getProperty Action Element retrieves the value of a bean property,
converts it to a string, and inserts it into the JSP outputs.
Ex:
• <jsp:getProperty name="myBook" property="price“/>
Directory structure of JSP
• The directory structure of JSP page is same as servlet. We contains the jsp
page outside the WEB-INF folder or in any directory.
• Localhost:8080/Dirname/name.jsp
JSP Scripting Elements
• The scripting elements are used to insert java code inside the jsp.
• There are three types of scripting elements:
1. scriptlet tag
2. expression tag
3. declaration tag
JSP scriptlet tag
• In JSP, java code can be written inside the jsp page using the scriptlet tag
• Scriptlet Tag allows you to write java code inside JSP page
Syntax:
<% java source code %>
Ex:
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>
Index.html welcome.jsp
<html>
<html>
<body> <body>
<form action="welcome.jsp"> <%
<input type="text" name="uname"> String name=request.getParameter("uname");
out.print("welcome "+name); %>
<input type="submit" value="go"><br/>
</body>
</form> </html>
</body>
</html>

Out put: welcome Devansh


JSP Expression tag

• Expression tag evaluates the expression placed in it, converts the result into
String and send the result back to the client through response object.
• Basically it writes the result to the client(browser).
• So you need not write out.print() to write data.
• It is mainly used to print the values of variable or method.
• <%= used to specify the Expression tag
Syntax
<%= statement %>
Ex:
<html> <body>
<%= "welcome to jsp" %>
</body> </html>
Example of JSP expression tag that prints current time & date

<HTML>
<BODY>
Hello ! CSE Students
<br>
Current time is: <%=new java.util.Date()%>
</BODY>
</HTML>

Output:
Hello ! CSE Students
Current time is: Sun Oct 29 10:50:04 IST 2017
Example of JSP expression tag that prints the user name
<html>
<html>
<body> <body>
<form action="welcome.jsp"> <
%= "Welcome "+request.getParameter("uname") %>
<input type="text" name="uname"> </body>
<input type="submit" value="go"><br/ </html>
></form>
</body>
</html>

Out put: welcome Devansh


Declaration Tag (or) Declaring Variables and Methods
• Declaration tag is a block of java code for declaring class wide variables,
methods.
• The JSP declaration tag is used to declare variables and methods.
• <%! Is used to specify declaration.
Syntax
<%! field or method declaration %>
Ex:
<html> <body>
<%! String name="Neha"; %>
<%! int age=5; %>
<%= "Name is: "+ name %><br>
<%= "AGE: "+ age %>
Example of JSP declaration tag that declares method

<html>
<body>
<%!
int cube(int n){
return n*n*n;
}
%>
<%= "Cube of 3 is:" +cube(3) %>
</body>
</html>
Jsp Implicit Objects

Jsp objects are created by JSP Engine during translation phase (while
translating JSP to Servlet).
There are total 9 implicit objects available in JSP.
1. out
2. request
3. response
4. config
5. application
6. session
7. pageContext
8. page
9. exception
Jsp Implicit Objects

Out:
• Out is one of the implicit objects to write the data to the buffer and send
output to the client in response
• Out is object of jspWriter class
Request:
• The request object is an instance of java.servlet.http.HttpServletRequest.
• It will be created by container for every request.
• It will be used to request the information like parameter, header
information , server name, etc.
• It uses getParameter() to access the request parameter.
Jsp Implicit Objects

Response:
• "Response" is an instance of class which implements HttpServletResponse
interface
• "Response object" will be created by the container for each request.
• It represents the response that can be given to the client
• The response implicit object is used to content type, add cookie and redirect
to response page
• void sendRedirect(String address) – It redirects the control to a new JSP page
• response.sendRedirect("http://beginnersbook.com");
Jsp Implicit Objects

Config:
• Config is of the type java.servlet.servletConfig
• It is created by the container for each jsp page
• It is used to get the initialization parameter in web.xml
Application :
• Application object is an instance of javax.servlet.ServletContext
• This is used for getting application-wide initialization parameters and to
maintain useful data across whole JSP application.
• Application object is created by container one per application, when the
application gets deployed.
Jsp Implicit Objects

Session
• The session is holding "httpsession" object
• Session object is used to get, set and remove attributes to session scope and
also used to get session information
pageContext:
• It is an instance of javax.servlet.jsp.PageContext
• It is used for accessing page, request, application and session attributes.
Exception:
• Exception implicit object is used in exception handling for displaying the error
messages
Index.html check.jsp
<html>
<html>
<body>
<head> <%
<title>Login Page</title> String uid=request.getParameter("id");
</head> String password=request.getParameter("pass");
<body> session.setAttribute("session-uid", uid);
<form action="check.jsp"> if(uid.equals("devansh") && password.equals("Harshi"))
{
UserId: <input type="text" name="id" /> <br>
response.sendRedirect("success.jsp");
Password: <input type="text"
}
name="pass" /> <br>
else
<input type="submit" value="Sign In!!"/>
{
</form> response.sendRedirect("failed.jsp");
</body> }
</html> %>
</body> </html>
success.jsp failed.jsp

<%@page contentType="text/html"
pageEncoding="UTF-8"%> <%@page contentType="text/html"
pageEncoding="UTF-8"%>
<html>
<html>
<body>
<body>
<h1 style=color:blue>Hey Devansh U
have Successfully login on </h1> <h1>U have Failed!</h1>

<h2 style=color:red> <%=new </body>


java.util.Date()%></h2> </html>
</body>
</html>
JSP directives
• Directives control the processing of an entire JSP page.
• It gives directions to the server regarding processing of a page.
Syntax of Directives:
<%@ directive name [attribute name=“value” attribute
name=“value” ........]%>
• There are three types of Directives in JSP:

1) Page Directive
2) Include Directive
3) TagLib Directive
Page Directive
• The Page directive defines a number of page dependent properties
which communicates with the Web Container at the time of
translation.
Basic syntax of using the page directive is
<%@ page attribute="value" %>
Some of the attributes are
• import attribute
• language attribute
• contentType attribute
Page Directive
import:
• This attribute is used to import packages.
Syntax : <%@page import="value"%>
language :
• language attribute defines scripting language to be used in the page.
Syntax : <%@ page language="value"%>
contentType:
• This attribute is used to set the content type of a JSP page.
Default value: text/html
2) Include Directive
• Include directive is used to copy the content of one JSP page to
another.
• It’s like including the code of one file into another.
<%@include file ="value"%>
• here value is the JSP file name which needs to be included.
• If the file is in the same directory then just specify the file name
otherwise complete URL(or path) needs to be mentioned in the value
field.
• Note: It can be used anywhere in the page.
Example:
• <%@include file="myJSP.jsp"%>
include.jsp declaration.jsp

<html> <html> <body>


<body> <%! String name="Neha"; %>
<%@ include file="declaration.jsp" %> <%! int age=5; %>
<%=name %> </body> </html>
Use this page on : <%=new
java.util.Date()%>
</body>
</html>
JSP Taglib
• 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
Syntax JSP Taglib directive
• %@taglib uri ="taglibURI" prefix="tag prefix"%>
• Where URI is uniform resource locator, which is used to identify the location
of custom tag and tag prefix is a string which can identify the custom tag in
the location identified by uri.
Example:
<%@ taglib uri="http://www.sample.com/mycustomlib" prefix="demotag" %>
<html> <body>
<demotag:welcome/>
</body> </html>
Sharing Data Between JSP Pages
• Any real application consists of more than a single page, and multiple
pages often need access to the same information and server-side
resources.
• When multiple pages process the same request (e.g., one page that
retrieves the data the user asked for and another that displays it),
there must be a way to pass data from one page to another.
• To make this happen, you need to be able to do two things:
1. Pass control from one page to another
2. Pass data from one page to another
Passing Control between Pages
• <jsp:forward> action tag is used for forwarding a request or control to
the another resource (It can be a JSP, html or Servlet).
• Request can be forwarded with or without parameter.
• The <jsp:forward> action stops processing of one page and starts
processing the page specified by the page attribute instead, called the
target page.
• The control never returns to the original page.
• The target page has access to all information about the request,
including all request parameters.
• You can also add additional request parameters when you pass
control to another page by using <jsp:param> action elements
Cont …

Forwarding along with parameters:


<jsp:forward page="URL_of_Page" />
<jsp:param name=“ ” value=“ ” />
<jsp:param name=“ ” value=“ ” />
</jsp:forward>

Forwarding without parameters:


<jsp:forward page="URL_of_Page" />
index.jsp display.jsp
<html> <html>
<body> <body>
<jsp:forward page="display.jsp"> <h2>Hello this is a display.jsp Page</h2>
My name is: <%=request.getParameter("name")
<jsp:param name="name" %><br>
value="Chvrr" />
</body>
</jsp:forward> </html>
</body>
</html>
Pass data from one page to another
• Session object is used to pass the data from one jsp page to other .
setAttribute(String, object) :
• This method is used to save an object in session by assigning a unique
string to the object.
getAttribute(String name):
• The object stored by setAttribute method is fetched from session
using getAttribute method.
index.html one.jsp two.jsp
<html> <html>
<html>
<body> <body> <body>
<form action="one.jsp"> <%
<%
Name: <input type="text" String
String
name="name"> NAME=request.getParameter("name");
name=(String)session.getAttribute("SES
String AGE=request.getParameter("age"); _NAME");
Age:<input type="text"
name="age"/> session.setAttribute("SES_NAME",NAME); String
age=(String)session.getAttribute("SES_A
<input type="submit" value="Go"/> session.setAttribute("SES_AGE",AGE); GE");
</form> %> %>
</body> <jsp:forward page="two.jsp"/> <h1><%="name is:"+name %></h1>
</html> </body> <h1><%="age is:"+age%></h1>
</html> </body>
</html>
JSP application design with JDBC
Signup.html <tr>
<html> <td>email</td><td><input type="text"
<body bgcolor=pink> name="email"/><td>
<table align=center> </tr>
<form method="POST" action="Signupjsp.jsp"> <tr>
<tr> <td>mobile</td><td><input type="text"
name="mobile"/></td>
<td>Name</td><td><input type="text"
name="name"/></td> </tr>
</tr> <tr>
<tr> <td></td><td><input type="submit"
value="submit"/></td>
<td>UserName</td><td><input type="text"
name="uname"/></td> </tr>
</tr><tr> </table>
<td>Password</td><td><input </form>
type="password" name="pword"/><td> </body></html>
</tr>
Signup.jsp
<html> try{
<body> Class.forName("com.mysql.jdbc.Driver");
<table> Connection con=DriverManager.getConnection
("jdbc:mysql://localhost/IIICSE","root","root");
<%@ page import="java.util.*" %>
<%@ page import="java.sql.*;" %> Statement stmt=con.createStatement();
<%@ page import="java.io.*;" %> int i=stmt.executeUpdate(
"insert into signup values('"+name+"','"+uname+"',"
<%
+ "'"+pass+"','"+email+"',"+mobile+")");
response.setContentType("text/html"); if(i>0)
String name=request.getParameter("name"); response.sendRedirect("login.html");
String uname=request.getParameter("uname");
else
String pass=request.getParameter("pword"); out.print("Insert Unsuccessful");
String email=request.getParameter("email"); }
long mobile=Long.parseLong catch (Exception e) {
out.print(e);
(request.getParameter("mobile")); }
out.close();
Login.html
<html>
<body bgcolor=pink>
<table align=center>
<form method="POST" action="loginjsp.jsp">
<td>UserName</td><td><input type="text" name="uname"/></td>
</tr>
<tr>
<td>Password</td><td><input type="password" name="pword"/><td>
</tr>
<tr>
<td></td><td><input type="submit" value="Login"/></td>
</tr>
</table>
</form>
</body>
</html>
login.jsp
<html> PreparedStatement ps= con.prepareStatement("Select
<body> uname,password from signup where uname=? and
<table> password=?");
ps.setString(1, uname);
<%@ page import="java.util.*" %>
ps.setString(2, pass);
<%@ page import="java.sql.*" %> ResultSet rs=ps.executeQuery();
<%@ page import="java.io.*;" %> if (rs.next()) {
response.sendRedirect("home.html");
<%
}
response.setContentType("text/html"); else {
String uname=request.getParameter("uname"); response.sendRedirect("login.html");
String pass=request.getParameter("pword");
}
try{ }
Class.forName("com.mysql.jdbc.Driver"); catch(Exception e) {
Connection out.print(e);
con=DriverManager.getConnection("jdbc:mys }
ql://localhost/IIICSE","root","root"); %>
JSP program to store employee details sent from registration form in to database table.

emp.html <td>phno:</td>
<html> <td><input type="text"name="ephno"/></td>
<body> </tr>
<h3><center>Employee Registration <tr>
Form</center></h3> <td>Address:</td>
<form method="POST“ <td><input type="text"name="eaddress"/></td>
action="http://localhost:8080/employee/employee </tr>
"> <tr>
<table align="center"> <td>email:</td>
<td><input type="text"name="email"/></td>
<tr> </tr>
<td>Eid:</td> <tr>
<td>Salary:</td>
<td><input type="text"name="eid"/></td>
<td><input type="text"name="esalary"/></td>
</tr> </tr>
<tr> <tr>
<td></td><td><input type="submit" value="submit"/></td>
<td>Ename:</td>
<td><input type="reset" value="Reset"/></td></tr>
<td><input type="text"name="ename"/></td> </table></form></body></html>
</tr> <tr>
emp.jsp
import java.io.*; PreparedStatement ps=con.prepareStatement("insert into employee
import java.util.*; values(?,?,?,?,?,?)");
import java.sql.*; ps.setString(1,eid);
import javax.servlet.*; ps.setString(2,ename);
import javax.servlet.http.*; ps.setString(3,ephno);
public class employee extends HttpServlet ps.setString(4,eaddress);
{ ps.setString(5,email);
public void doPost(HttpServletRequest ps.setString(6,esalary);
request,HttpServletResponse response)throws int i=ps.executeUpdate();
IOException,ServletException if(i>0)
{ {
response.setContentType("text/html");
PrintWriter out=response.getWriter(); response.sendRedirect("employeesalary.html");
String eid=request.getParameter("eid"); }
String else
ename=request.getParameter("ename"); {
String out.println("Not
ephno=request.getParameter("ephno"); inserted");
String eaddress=request.getParameter("eaddress");
String email=request.getParameter("email"); }
String }
esalary=request.getParameter("esalary"); catch(Exception e)
try {
{ } }}
JSP Application Design with MVC.
• Reenskaug formulated the model–view–controller (MVC) pattern for
graphical user interface (GUI) software design in 1979 while visiting
the Xerox Palo Alto Research Center (PARC)
• This model has since been used for GUI applications developed in all
popular programming languages.
• MVC is an architecture that separates business logic, presentation and
data
• In MVC, M stands for Model, V stands for View,C stands for controller.
• MVC is a systematic way to use the application where the flow starts
from the view layer, where the request is raised and processed in
controller layer and sent to model layer to insert data and get back the
success or failure message.
Model Layer
• This is the data layer which consists of the business logic of the
system.
• It consists of all the data of the application.
• It consists of JavaBeans, EJB, etc. into it.
• It consists of classes which have the connection to the database.
• The controller connects with model and fetches the data and
sends to the view layer.
• The model connects with the database as well and stores the
data into a database which is connected to it.
View Layer
• This is a presentation layer.
• It consists of HTML, JSP, etc. into it.
• It normally presents the UI of the application.
• It is used to display the data which is fetched from the controller
which in turn fetching data from model layer classes.
• This view layer shows the data on UI of the application.
Controller Layer:

• It acts as an interface between View and Model.


• It intercepts all the requests which are coming from the view
layer.
• It receives the requests from the view layer and processes the
requests and does the necessary validation for the request.
• This requests is further sent to model layer for data processing,
and once the request is processed, it sends back to the controller
with required information and displayed accordingly by the view.
MVC roles in a pure JSP scenario
Java Beans
• A JavaBean is a specially constructed Java class written in the Java
• It contains the getter and setter methods
• Java Beans are reusable components.
• It is used to separate Business logic from the Presentation logic
Following are the unique characteristics that distinguish a JavaBean
from other Java classes −
• It provides a default, no-argument constructor.
• It should be serializable and which can implement
the Serializable interface.
• It should provide methods to set and get the values of the properties,
known as getter and setter methods.
Index.html(view)
<html>
<body bgcolor="orange">
<form method="POST" action="jspbean.jsp">
<table>
<tr><td>ID</td><td> <input type="text" name="msgid"> </td></tr>
<tr><td>Message</td><td> <input type="text" name ="message"> </td></tr>
<tr><td></td><td><input type = "submit" value="Submit"> </td></tr>
</table>
</form>
</body>
</html>
jspbean.jsp(Controller)
<%@ page language="Java" import="java.sql.*" %>
<html>
<body>
<%
int msgid=Integer.parseInt(request.getParameter("msgid"));
String message=request.getParameter("message");
%>
<h1>JSP using JavaBeans example</h1>
<jsp:useBean id="sample" class="myexample.bean" scope="page">
<jsp:setProperty name="sample" property="*"/>
</jsp:useBean>
<%sample.insert();%>
</body>
</html>
bean.java(Model)
package myexample; catch(Exception e){ public String getmessage()
import java.io.*; System.out.println("Exception
is ;"+e); {
import java.sql.*; } } return (this.message);
public class bean public void setmsgid(int msgid) }
{ { public void insert()
private int msgid; this.msgid = msgid; {
private String message; } try
private Connection con=null; public int getmsgid() {
private ResultSet rs= null; { String sql = "insert into message(id,message)
private Statement stmt= null; return (this.msgid); values('"+msgid+"','"+message+"')";

public bean() } Statement stmt= con.createStatement();

{ public void setmessage(String stmt.executeUpdate (sql);

try { message) stmt.close ();

Class.forName("com.mysql.jdbc.Driver"); { }catch(Exception e){

con=DriverManager.getConnection("jdbc this.message = message; System.out.println("Exception is ;"+e);


:mysql://localhost/ } } }}
IIICSE","root","root");
}

You might also like