Sunteți pe pagina 1din 40

JSP

Java Server Pages


JSP
• Servlets are pure Java programs. They introduce dynamism
into web pages by using programmatic content.
• JSP technology is an extension/wrapper over the Java
servlet technology.
• JSP are text based documents.
• Java Server Pages are HTML pages embedded with
snippets of Java code.
• We will focus only on JSP since it subsumes the servlet
technology.
• Two major components of JSP:
– Static content: provided by HTML or XML
– Dynamic content: generated by JSP tags and scriplets
written in Java language to encapsulate the application
logic.
JSP Processing
What Really happens to your JSP code?
This JSP:
<html>
<body>
<%! int count = 0; %>
The Page count is now :
<%= ++count %>
</body>
</html>
Becomes this servlet:
public class basicCounter_jsp extends SomeSpecialHttpServlet
{
public void _jspservice(HttpServletRequest req,HttpServletResponse resp)
throws java.io.IOException , ServletException
{
PrintWriter out = response.getWriter();
response.setContentType(“text/html”);
out.write(“<html><body>”);
int count = 0;
out.write(“The page count is now:”);
out.print(++count);
out.write(“</body></html>”);
}
}
Anatomy of a JSP page
JSP page
• A JSP page is a page created by the web developer that
includes JSP technology-specific tags, declarations, and
possibly scriptlets, in combination with other static HTML
or XML tags.
• A JSP page has the extension .jsp; this signals to the web
server that the JSP engine will process elements on this
page.
• Pages built using JSP technology are typically
implemented using a translation phase that is performed
once, the first time the page is called. The page is compiled
into a Java Servlet class and remains in server memory, so
subsequent calls to the page have very fast response times.
JSP Lifecycle
Servlet from JSP

Init Event jspInit()

Request
Response
jspService()

Destroy Event jspDestroy()


Life cycle
Once a JSP is translated to a servlet , the container invokes the
following life cycle methods on the servlet , that are defined in
the javax.servlet.jsp.JspPage interface:
1. jspInit() : This method is invoked at the time when the servlet
is initialized.
2. _jspService() : This method is invoked when request for the JSP
page is received.
3. jspDestroy() : This method is invoked before the servlet is
removed from the service.
JSP scripting Elements
Scripting Element Example
Comment <%-- comment --%>
Directive <%@ directive %>
Declaration <%! declarations %>
Scriptlet <% scriplets %>
Expression <%= expression %>
Directive tag
• Page: provder information about page, such as scripting language
that is used, content type, or buffer size
• Include – used to include the content of external files
• Taglib – used to import custom actions defined in tag libraries
1. page: <%@ page ... %>
defines page dependent properties such as language, session,
errorPage,flush etc.
2.include :<%@ include ... %>
defines file to be included.
3.Taglib :<%@ taglib ... %>
declares tag library used in the page
Ex: <%@ taglib prefix="sql"
uri="http://java.sun.com/jsp/jstl/sql" %>
Page directive
• Different directives are (cont’d.)
– autoFlush:When true the buffer is flushed when max buffer size is
reached (if set to false an exception is thrown when buffer exceeds the
limit)
– isThreadSafe: (default true) If false the compiled servlet implements
SingleThreadModel interface
– Info: String returned by the getServletInfo() of the compiled servlet
– errorPage: Defines the relative URI of web resource to which the
response should be forwarded in case of an exception
– contentType: (Default text/html) Defines MIME type for the output
response
– isErrorPage: True for JSP pages that are defined as error pages
– pageEncoding: Defines the character encoding for the jsp page
example
<%@
page language=“java”
buffer=“10kb”
autoflush=“true”
errorPage=“/error.jsp”
import=“java.util.*, javax.sql.RowSet”
%>
• Declaration: variable declaration
<%! int age = 56 %>
• Directive: ex: import classes
<%@ page import = “java.util.*” %>
• Scriplet: Java code
<%
out.println(“welcome”);
%>
• Expression: regular expression using variables and
constants
<%= a+b %>
• Comments
<%-- this is first jsp page--%>
Date.jsp
<html>
<body>
<%= new java.util.Date () %>
</body>
</html>
Include.jsp
<html>
<body>
<h4> Today’s Date is :
<jsp:include page=“Date.jsp” flush=“true” /> </h4>
<%
out.println(“<h4> The ouput of the file Date.jsp is shown
above </h3>”);
%>
</body>
</html>
Java Implicit Objects
Scope
• Implicit objects provide access to server side objects
– e.g. request, response, session etc.
• There are four scopes of the objects
– Page: Objects can only be accessed in the page where
they are referenced
– Request: Objects can be accessed within all pages that
serve the current request.
(Including the pages that are forwarded to and included in
the original jsp page)
– Session: Objects can be accessed within the JSP pages for
which the objects are defined
– Application: Objects can be accessed by all JSP pages in a
given context
Java Implicit Objects
List
1. request: Reference to the current request
2. response: Response to the request
3. session: session associated woth current request
4. application: Servlet context to which a page belongs
5. pageContext: Object to access request, response,
session and application associated with a page
6. config: Servlet configuration for the page
7. out: Object that writes to the response output stream
8. page: instance of the page implementation class (this)
9. exception: Available with JSP pages which are error
pages
Java Implicit Objects
Example
<html> <p>
<head> Storing a string to the application...<br>
<title>Implicit Objects</title> <% application.setAttribute("name", "Meeraj"); %>
</head> Retrieving the string from application...<br>
<body style="font-family:verdana;font-size:10pt"> <b>Name:</b>
<p> <%= application.getAttribute("name") %>
Using Request parameters...<br> </p>
<b>Name:</b> <%= request.getParameter("name") %> <p>
</p> Storing a string to the page context...<br>
<p> <% pageContext.setAttribute("name", "Meeraj"); %>
<% out.println("This is printed using the out implicit Retrieving the string from page context...</br>
variable"); %>
<b>Name:</b>
</p>
<%= pageContext.getAttribute("name") %>
<p>
</p>
Storing a string to the session...<br>
</body>
<% session.setAttribute("name", "Meeraj"); %>
</html>
Retrieving the string from session...<br>
<b>Name:</b> <%= session.getAttribute("name") %>
</p>
JSP Actions
• Processed during the request processing phase.
– As opposed to JSP directives which are processed during translation
• Standard actions should be supported by J2EE compliant web servers
• Custom actions can be created using tag libraries
• There are three main roles of the action tags:
Enable the use of the server side Javabeans.
Transfer control between pages
browser independent support for applets
The different actions are
1. <jsp:useBean>
2. <jsp:setProperty>
3. <jsp:getProperty>
4. <jsp:param>
5. <jsp:include>
6. <jsp:forward>
7. <jsp:plugin>
JSP Actions
Include
• Include action used for including resources in a JSP page
– Include directive includes resources in a JSP page at translation time
– Include action includes response of a resource into the response of
the JSP page
– Same as including resources using RequestDispatcher interface
– Changes in the included resource reflected while accessing the page.
– Normally used for including dynamic resources

• Example
– <jsp:include page=“inlcudedPage.jsp”>
– Includes the the output of includedPage.jsp into the page where this
is included.
JSP Actions
Forward
• Forwards the response to other web specification resources
– Same as forwarding to resources using RequestDispatcher interface

• Forwarded only when content is not committed to other web


application resources
– Otherwise an IllegalStateException is thrown
– Can be avoided by setting a high buffer size for the forwarding jsp
page

• Example
– <jsp:forward page=“Forwarded.html”>
– Forwards the request to Forwarded.html
JSP Actions
Param
• Used in conjunction with Include & Forward actions to
include additional request parameters to the included or
forwarded resource
• Example
<jsp:forward page=“Param2.jsp”>
<jsp:param name=“FirstName” value=“Sanjay”>
</jsp:forward>
– This will result in the forwarded resource having an additional
parameter FirstName with a value of Sanjay
JSP Actions
useBean
• Creates or finds a Java object with the defined scope.
– Object is also available in the current JSP as a scripting variable

• Syntax:
<jsp:useBean id=“name”
scope=“page | request | session | application”
class=“className” type=“typeName” |
bean=“beanName” type=“typeName” |
type=“typeName” />
– At least one of the type and class attributes must be present
– We can’t specify values for bith the class and bean name.

• Example
<jsp:useBean id=“myName” scope=“request” class=“java.lang.String”>
<% firstName=“Sanjay”; %>
</jsp:useBean>
JSP Actions
get/setProperty
• getProperty is used in conjunction with useBean to get property values of
the bean defined by the useBean action
• Example (getProperty)
– <jsp:getProperty name=“myBean” property=“firstName” />
– Name corresponds to the id value in the useBean
– Property refers to the name of the bean property

• setProperty is used to set bean properties


• Example (setProperty)
– <jsp:setProperty name=“myBean” property=“firstName” value=“Sanjay”/>
– Sets the name property of myBean to SanjayExample (setProperty)
– <jsp:setProperty name=“myBean” property=“firstName” param=“fname”/>
– Sets the name property of myBean to the request parameter fname
– <jsp:setProperty name=“myBean” property=“*”>
– Sets property to the corresponding value in request
JSP Actions
plugIn
• Enables the JSP container to render appropriate HTML (based on the
browser type) to:
– Initiate the download of the Java plugin
– Execution of the specified applet or bean
• plugIn standard action allows the applet to be embedded in a browser
neutral fashion
• Example
<jsp: plugin type=“applet” code=“MyApplet.class” codebase=“/”>
<jsp:params>
<jsp:param name=“myParam” value=“122”/>
</jsp:params>
<jsp:fallback><b>Unable to load applet</b></jsp:fallback>
</jsp:plugin>
JavaBean
• A Javabeans is a special type of the class that has a number
of methods.
• A JavaBeans component is a Java class with the following
features:
• A no-argument constructor.
• Properties defined with accessors and mutators(getter and
setter method).
• Class must not define any public instance variables.
• The class must implement
the java.io.Serializable interface
Example program
Package pack;
import java.io.Serializable;
public class StudentBean implements Serializable{
private String name;
private int roll;
public StudentBean() { this.name="";
this.roll=""; }
public void setName(String name) {
this.name = name; }
public String getName() { return name; }
public int getRoll() { return roll; }
public void setRoll(int roll) { this.roll = roll; }
Sample code
Login.jsp
<body>
<h2>Using Java Beans with JSP </h2>

<form method="get"
action="http://localhost:7001/examplesWebApp/Receive.jsp">

Enter User Name <input type="text" name="user"> <br>


Enter Password <input type="password" name="pass"> <br>
<input type="submit">

</form>
</body>
Receive.jsp
<body>
<jsp:useBean id="snr" class="pack.ValidateBean" />

<jsp:setProperty name="snr" property="user" />


<jsp:setProperty name="snr" property="pass" />

You entered user name as <jsp:getProperty name="snr" property="user" /> <br>

You entered user password as <jsp:getProperty name="snr" property="pass" />


<br>

<br>

You are a : <%= snr.validate("Rao", "java") %> user. <br>

<b>Thank You</b>
</body>
Java bean code:
public void setPass(String pass)
package pack;
public class ValidateBean {
{ this.pass = pass;
String user; }
String pass; public String getPass( )
{
public ValidateBean( ) { } return pass;
}
public void setUser(String user)
public String validate(String s1,String s2)
{
{
this.user = user;
if(s1.equals(user) && s2.equals(pass))
}
return "VALID";
public String getUser( )
else
{
return "INVALID";
return user;
}
}
}
Session tracking
3)Hidden form fields - HTML hidden edit
boxes such as
<input type = “hidden” name=“user”
value=“ ---”>
4) Session objects – JSP Implicit Object
A session object uses a key / value combination to store
information.
To retrieve information from a session:
session.getValue(“msg”)
The return type of the method getValue is Object ,
so you will need to typecast to get the required value. If there
is not a session key with that name , null is returned.
To set a session key with a value,
session.putValue (“msg” , val)
//sample code
connecting to database in JSP
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1 import="java.sql.*"%>
<html>
<head>
<title> connecting to database in jsp</title>
</head>
<body>
<%
response.setContentType("text/html;charset=UTF-8");
try {
Class.forName("com.mysql.jdbc.Driver");
Cont..
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/cse",
"root",“root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next())
out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}
catch(Exception e){ out.println(e);}

%>
</body>
</html>
The end

S-ar putea să vă placă și