WT Unit-V

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 63

UNIT-5

JSP(Java Server Pages)


JSP vs Servlets
• Similarities
– Provides identical results to
end user.
– JSP is an extension of
servlets.
– Provides similar API
support.
• Differences
– Servlets: “HTML embedded in Java
Code”
HTML code inaccessible to Graphics
designer
But accessible to Programmer.
– JSP: “Java Code embedded in HTML”
HTML code accessible to Graphic Designer
Java code accessible to Programmer.
– Jsp allows code update without
restarting the server.
– Eliminates redundant code.
The Anatomy of a JSP Page

• A JSP page is simply a regular web page with


JSP elements for generating the parts that
differ for each request
• Everything in the page that isn't a JSP element is
called template text.
• template text can be any text: HTML, WML, XML,
or even plain text
• Template text is always passed straight through to the
browser
• When a JSP page request is processed,
– the template text and dynamic content generated by the JSP
elements are merged, and the result is sent as the response
to the browser
JSP Processing

• the web server needs a JSP container to process JSP pages.

• The JSP container is responsible for intercepting requests for JSP pages.

• To process all JSP elements in the page, the container first turns the JSP
page into a servlet known as the JSP page implementation class
• all template text is converted to println( ) statements and all JSP elements
are converted to Java code that implements the corresponding dynamic
behavior.
• The container then compiles the servlet class.
• all template text is converted to println( ) statements and all
JSP elements are converted to Java code that implements the
corresponding dynamic behavior

• Converting the JSP page to a servlet and compiling the servlet


form the translation phase.
• The JSP container initiates the translation phase for a page
automatically when it receives the first request for the page.

• Since the translation phase takes a bit of time, the first user to
request a JSP page notices a slight delay.
• The translation phase can also be initiated explicitly; this is
referred to as precompilation of a JSP page
• request processing phase
• The JSP container is also responsible for invoking the
JSP page implementation class (the generated servlet)
to process each request and generate the response.

• As long as the JSP page remains unchanged, any


subsequent request goes straight to the request
processing phase

• When the JSP page is modified, it goes through the


translation phase again before entering the request
processing phase.
• a servlet container and a JSP container--are often
combined in one package under the name web
container
• a JSP page inherits all the advantages of a servlet:
– platform and vendor independence
– integration
– efficiency
– scalability
– robustness
– and security
JSP life cycle
• _jspInit()
• _jspDestroy()
• _jspService( request, response )

_jspService(request,
_jspInit() _jspDestroy()
response)
Initialise JSP Invoked by
Handle Requests:
Invoked only once container
invoked
to cleanup
for every request
• Contract between the JSP engine and JSP
– _jspInit() Corresponds to servlet init(), but has no parameters (use
config implicit object to obtain information regarding environment)

– _jspService() The main processing method; all Java code belongs to


this method by default (if not contained in another method), but it is
not explicitly declared in a JSP document

– _jspDestroy() Corresponds to the servlet destroy() method and is


called just before the generated servlet is destroyed
JSP Elements

• Three different elements are used in


constructing JSPs
– Scripting Elements
– Directives
– Actions
Scripting Elements
• There are three kinds of scripting
elements
– Declarations
– Scriptlets
– Expressions
Declarations
• Declarations are used to define methods & instance variables
• Do not produce any output that is sent to client
• Embedded in <%! and %> delimiters
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>

• The functions and variables defined are available to the JSP Page as well as to the
servlet in which it is compiled
Scriptlets

• Used to embed java code in JSP pages.


– Contents of JSP go into _JSPpageservice() method
– Code should compile with syntactical and semantic constuct of java
– Embedded in <% and %> delimiters
Example:
<%
int x = 5;
int y = 7;
int z = x + y;
%>
Index.html

<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
Welcome.jsp

<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</html>
Expressions
• Used to write dynamic content back to the browser.
• If the output of expression is Java primitive the value is printed back to the
browser
• Embedded in <%= and %> delimiters
• Example:
– <%= new java.util.Date() %>

– I

Index.html
Welcme.jsp
<html>
<html>
<body>
<body>
<form action="welcome.jsp">
<%= "Welcome
<input type="text" name="uname"><br/>
"+request.getParameter("uname") %>
<input type="submit" value="go">
</body>
</form>
</html>
</body>
</html>
JSP Implicit Objects
• request: HttpServletRequest
– Reference to the current request
• response: HttpServletResponse
– Response to the request
• session: HttpSession
– session associated with current request
• application: ServletContext
– Servlet context to which a page belongs
• pageContext: PageContext
– Object to access request, response, session and application associated with a page
• config: ServletConfig
– Servlet configuration for the page
• out: JspWriter
– Object that writes to the response output stream
• page: Object
– instance of the page implementation class (this)
• exception: Throwable
– Available with JSP pages which are error pages
Index.html

<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

welcome.jsp
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
JSP Initialization and Context Parameters
web.xml

<web-app>

<servlet>
<servlet-name>init</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>

<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>

</servlet>

<servlet-mapping>
<servlet-name>init</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

<context-param>
<param-name>url</param-name>
<param-value>jdbc:odbc:dbname</param-value>
</context-param>
</web-app>
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
===============

<%

out.print("Welcome "+request.getParameter("uname"));

String driver=config.getInitParameter("dname");
out.print("driver name is="+driver);

String url=config.getInitParameter(“url");
out.print("driver name is="+driver);

%>
<html>
<body>
<form action="welcome.jsp"> <html>
<input type="text" name="uname"> <body>
<input type="submit" value="go"><br/> <%
</form>
</body> String
</html> name=(String)session.getAttribute("user");
out.print("Hello "+name);
============================
<html> %>
<body> </body>
<% </html>

String name=request.getParameter("uname");
out.print("Welcome "+name);

session.setAttribute("user",name);

<a href="second.jsp">second jsp page</a>

%>
</body>
</html>
• In JSP, pageContext is an implicit object of type
PageContext class.
• The pageContext object can be used to set,get or
remove attribute from one of the following
scopes:
– page
– request
– session
– application
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body> <html>
<body>
</html>
<%

<html> String
<body> name=(String)pageContext.getAttribute("us
er",PageContext.SESSION_SCOPE);
<%
out.print("Hello "+name);

String name=request.getParameter("uname"); %>


out.print("Welcome "+name); </body>
</html>
pageContext.setAttribute("user",name,PageCo
ntext.SESSION_SCOPE);

<a href="second.jsp">second jsp page</a>

%>
</body>
</html>
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:


– page directive
– include directive
– taglib directive

– Syntax:
<%@ directive attribute="value" %>
JSP page directive
• The page directive defines attributes that apply to an entire JSP page
• Syntax:
– <%@ page attribute="value" %>
• Attributes of JSP page directive
– import
• Declares the packages and classes that need to be imported for using in the java
code
– <%@ page import="java.util.Date" %>
– Today is: <%= new Date() %>

– contentType
• Defines MIME type for the output response
• <%@ page contentType=application/msword %>
– extends
• Declares the class which the servlet compiled from JSP needs to extend
– info
• String returned by the getServletInfo() of the compiled servlet
<%@ page info=“Created by rajashekar" %>
– buffer
• defines buffer size of the jsp in kilobytes
• <%@ page buffer="16kb" %>
• language
• Defines server side scripting language
• isThreadSafe
• If false the compiled servlet implements SingleThreadModel interface
• <%@ page isThreadSafe="false" %>
• autoFlush
• When true the buffer is flushed when max buffer size is reached
• <% @ page autoFlush="true/false" %>

• session
• JSP page creates session by default.
• Boolean which says if the session implicit variable is allowed or not
• <%@ page session="true/false"%>
• errorPage

• Defines the relative URI of web resource to which the response should be
forwarded in case of an exception
• <%@ page errorPage="myerrorpage.jsp" %>

• isErrorPage
• True for JSP pages that are defined as error pages
<%@ page isErrorPage="true" %>

Sorry an exception occured!<br/>


The exception is: <%= exception %>
<html>
<body>

<%@ page
errorPage="myerrorpage.jsp" %>

<%= 100/0 %>

</body>
</html>
• In JSP, exception is an implicit object of type java.lang.Throwable class.
• This object can be used to print the exception.
• But it can only be used in error pages.

myerrorpage.jsp

<%@ page isErrorPage="true" %>


<html>
<body>
Sorry following exception occured:<%= exception %>
</body>
</html>
Jsp Include Directive
• The include directive is used to include the contents of any resource it may
be jsp file, html file or text file

• The include directive includes the original content of the included resource
at page translation time

• Advantage: Code Reusability


• Syntax: <%@ include file="resourceName" %
<html>
<body>
<%@ include file="header.html" %>

Today is: <%= java.util.Calendar.getInstance().getTime() %>


<%@ include file=“footer.html" %>
</body>
</html>
JSP Taglib directive

• The JSP taglib directive is used to define a tag library that defines many
tags.
• used to import custom actions defined in tag libraries

• We use the TLD (Tag Library Descriptor) file to define the tags.
• Syntax:
– <
%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
JSP Action Tags
• There are many JSP action tags or elements.

• Each JSP action tag is used to perform some specific tasks.

• The action tags are used to control the flow between pages and to use Java
Bean.
• jsp:forward forwards the request and response to
another resource.

• jsp:include includes another resource.

• jsp:useBean creates or locates bean object.

• jsp:setProperty sets the value of property in bean object.

• jsp:getProperty prints the value of property of the bean.

• jsp:plugin embeds another components such as applet.

• jsp:param sets the parameter value. It is used in forward


and include mostly.
jsp:forward
• The jsp:forward action tag is used to forward the
request to another resource it may be jsp, html or
another resource.
• <jsp:forward page="relativeURL | <
%= expression %>" />
• <h2>this is index page</h2>
<jsp:forward page="printdate.jsp" >
<jsp:param name="name" value=“VJIT" />
</jsp:forward>

<
% out.print("Today is:"+java.util.Calendar.getIn
stance().getTime()); %>
<%= request.getParameter("name") %>
jsp:include
• The jsp:include action tag is used to include the content of
another resource it may be jsp, html or servlet.

• The jsp:include action tag includes the resource at request


time so it is better for dynamic pages

• The jsp:include tag can be used to include static as well as


dynamic pages.

<jsp:include page="relativeURL | <%= expression %>" />


JSP include directive JSP include action

includes resource at translation includes resource at request time.


time.

better for static pages. better for dynamic pages.

includes the original content in calls the include method.


the generated servlet.
jsp:useBean action tag

• The jsp:useBean action tag is used to locate or instantiate a


bean class

• If bean object of the Bean class is already created, it doesn't


create the bean depending on the scope.

<jsp:useBean id= "instanceName" scope= "page | request | session | ap


plication"
class= "packageName.className" type= "packageName.className"
beanName="packageName.className | <%= expression >" >
</jsp:useBean>
• id: is used to identify the bean in the specified scope

• scope: represents the scope of the bean


– page: specifies that you can use this bean within the JSP page.
• The default scope is page.
– request: specifies that you can use this bean from any JSP page that processes the same
request.
• It has wider scope than page.
– session: specifies that you can use this bean from any JSP page in the same session whether
processes the same request or not.
• It has wider scope than request.
– application: specifies that you can use this bean from any JSP page in the same application.
• It has wider scope than session.
• class: instantiates the specified bean class

• type: provides the bean a data type if the bean already exists in the scope. It is
mainly used with class or beanName attribute

• beanName: instantiates the bean using the java.beans.Beans.instantiate() method.


• The setProperty and getProperty action tags
are used for developing web application with
Java Bean

• In web development, bean class is mostly used


because it is a reusable software component
that represents data
jsp:setProperty
• The jsp:setProperty action tag sets a property
value or values in a bean using the setter method.

<jsp:setProperty name="instanceOfBean" property= "*" |


property="propertyName" param="parameterName" |
property="propertyName" value="{ string | <
%= expression %>}"
/>
• <jsp:setProperty name="bean" property="*" /
>

• <jsp:setProperty name="bean" property="use


rname" />
• <jsp:setProperty name="bean" property="use
rname" value=“Rajashekar" />
jsp:getProperty

• The jsp:getProperty action tag returns the value of the property


• Syntax:
– <jsp:getProperty name="instanceOfBean" property="prope
rtyName" />
• Example:
– <jsp:getProperty name="obj" property="name" />
<html>
<body>
<form name="save" action="stud_bean.jsp" method="post">
<table align="center">
<tr><td>Name :</td><td><input type="text" name="name" > </td></tr>
<tr><td>ID :</td><td><input type="text" name="id" > </td></tr>
<tr><td>Branch :</td><td><input type="text" name="branch" > </td></tr>
<tr><td colspan=2 align="Center"><input type="submit" value="Save" >
</td></tr>
</table>
</form>
</body>
</html>
package students;
public String getName()
public class UserBean {
{ return this.name;
private String name; }
private String id; public String getId()
private String branch; {
return this.id;
public void setName(String name) }
{ public String getbranch()
this.name=name; {
} return this.branch;
public void setId(String id) }
{ }
this.id=id;
}
public void setBranch(String branch)
{
this.branch=branch;
}
<jsp:useBean id="b1" class="students.UserBean" />
<jsp:setProperty name="b1" property="*" />

Student Details : <br />

Name: <jsp:getProperty name="b1" property="name" /><br />


ID : <jsp:getProperty name="b1" property="id" /><br />
Branch : <jsp:getProperty name="b1" property="branch"
/><br />
MVC
MVC in JSP
• MVC stands for Model View and Controller.
• It is a design pattern that separates the business logic,
presentation logic and data.

• Model represents the state of the application i.e. data. It can


also have business logic.

• View represents the presentation i.e. UI(User Interface).

• Controller acts as an interface between View and Model.


– Controller intercepts all the incoming requests.
MODEL

● This is the data layer which consists of the business logic of the
system.
● It consists of all the data of the application
● It also represents the state of the application.
● 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.
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.
• Advantages

– Navigation Control is centralized


– Easy to maintain the large application
Session Tracking in JSP
• In JSP, by default a session is automatically created for the request
if one does not exist.

• So if your starting page is a JSP, a session would have already been


created when you get the first request.

• 1. Setting Session :
• use session.setAttribute("ATTRIBUTE NAME","ATTRIBUTE VALUE")
method for setting value in session.

• 2. Retrieving values from session attribute :


• To retrieve value from session attribute we need to use following
method. session.getAttribute("attribute name");
<html>
<head>
<title>Session Management Example</title>
</head>
<body>
<form method="post" action="firstpage.jsp">
<font size=5>Enter your name<input type="text"
name="name"></font><br><br>
<font size=5>Enter your password<input type="password"
name="password">
</font><br><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
<%
String name = request.getParameter("name");
String password = request.getParameter("password");
if (name.equals(“Rajasheakr") && password.equals(“Parupati")) {
session.setAttribute("username", name);
response.sendRedirect("secondpage.jsp");
}
else {
response.sendRedirect("index.jsp");
}
%>
<html>
<head>
<title>Welcome in the program of
session</title>
</head>
<body>
<font size = 5>Hello <%=
session.getAttribute("username") %></font>
</body>
</html>
Session Tracking using Cookies
• Creating a Cookie object
– Cookie c = new Cookie("key","value");
• Setting the maximum age
– c.setMaxAge(60*60*24);
• Sending the Cookie into the HTTP response
headers
– response.addCookie(cookie);
• Reading Cookies with JSP
• Reading Cookies with JSP
– To read cookies, you need to create an array of Cookie
objects by calling the getCookies( ) method
of HttpServletRequest
– use getName() and getValue() methods to access each
cookie and associated value
<html>
<body>

<form action = "main.jsp" method = "GET">


First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>

</body>
</html>
<%
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));

// Add both the cookies in the response header.


response.addCookie( firstName );
response.addCookie( lastName );
%>
cookies = request.getCookies();

if( cookies != null ) {


out.println("<h2> Found Cookies Name and
Value</h2>");

<html> for (int i = 0; i < cookies.length; i++) {


<head> cookie = cookies[i];
<title>Reading Cookies</title> out.print("Name : " + cookie.getName( ) + ", ");
</head> out.print("Value: " + cookie.getValue( )+" <br/>");
}
<body> } else {
<center> out.println("<h2>No cookies founds</h2>");
<h1>Reading Cookies</h1> }
</center> %>
<% </body>
Cookie cookie = null;
Cookie[] cookies = null; </html>

You might also like