IMRAN DAUD
FOUNDATION UNIVERSITY
INSTITUTE OF MANAGEMENT AND
COMPUTER SCIENCES
Imran Daud
FUIMCS
Web Engineering
JSP
Intro to JSP
 Sun‟s Solution for developing dynamic websites.
 Server side scripting support for creating database
driven web applications.
 Web file always has „.jsp‟ extension.
 Insert java code into JSP file.
 On receiving request, JSP pages are loaded into
server memory for its execution.
 JSP Services are efficient and client is served in short
period of time.
Web-Server for JSP
 Number of web-servers are available.
 Apache TomCat
 WebSphere
 GalssFish
 etc
Setup NetBeans
 Start NetBeans
 Goto File->New Project…
Name & Location for Project
Choose Web-Server
Install New Web-Server
Installation and Login Details
First Install
required
web-server.
Give server
location
Username &
Password
We use Already Installed with NetBeans
Test Web-Server
 Run jsp file to test server by clicking green play
button.
JSP Tags
 <% (scriptless)
 <@ (directive page, include and taglib)
 <%-- (comment)
JSP Tags
 Directives
In the directives we can import packages, define error handling
pages or the session information of the JSP page.
 Declarations
This tag is used for defining the functions and variables to be used
in the JSP.
 Scriplets
In this tag we can insert any amount of valid java code and these
codes are placed in _jspService method by the JSP engine.
 Expressions
We can use this tag to output any data on the generated page. These
data are automatically converted to string and printed on the output
stream
Directive
<%@directive attribute="value" %>
 Where directive may be:
 page: page is used to provide the information about it.
Example: <%@page language="java" %>
 include: include is used to include a file in the JSP page.
Example: <%@ include file="/header.jsp" %>
 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" %>
Attributes can be
 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" %>
 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" %>
 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" %>
 errorPage="error.jsp"
errorPage is used to handle the un-handled exceptions in the page.
Example: <%@page language="java" session="true" errorPage="error.jsp" %>
 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" %>
Adding Scriptless
 <% opening tag
 %> closing tag
 To print message<% =“Hello World” %>
 To print <% = new java.util.Date() %>
JSP Declarations
 you must use the <%! and %> sequences to enclose
your declarations.
<%!
Date theDate = new Date();
Date getDate() {
out.println( "In getDate() method");
return theDate;
}
%>
Hello! The time is now <%= getDate() %>
Practice
 Make website counter…….
Declaration and Website Counter
<%!
 static int i=0;
 private int getCount(){
 return ++i;
 }
%>
<%=getCount()%>
Variables in Scriptless
 request:
request represents the clients request and is a subclass of HttpServletRequest. Use
this variable to retrieve the data submitted along the request.
Example:
<%
//java codes
String userName=null;
userName=request.getParameter("userName");
%>
 response:
response is subclass of HttpServletResponse.
 session:
session represents the HTTP session object associated with the request.
 out:
out is an object of output stream and is used to send any output to the client.
Handling „Request‟
 Steps
 Make index page with „form‟ containing username and
password.
 Use post or get method within form tag.
 Make two buttons submit and rest.
 Handle request in another jsp page.
 Methods to use are:
 Request
 Pagecontext(to redirect page)
Request methods
 very useful pre-defined variable is "request".
 It is of type javax.servlet.http.HttpServletRequest
 <%
request.getRemoteHoste(); or
request.getRemoteAddr();
 %>
JSP Session
 Associate any data with session by using .
 As long as session is maintained with user data will
be accessible on any page of website.
 Session object is associated with each user visiting
that website.
 Example: Associate username with session with
website of three pages.
How to Mix Scriptless and HTML
Import package
 <%@page import="java.util.*" %>
 <HTML>
 <BODY>
<% System.out.println( "Evaluating date now" );
Date date = new Date();
 %>
 Hello! The time is now
 <%= date %>
 </BODY>
 </HTML>
JSP Beans
 JSP introduces another organized way to retrieve
form data (but also supports other functionalities).
 That is by introducing bean.(This is not full beans)
 Define java with settter and
getter functions.
Bean Proporties
 i) It has a public no-args constructor
 ii) It has 'set' and 'get' methods for its properties.
 iii) It may have any general functions.
Steps in Creating JSP Beans
 Create html page with form data by setting action
page.
 Create java class with setter and getter function with
same name as defined in form fccccdcx.
 Create JSP page that will handle request data with
following tags.
 <jsp:useBean id=“mybean” class=“package.className"
scope="session"/>
 <jsp:setProperty name="mybean" property="*" />
 Retrieve data by following command.
 <%=mybean.getPassword()%>
Scope of Bean
 Scope= “Page” (only in current page of page specified)
 Scope = “request” (within request)
 Scope = “session” (all pages)
 If we access parameter in third page using „request‟
object then it shows null value.
 But same can be accessed using session object, if
scope is set to session.
 Now we can also access parameter through „request‟
object with following command in 2nd page.
 <jsp:forward page="session.jsp" />
 Use following to include page in existing page
 <jsp:include = “page.jsp” flush = “false” />
Quiz
 Use beans to make website counter……
Tag Libraries
 Also known as custom tags defined by user.
 Use to initiate any custom action.
 Custom actions include form processing, accessing
databases and other enterprise services such as email
and directories, and flow control.
Features of Custom Tags
 They can be customized via attributes passed from the calling
page.
 They have access to all the objects available to JSP pages.
 They can modify the response generated by the calling page.
 They can communicate with each other. You can create and
initialize a JavaBeans component, create a variable that refers
to that bean in one tag, and then use the bean in another tag.
 They can be nested within one another, allowing for complex
interactions within a JSP page.
Custom Tags
 Declare Tag Libraries
 <%@ taglib uri="/tlt" prefix="tlt" %>
 „Uri‟ attribute refers to a URI that uniquely identifies the tag
library.
 The prefix attribute distinguishes tags provided by a given tag
library from those provided by other tag libraries.
Steps
To define a tag, you need to:
 First declare the tags in a tag library
descriptor(TLD).
 Develop a tag handler and helper classes for the tag.
Tag Handler
Tag Handler
 Tag handler object is invoked by jsp container to
evaluate custom tag.
 This tag handler is java file with all custom actions
defined in it.
 We only use overridden functions
Classes to Import for handler
 TagSupport
 SimpleTagSupport
Tag Library Descriptor (TLD)
How to ?
 Create New File Tag Library Descriptor.
 Create Tag Handler file.
 Set functionality in tag handler. (once tag handler file is created
it automatically will write basic tags in TLD file).
 Call custom tag using following
 <%@taglib uri="mytld" prefix="mytag" %>
 <mytag:mytaghandler/>
Database
 Pre-Req:
 MySQL Server
 MySQL Workbench
 Create Database with table and attributes.
 WAMP Server
 Important
 Include SQL Library in Library folder before stating to
implement your project.
Steps to follow
 Import SQL Package in JSP File
 <%@ page language="java" import="java.sql.*" %>
 Load MySQL Driver
 Class.forName("com.mysql.jdbc.Driver");
 Create Connection with SQL Server
 Connection c=DriverManager.getConnection("jdbc:mysql://
localhost:3300/mydb","root", "123");
 Statement s= c.createStatement();
 ResultSet
 Statement
 ResultSet rs=s.executeQuery("Select * from student");
Show Results
 while (rs.next())
 {
out.println(rs.getString("myfield")+"<br>");
}
JSTL Use
 JSTL Tags are used for
 Iteration and conditionals
 Tags for manipulating XML documents
 Internationalization tags
 SQL tags.
JSTL
JSTL Steps
 Add JSTL library by right clicking on library folder of
project.
 To use JSTL in JSP file use following
 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"
%>
JSTL Core Tags
JSTL SQL Tags
JSTL Functions
JSTL Format Tags
Reference
 http://www.csl.mtu.edu/cs2321/
 Netbeans.org
 Roseindia.net
 Jsptut.com
 tutorialspoint.com/jsp

4. jsp

  • 1.
    IMRAN DAUD FOUNDATION UNIVERSITY INSTITUTEOF MANAGEMENT AND COMPUTER SCIENCES Imran Daud FUIMCS Web Engineering JSP
  • 2.
    Intro to JSP Sun‟s Solution for developing dynamic websites.  Server side scripting support for creating database driven web applications.  Web file always has „.jsp‟ extension.  Insert java code into JSP file.  On receiving request, JSP pages are loaded into server memory for its execution.  JSP Services are efficient and client is served in short period of time.
  • 3.
    Web-Server for JSP Number of web-servers are available.  Apache TomCat  WebSphere  GalssFish  etc
  • 4.
    Setup NetBeans  StartNetBeans  Goto File->New Project…
  • 5.
    Name & Locationfor Project
  • 6.
  • 7.
  • 8.
    Installation and LoginDetails First Install required web-server. Give server location Username & Password
  • 9.
    We use AlreadyInstalled with NetBeans
  • 12.
    Test Web-Server  Runjsp file to test server by clicking green play button.
  • 13.
    JSP Tags  <%(scriptless)  <@ (directive page, include and taglib)  <%-- (comment)
  • 14.
    JSP Tags  Directives Inthe directives we can import packages, define error handling pages or the session information of the JSP page.  Declarations This tag is used for defining the functions and variables to be used in the JSP.  Scriplets In this tag we can insert any amount of valid java code and these codes are placed in _jspService method by the JSP engine.  Expressions We can use this tag to output any data on the generated page. These data are automatically converted to string and printed on the output stream
  • 15.
    Directive <%@directive attribute="value" %> Where directive may be:  page: page is used to provide the information about it. Example: <%@page language="java" %>  include: include is used to include a file in the JSP page. Example: <%@ include file="/header.jsp" %>  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" %>
  • 16.
    Attributes can be 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" %>  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" %>  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" %>  errorPage="error.jsp" errorPage is used to handle the un-handled exceptions in the page. Example: <%@page language="java" session="true" errorPage="error.jsp" %>  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" %>
  • 17.
    Adding Scriptless  <%opening tag  %> closing tag  To print message<% =“Hello World” %>  To print <% = new java.util.Date() %>
  • 18.
    JSP Declarations  youmust use the <%! and %> sequences to enclose your declarations. <%! Date theDate = new Date(); Date getDate() { out.println( "In getDate() method"); return theDate; } %> Hello! The time is now <%= getDate() %>
  • 19.
  • 20.
    Declaration and WebsiteCounter <%!  static int i=0;  private int getCount(){  return ++i;  } %> <%=getCount()%>
  • 21.
    Variables in Scriptless request: request represents the clients request and is a subclass of HttpServletRequest. Use this variable to retrieve the data submitted along the request. Example: <% //java codes String userName=null; userName=request.getParameter("userName"); %>  response: response is subclass of HttpServletResponse.  session: session represents the HTTP session object associated with the request.  out: out is an object of output stream and is used to send any output to the client.
  • 22.
    Handling „Request‟  Steps Make index page with „form‟ containing username and password.  Use post or get method within form tag.  Make two buttons submit and rest.  Handle request in another jsp page.  Methods to use are:  Request  Pagecontext(to redirect page)
  • 23.
    Request methods  veryuseful pre-defined variable is "request".  It is of type javax.servlet.http.HttpServletRequest  <% request.getRemoteHoste(); or request.getRemoteAddr();  %>
  • 24.
    JSP Session  Associateany data with session by using .  As long as session is maintained with user data will be accessible on any page of website.  Session object is associated with each user visiting that website.  Example: Associate username with session with website of three pages.
  • 25.
    How to MixScriptless and HTML
  • 26.
    Import package  <%@pageimport="java.util.*" %>  <HTML>  <BODY> <% System.out.println( "Evaluating date now" ); Date date = new Date();  %>  Hello! The time is now  <%= date %>  </BODY>  </HTML>
  • 27.
    JSP Beans  JSPintroduces another organized way to retrieve form data (but also supports other functionalities).  That is by introducing bean.(This is not full beans)  Define java with settter and getter functions.
  • 28.
    Bean Proporties  i)It has a public no-args constructor  ii) It has 'set' and 'get' methods for its properties.  iii) It may have any general functions.
  • 29.
    Steps in CreatingJSP Beans  Create html page with form data by setting action page.  Create java class with setter and getter function with same name as defined in form fccccdcx.  Create JSP page that will handle request data with following tags.  <jsp:useBean id=“mybean” class=“package.className" scope="session"/>  <jsp:setProperty name="mybean" property="*" />  Retrieve data by following command.  <%=mybean.getPassword()%>
  • 30.
    Scope of Bean Scope= “Page” (only in current page of page specified)  Scope = “request” (within request)  Scope = “session” (all pages)
  • 31.
     If weaccess parameter in third page using „request‟ object then it shows null value.  But same can be accessed using session object, if scope is set to session.  Now we can also access parameter through „request‟ object with following command in 2nd page.  <jsp:forward page="session.jsp" />  Use following to include page in existing page  <jsp:include = “page.jsp” flush = “false” />
  • 32.
    Quiz  Use beansto make website counter……
  • 33.
    Tag Libraries  Alsoknown as custom tags defined by user.  Use to initiate any custom action.  Custom actions include form processing, accessing databases and other enterprise services such as email and directories, and flow control.
  • 34.
    Features of CustomTags  They can be customized via attributes passed from the calling page.  They have access to all the objects available to JSP pages.  They can modify the response generated by the calling page.  They can communicate with each other. You can create and initialize a JavaBeans component, create a variable that refers to that bean in one tag, and then use the bean in another tag.  They can be nested within one another, allowing for complex interactions within a JSP page.
  • 35.
    Custom Tags  DeclareTag Libraries  <%@ taglib uri="/tlt" prefix="tlt" %>  „Uri‟ attribute refers to a URI that uniquely identifies the tag library.  The prefix attribute distinguishes tags provided by a given tag library from those provided by other tag libraries.
  • 36.
    Steps To define atag, you need to:  First declare the tags in a tag library descriptor(TLD).  Develop a tag handler and helper classes for the tag.
  • 37.
    Tag Handler Tag Handler Tag handler object is invoked by jsp container to evaluate custom tag.  This tag handler is java file with all custom actions defined in it.  We only use overridden functions
  • 38.
    Classes to Importfor handler  TagSupport  SimpleTagSupport
  • 39.
  • 40.
    How to ? Create New File Tag Library Descriptor.  Create Tag Handler file.  Set functionality in tag handler. (once tag handler file is created it automatically will write basic tags in TLD file).  Call custom tag using following  <%@taglib uri="mytld" prefix="mytag" %>  <mytag:mytaghandler/>
  • 41.
    Database  Pre-Req:  MySQLServer  MySQL Workbench  Create Database with table and attributes.  WAMP Server  Important  Include SQL Library in Library folder before stating to implement your project.
  • 42.
    Steps to follow Import SQL Package in JSP File  <%@ page language="java" import="java.sql.*" %>  Load MySQL Driver  Class.forName("com.mysql.jdbc.Driver");  Create Connection with SQL Server  Connection c=DriverManager.getConnection("jdbc:mysql:// localhost:3300/mydb","root", "123");  Statement s= c.createStatement();  ResultSet  Statement  ResultSet rs=s.executeQuery("Select * from student");
  • 43.
    Show Results  while(rs.next())  { out.println(rs.getString("myfield")+"<br>"); }
  • 44.
    JSTL Use  JSTLTags are used for  Iteration and conditionals  Tags for manipulating XML documents  Internationalization tags  SQL tags.
  • 45.
  • 46.
    JSTL Steps  AddJSTL library by right clicking on library folder of project.  To use JSTL in JSP file use following  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  • 47.
  • 49.
  • 51.
  • 52.
  • 53.
    Reference  http://www.csl.mtu.edu/cs2321/  Netbeans.org Roseindia.net  Jsptut.com  tutorialspoint.com/jsp