Vous êtes sur la page 1sur 22

Introduction to JSP.....................................................................................................................................

2
What is jsp?............................................................................................................................................2
Why use JSP?.........................................................................................................................................2
JSP Architecture.........................................................................................................................................3
Steps required for a JSP request:............................................................................................................3
Setting up the JSP environment.............................................................................................................5
Using JSP tags ...........................................................................................................................................5
Declaration tag ( <%! %> ) ..................................................................................................................6
Expression tag ( <%= %>) ..................................................................................................................6
Directive tag ( <%@ directive ... %>)...................................................................................................6
Scriptlet tag ( <% ... %> ) .....................................................................................................................7
Example using scripting elements and Directive...................................................................................8
Implicit objects...........................................................................................................................................9
Actions.......................................................................................................................................................9
include....................................................................................................................................................9
UseBean...............................................................................................................................................10
Forward................................................................................................................................................11
Accessing database from JSP...................................................................................................................11
JSP Cookies Example...............................................................................................................................14
Working with jsp session.........................................................................................................................14
Comments and Character Quoting Conventions......................................................................................15
Jsp Expression Language ........................................................................................................................15
JSP Scopes................................................................................................................................................16
Page......................................................................................................................................................16
Request ................................................................................................................................................16
Application...........................................................................................................................................17
Example...................................................................................................................................................17
Custom error page....................................................................................................................................21

Agenda
Introduction to JSP
JSP Architecture
Using jsp tags
JSP Scriptlets
JSP Directives
The JSP page Directive
The JSP include Directive
JSP Declarations
Example Using Scripting Elements and Directives
Implicit Objects
● request
● response
● out
● application
● session
● config
● pageContext
● page
Actions
● The jsp:include Action
● The jsp:useBean Action
● The jsp:setProperty Action
● The jsp:getProperty Action
● The jsp:forward Action
Accessing database from JSP
JSP Cookies Example
Working with JSP Sessions
Comments and Character Quoting Conventions
CaseStudy-How to Design a OOPS Application
Hands-On Session

Introduction to JSP

What is jsp?
JavaServer Pages (JSP) technology is the Java platform technology provides a way to dynamically
generated web pages and simplifies the process of developing web-based applications.

Jsp is based on java , Object Oriented Language.

Jsp files are HTML files with special tag containing java source code that provides the dynamic
content.

JSP become a servlet.A servlet don't create. The container looks at your jsp , translates it into source
code, and compiles it into a java servlet class.

Why use JSP?


JSP is easy to learn and allows developers to quickly produce web sites and applications in an open and
standard way.

JSP is based on Java,an object-oriented language. JSP offers a robust platform for web development.

Main reasons to use JSP:


➢ Multi platform
➢ Component reuse by using Javabeans and EJB.
➢ Advantages of Java.
➢ You can take one JSP file and move it to another platform,web server or JSP Servlet engine.
JSP Architecture

Steps required for a JSP request:


1. The user goes to a web site made using JSP. The user goes to a JSP page (ending
with .jsp). The web browser makes the request via the Internet.
2. The JSP request gets sent to the Web server.
3. The Web server recognises that the file required is special (.jsp),therefore passes
the JSP file to the JSP Servlet Engine.
4. If the JSP file has been called the first time,the JSP file is parsed,otherwise go to
step 7.
5. The next step is to generate a special Servlet from the JSP file. All the HTML
required is converted to println statements.
6. The Servlet source code is compiled into a class.
7. The Servlet is instantiated,calling the init and service methods.
8. HTML from the Servlet output is sent via the Internet.
9. HTML results are displayed on the user's web browser.
Setting up the JSP environment
Before setting up the JSP environment,you must make sure you have the JDK.
Download the latest JDK
Set PATH & CLASSPATH
Download Tomcat
Set the TOMCAT_HOME
Example:
Set PATH=Installation directory of the java
Set CLASSPATH=set the java library files (jre&lib)
Set TOMCAT_HOME=installation directory of the Tomcat

Using JSP tags


There are five main tags:
1. Declaration tag
2. Expression tag
3. Directive tag
4. Scriptlet tag
5. Action tag
Declaration tag ( <%! %> )
This tag allows the developer to declare variables or methods.
Before the declaration you must have <%!
At the end of the declaration,the developer must have %>
Code placed in this tag must end in a semicolon ( ; ).

Declarations do not generate output so are used with JSP expressions or scriptlets.
For Example,

<%!
private int counter = 0 ;
private String get Account ( int accountNo) ;
%>

Expression tag ( <%= %>)


This tag allows the developer to embed any Java expression and is short for out.println().

A semicolon ( ; ) does not appear at the end of the code inside the tag.

For example,to show the current date and time.

Date : <%= new java.util.Date() %>

Note: Never end an expression with a semicolon.

Directive tag ( <%@ directive ... %>)


In the directives we can import packages, define error handling pages or the session information of the
JSP page.
A JSP directive gives special instructions to the container at page translation time.A JSP declaration is
always defined inside the class but outside the service method.Declarations are for static,instance
variable and method.Variables and functions defined in the declaratives are class level and can be used
anywhere in the JSP page.

There are three main types of directives:

1) page - processing information for this page.


2) Include - files to be included.
3)Tag library - tag library to be used in this page.

Package foo;
public class Counter{
public static int count;
public static int getCount()
{
count++;
return count;
}
}

Wrong
<% out.println(Counter.getCount()); %>

should be
<% out.println(foo.Counter.getCount()); %>

To import a single package:


<%@ page import=”foo.*” %>
<html>
<body>
the page count is
<%
out.println(counter.getCount());
%>
</body>
</html>

To import multiple packages


<%@ page import=”foo.*,java.util.*” %> -- use comma to seperate the package.

Scriptlet tag ( <% ... %> )


In this tag we can insert any amount of valid java code and these codes are placed in _jspService
method by the JSP engine.

Syntax of JSP directives is:


<%@directive attribute="value" %>
Where directive may be:
1. page: page is used to provide the information about it.
Example: <%@page language="java" %>

2. include: include is used to include a file in the JSP page.


Example: <%@ include file="/header.jsp" %>

3. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined
our own tags).
Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>

and attribute may be:


1. language="java"
This tells the server that the page is using the java language. Current JSP specification supports
only java language.
Example: <%@page language="java" %>

2. extends="mypackage.myclass"
This attribute is used when we want to extend any class. We can use comma(,) to import more
than one packages.
Example: <%@page language="java" import="java.sql.*,mypackage.myclass" %>

3. session="true"
When this value is true session data is available to the JSP page otherwise not. By default this
value is true.
Example: <%@page language="java" session="true" %>

4. errorPage="error.jsp"
errorPage is used to handle the un-handled exceptions in the page.
Example: <%@page language="java" session="true" errorPage="error.jsp" %>

5. contentType="text/html;charset=ISO-8859-1"
Use this attribute to set the mime type and character set of the JSP.
Example: <%@page language="java" session="true" contentType="text/html;charset=ISO-
8859-1" %>

Example using scripting elements and Directive


<%@ page language="java" %>
<html>
<head>
<title> test page</title>
</head>
<body>
<%!
int cnt=0;
private int getCount()
{
cnt++;
System.out.println("count========="+cnt);
return cnt;
}
%>

<%
String name=request.getParameter("username");
out.println("name========="+name);
%>

the page count is now: <%=getCount()%>


<form name="f" method="post" action="declare.jsp">
<table border="0"><tr><td>Name</td><td><input type="text" name="username">
</td></tr>
<tr><td colspan="2"><input type="submit" value="submit"></td></tr>
</table>
</form>

</body>
</html>

Implicit objects
Object Class or Interface Description
page jsp.HttpJspPage Page's servlet instance
config ServletConfig Servlet configuration information
pageContext jsp.pageContext Provides access to all the
namespaces associated with a JSP
page and access to several page
attributes
request http.HttpServletRequest Data included with the HTTP
Request
response http.HttpServletResponse HTTP Response data, e.g. cookies
out jsp.JspWriter Output stream for page context
session http.HttpSession User specific session data
application ServletContext Data shared by all application
pages

Actions
Action tag is used to transfer the control between pages and is also used to enable the use of
server side JavaBeans

The three that will be discussed here are:

• include
• forward
• useBean

include
Static resources should always be included using the JSP include directive.This is the compile
time include. Do note that you should always supply a relative URL for the file
attribute.
Difference between directive include and jsp include

<%@ include> : Used to include static resources during translation time.


jsp:include Used to include dynamic content or static content during runtime.

Syntax

<!--#include file="data.inc"--> or

<%@ include file="copyright.html" %>

<jsp:include path=”path”/>

UseBean
JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes.
You use tags to declare a bean and use to set value of the bean class and use to get value of the
bean class.

bean.java

package jsplearning;

public class bean {

public String username;

public String getUsername() {


return username;
}

public void setUsername(String username) {


this.username = username;
}

}
bean.jsp

<%@ page language="java" %>

<jsp:useBean id="beanname" class="jsplearning.bean" scope="page">


<jsp:setProperty name="beanname" property="username" value="deepa"/>
</jsp:useBean>

<h1>name=<jsp:getProperty name="beanname" property="username"/></h1>

get the user input

bean.java
package jsplearning;

public class bean {

public String username;


public String getUsername() {
return username;
}

public void setUsername(String username) {

this.username = username;
}

bean.jsp

<%@ page language="java" %>

<jsp:useBean id="beanname" class="jsplearning.bean" scope="page">


<jsp:setProperty name="beanname" property="username"/>
</jsp:useBean>

<h1>name=<jsp:getProperty name="beanname" property="username"/></h1>

<form name="f" method="post" action="bean.jsp">


<input type="text" name="username">
<input type="submit" value="submit">
</form>

Forward
It forwards the current request to another page.
Syxtax:
<jsp:forward page=”url”>
<jsp:param----/>
</jsp:forward>
You can also use the: <jsp:forward page="/newpage.jsp" /> Also note that you can only use
this before any output has been sent to the client. I beleve this is the case with the
response.sendRedirect() method as well.
If you want to pass any paramateres then you can pass using <jsp:forward
page="/servlet/login"> <jsp:param name="username" value="jsmith" /> </jsp:forward>>

Accessing database from JSP


<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ page language="Java" import="java.sql.*" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<jsp:useBean id="sampl" class="hello.mysql" scope="session"/>
<jsp:setProperty name="sampl" property="employid"/>

<html>
<head>
</head>

<body>
<form name="form1">

Emp ID: <input type="text" name ="employid"> <br><br><br>

<input type = "submit" value="Submit">

</form>
<table><tr><td>
<%
sampl.setConnection();

String emplyoid = request.getParameter("employid");


if (emplyoid != null) {
out.println("id="+ sampl.getEmployid());
sampl.insert1();

}
%>

</td></tr></table>
</body>
</html>
_______________________________

mysql.java
___________
package hello;
import java.sql.*;

import javax.servlet.http.*;

public class mysql {

public String employid;


public Connection con;
public ResultSet rs=null;
public PreparedStatement st=null;
public mysql()
{

}
public void setConnection()
{
try
{
Class.forName("org.gjt.mm.mysql.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/mysql",
"root", "");

}
catch(Exception e)
{
System.out.println("error="+e.getMessage());
}

public void setEmployid(String id)


{
employid=id;
}
public String getEmployid()
{
return employid;

public void insert1()


{

try{

String s1="insert into samp(employid) values('"+employid+"')";


System.out.println("s1="+s1);
st=con.prepareStatement(s1);
st.executeUpdate();

}
catch(Exception e)
{
System.out.println("error="+e.getMessage());

/* try
{
String s1="insert into samp(emplyid) values('"+employid+"')";
System.out.println("s1="+s1);
st=con.prepareStatement(s1);
st.executeUpdate();
}
catch(Exception e)
{
System.out.println("error="+e.getMessage());
}
*/

}
}

<%@ page import="java.sql.*" %>


<%
Connection ocon = null;
Class.forName("org.gjt.mm.mysql.Driver");
ocon = DriverManager.getConnection("jdbc:mysql://localhost/mysql", "root", "");
ResultSet rst=null;
Statement stmt=null;
stmt=ocon.createStatement();
rst=stmt.executeQuery("select * from user ");
while(rst.next()){
out.println(rst.getString(2));
}
%>

JSP Cookies Example

Working with jsp session


Comments and Character Quoting Conventions
There are a small number of special constructs you can use in various cases to insert comments or
characters that would otherwise be treated specially. Here's a summary:
Syntax Purpose
<%-- comment --%>
A JSP comment. Ignored by JSP-to-scriptlet translator. Any
embedded JSP scripting elements, directives, or actions are
ignored.
<!-- comment -->
An HTML comment. Passed through to resultant HTML. Any
embedded JSP scripting elements, directives, or actions are
executed normally.
<\% Used in template text (static HTML) where you really want
"<%".
%\>
Used in scripting elements where you really want "%>".

A single quote in an attribute that uses single quotes.


\' Remember, however, that you can use either single or double
quotes, and the other type of quote will then be a regular
character.
A double quote in an attribute that uses double quotes.
\" Remember, however, that you can use either single or double
quotes, and the other type of quote will then be a regular
character.
%\>
%> in an attribute.
<\%
<% in an attribute.

Jsp Expression Language


El expressions are always within curly braces, and prefixed with the dollar sign.

Syntax
${person.name}

Example

<%@ page contentType="text/html" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<html>
<body bgcolor=lightblue>
<form method=post>
NAME <input type=text name="text1"><br>
PLACE<input type=text name="text2"><br>
<input type=submit>
</form>
<!-- NAME:<c:out value="${param.text1}" /><br>
PLACE:<c:out value="${param.text2}" />-->
name:<c:out value="${param.text1}" />
place:<c:out value="${param.text2}" />

</body>
</html>

EL expression using bean

<%@ page language="java" errorPage="error.jsp"%>


<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<jsp:useBean id="beanname" class="jsplearning.bean" scope="page">
<jsp:setProperty name="beanname" property="username"/>
</jsp:useBean>

<h1>name=<jsp:getProperty name="beanname" property="username"/></h1>

<h1>El value= <c:out value="${beanname.username}"/></h1>


<form name="f" method="post" action="bean.jsp">
<input type="text" name="username">
<input type="submit" value="submit">
</form>

JSP Scopes
Page
Request
Session
Application

Page

Page Scope is the smallest scope. Accessible only in the page in which the object is created. Released
when the response is returned or the request forwarded. This is like making a “private variable” in
Java.

Request
Request scope is the next smallest scope, and is represented with the JSP's request object. All JSPs and
servlets that share a request share the request scope. For example, if I have a JSP that forwards to
another page, and that second page includes a third JSP page, then all three pages are in the same
request, and can share objects through the request scope. A special note here, is the
response.redirect(), will create a new request, unlike forwards and includes. Also note, a new
request is made every time the user gets a new page, be it by clicking a link, a button, or some
JavaScript call.

Session
Session scope is the next lowest scope, represented by an HttpSession object. All requests from the
same user are in the same session. Each user has his own session.

Application
Application scope objects are global objects and accessible to all jsp pages which lie in the same
application. All users share the same values of the application scope, as there is only one made for the
web application. If you have some static material that all users should be able to access, then put it in
the application. So application scope is usually best used for Read-Only data.

Example
Four files
Firstinclude.jsp
Secondinclude.jsp
Linked.jsp
Forward.jsp

Firstinclude.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="scopeVarPage" value="Page Value" scope="page" />
<c:set var="scopeVarRequest" value="Request Value" scope="request" />
<c:set var="scopeVarSession" value="Session Value" scope="session" />
<c:set var="scopeVarApplication" value="Application Value" scope="application" />

<body>
<h3>Main File: index.jsp</h3>

<table border="1">
<tr>
<th>Scoped Variable</th>

<th>Current Value</th>
</tr>

<tr>
<td>
<b>Page Scope</b>

(scopeVarPage)</td>

<td>&#160;
<c:out value="${scopeVarPage}" />
</td>
</tr>

<tr>
<td>
<b>Request Scope</b>

(scopeVarRequest)</td>
<td>&#160;
<c:out value="${scopeVarRequest}" />
</td>
</tr>

<tr>
<td>
<b>Session Scope</b>

(scopeVarSession)</td>

<td>&#160;
<c:out value="${scopeVarSession}" />
</td>
</tr>

<tr>
<td>
<b>Application Scope</b>

(applicationVarPage)</td>

<td>&#160;
<c:out value="${scopeVarApplication}" />
</td>
</tr>
</table>

<br />

<br /> <h3>Include another file

<jsp:include page="secondinclude.jsp" />


</h3>
<br />

<br /> <h3>Link to new page

<a href="linked.jsp">[Click Here to View: linked.jsp]</a>


</h3>

<h3>Forward to new page <jsp:forward page="forward.jsp"/>[Click Here to View:


linked.jsp]</a> </h3>

</body>
</html>

Secondinclude.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<table border="1">
<tr>
<th>Scoped Variable</th>

<th>Current Value</th>
</tr>

<tr>
<td>
<b>Page Scope</b>

(scopeVarPage)</td>

<td>&#160;
<c:out value="${scopeVarPage}" />
</td>
</tr>

<tr>
<td>
<b>Request Scope</b>

(scopeVarRequest)</td>

<td>&#160;
<c:out value="${scopeVarRequest}" />
</td>
</tr>

<tr>
<td>
<b>Session Scope</b>

(scopeVarSession)</td>

<td>&#160;
<c:out value="${scopeVarSession}" />
</td>
</tr>

<tr>
<td>
<b>Application Scope</b>

(applicationVarPage)</td>

<td>&#160;
<c:out value="${scopeVarApplication}" />
</td>
</tr>
</table>

linked.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Scope Example</title>
</head>

<body>
<h3>Forwarded File: forward.jsp</h3>

<table border="1">
<tr>
<th>Scoped Variable</th>

<th>Current Value</th>
</tr>

<tr>
<td>
<b>Page Scope</b>

(scopeVarPage)</td>

<td>&#160;
<c:out value="${scopeVarPage}" />
</td>
</tr>

<tr>
<td>
<b>Request Scope</b>

(scopeVarRequest)</td>

<td>&#160;
<c:out value="${scopeVarRequest}" />
</td>
</tr>

<tr>
<td>
<b>Session Scope</b>

(scopeVarSession)</td>

<td>&#160;
<c:out value="${scopeVarSession}" />
</td>
</tr>

<tr>
<td>
<b>Application Scope</b>

(applicationVarPage)</td>

<td>&#160;
<c:out value="${scopeVarApplication}" />
</td>
</tr>
</table>
</body>
</html>

forward.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Scope Example</title>
</head>

<body>
<h3>Forwarded File: forward.jsp</h3>
<table border="1">
<tr>
<th>Scoped Variable</th>

<th>Current Value</th>
</tr>

<tr>
<td>
<b>Page Scope</b>

(scopeVarPage)</td>

<td>&#160;
<c:out value="${scopeVarPage}" />
</td>
</tr>

<tr>
<td>
<b>Request Scope</b>

(scopeVarRequest)</td>

<td>&#160;
<c:out value="${scopeVarRequest}" />
</td>
</tr>

<tr>
<td>
<b>Session Scope</b>

(scopeVarSession)</td>

<td>&#160;
<c:out value="${scopeVarSession}" />
</td>
</tr>

<tr>
<td>
<b>Application Scope</b>

(applicationVarPage)</td>

<td>&#160;
<c:out value="${scopeVarApplication}" />
</td>
</tr>
</table>
</body>
</html>

Custom error page


<%@ page language="java" errorPage="error.jsp"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<jsp:useBean id="beanname" class="jsplearning.bean" scope="page">
<jsp:setProperty name="beanname" property="username"/>
</jsp:useBean>

<h1>name=<jsp:getProperty name="beanname" property="username"/></h1>

<<h1>El value= <c:out value="${beanname.userna}"/></h1>

<form name="f" method="post" action="bean.jsp">


<input type="text" name="username">
<input type="submit" value="submit">
</form>

error.jsp
%@ page language="java" isErrorPage="true" %>
<h1>error=<%=exception%></h1>

o/p of the error page

error=javax.servlet.jsp.el.ELException: Unable to find a value for "userna" in object of class


"jsplearning.bean" using operator "."

Vous aimerez peut-être aussi