Separating Programming and Presentation: JSP Technology: CSI 3140 WWW Structures, Techniques and Standards

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 36

CSI 3140

WWW Structures, Techniques and Standards

Separating Programming and


Presentation:
JSP Technology
JSP
JSP technology is used to create web application. It focuses more on presentation
logic of the web apllication.

JSP pages are easier to maintain then a Servlet. JSP pages are opposite of Servlets.
Servlet adds HTML code inside Java code while JSP adds Java code inside HTML.
Everything a Servlet can do, a JSP page can also do it.

JSP enables us to write HTML pages containing tags that run powerful Java
programs. 

JSP separates presentation and business logic as Web designer can design and
update JSP pages without learning the Java language and Java Developer can also write
code without concerning the web design.

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


Lifecycle

A JSP page is converted into Servlet in order to service requests. The


translation of a JSP page to a Servlet is called Lifecycle of JSP. JSP Lifecycle
consists of following steps.
Translation of JSP to Servlet code.
Compilation of Servlet to bytecode.
Loading Servlet class.
Creating servlet instance.
Initialization by calling jspInit() method
Request Processing by calling _jspService() method
Destroying by calling jspDestroy() method

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


Contd….
Web Container translates JSP code into a servlet class source(.java) file, then
compiles that into a java servlet class.

In the third step, the servlet class bytecode is loaded using classloader. The
Container then creates an instance of that servlet class.

The initialized servlet can now service request. For each request the Web
Container call the _jspService()method.

When the Container removes the servlet instance from service, it calls
the jspDestroy() method to perform any required clean up.

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


What happens to a JSP when it is translated into Servlet
Let's see what really happens to JSP code when it is translated into Servlet
<html>
<head>
<title>
My First JSP Page</title>
</head>
<% int count = 0; %>
<body>
Page Count is: <% out.println(++count); %>
</body>
</html>

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


The above JSP page becomes this Servlet
public class hello_jsp extends HttpServlet
{
public void _jspService(HttpServletRequest request,HttpServletResponse response) throws
IOException,ServletException
{
PrintWriter out = response.getWriter();
response.setContenType("text/html");
out.write("<html><body>");
int count=0;
out.write("Page count is:");
out.print(++count);
out.write("</body></html>");
}
}

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


JSP Scripting Element

JSP Scripting element are written inside <% %> tags. These code inside <%
%> tags are processed by the JSP engine during translation of the JSP page. Any
other text in the JSP page is considered as HTML code or plain text.
Scriptlet Tag allow you write java code inside JSP page.
<% java code %>

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


JSP Scripting Element

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


JSP Expression Language (EL)
JSP Expression Language (EL) makes it possible to easily access application data
stored in JavaBeans components. JSP EL allows you to create expressions
both (a) arithmetic and (b)logical.
 Within a JSP EL expression, you can use integers, floating point numbers, strings,
the built-in constants true and false for boolean values, and null.
Synatx of EL: ${expression}
<html>
<body>
${1<2}
${1+2+3} </body>
</html>
o/p: true 6

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


Example 2: Value fetch using param variable of expression
language

In this example we are prompting user to enter name and roll number. On the other JSP page
we are fetching the entered details using param variable of EL.
index.jsp
<html> <body> <form action="display.jsp">
Student Name: <input type="text" name="stuname" />
<br> Student RollNum:<input type="text" name="rollno" /><br>
<input type="submit" value="Submit Details!!"/> </form> </body> </html>
display.jsp
<html>
<body>
Student name is ${ param.stuname } <br>
Student Roll No is ${ param.rollno } </body>
</html>

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides
JSP Expression Language (EL)
EL operators:
 Relational: <, >, <=, >=, ==, !=
 Or equivalents: lt, gt, le, ge, eq, ne
 Logical: &&, ||, !
 Or equivalents: and, or, not
 Arithmetic:
 +, - (binary and unary), *
 /, % (or div, mod)
 empty: true if arg is null or empty
string/array/Map/Collection
 Conditional: ? :
 Array access: [ ] (or object notation)
 Parentheses for grouping

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


JSP Expression Language (EL)

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


JSP Standard Tag Library(JSTL)

JSP Standard Tag Library(JSTL) is a standard library of custom tags. The


JSTL contain several tag that can remove scriplet code from a JSP page.
JSTL are divided into 5 catagories.
Core Tags
Formatting tags
SQL tags
XML tags
JSTL Functions

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


JSTL Core

: JSTL Core provide several core tags such as if, forEach, import, out etc to support some basic scripting task. Url
to include JSTL Core Tag inside JSP page is:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

JSTL if tag: The if tag is a conditional tag used to evaluate conditional expression. Example
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html> <head> <title>Tag Example</title> </head>
<body>
<c:if test="${param.name == 'studytonight' }">
<p>Welcome to ${param.name} </p>
</c:if>
</body>
</html>

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


JSTL out tag: The out tag is used to evaluate a expression and write the result
to JspWriter. Example
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html>
<head>
<title>Tag Example</title>
</head>
<body>
<c:out value="${param.name}" default="StudyTonight" > </body> </html>
 The value attribute specifies the expression to be written to the JspWriter.
 The default attribute specifies the value to be written if the expression evaluate null.

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


JSTL forEach tag: The forEach tag provide a mechanism to iteration within a
JSP page. JSTL forEach tag works similar to enhanced for loop of Java
Technology. You can use this tag to iterate over a existing collection of item.
Example

<body>
<c:forEach var="message" items="${errorMsgs}" >
<li>${message}</li>
</c:forEach >
</body>

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


In this article we are discussing <c:choose>, <c:when> and <c:otherwise>
core tags of JSTL.
These tags are used together like switch-case and default statements in java.
<c:choose> is the one which acts like switch, <c:when> like case which can be
used multiple times inside <c:choose> for evaluating different-2 conditions.
 <c:otherwise> is similar to default statement which works when all the
<c:when> statements holds false.

JSTL set tag: The JSTL set tag is used to store a variable in specified scope
or update the property of JavaBean instance

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides
JSTL SQL tag

The JSTL SQL tag library provides tags for interacting with relational databases
(RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP:
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


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

<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"


url="jdbc:mysql://localhost/TEST"
user="root" password="pass123"/>

<sql:update dataSource="${snapshot}" var="count">


INSERT INTO Employees VALUES (104, 2);
</sql:update>

<sql:query dataSource="${snapshot}" var="result">


SELECT * from Employees;
</sql:query>

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


Cont..

<table border="1" width="100%">


<c:forEach var="row" items="${result.rows}">
<tr>
<td><c:out value="${row.id}"/></td>
<td><c:out value="${row.first}"/></td>
</tr>
</c:forEach>
</table>

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


JavaBeans Classes

 JSTL Core actions are designed to be used for simple,


presentation-oriented programming tasks
 More sophisticated programming tasks should still be
performed with a language such as Java
 JavaBeans technology allows a JSP document to call Java
methods
 According to Java white paper, it is a reusable software
component. A bean encapsulates many objects into one object,
so we can access this object from multiple places. Moreover, it
provides the easy maintenance.

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


JavaBeans Classes

Example

Requirements: JavaBeans class must


 Be public and not abstract
 Contain at least one simple property design pattern method
(defined later)

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


JavaBeans Classes

Using a JavaBeans class in JSP

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


It may have a number of "getter" and "setter" methods for the
properties.

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


JavaBeans Classes

Simple property design patterns


 Two types: getter and setter
 Both require that the method be public
 getter:
 no arguments
 returns a value
 name begins with get (or is, if return type is boolean) followed by
upper case letter
 setter:
 one argument (same type as setter return value)
 void
 name begins with set followed by upper case letter

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


JavaBeans Classes

EL calls simple property design method in


response to access of bean property:
 Attempt to read property generates call to
associated get/is method (or error if none
exists)
 Attempt to assign value to property generates
call to associated set method (or error)

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


JavaBeans Classes

Example setter method

Calling setter from JSP

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


//Employee.java
package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}

public int getId(){return id;}

public void setName(String name){this.name=name;}

public String getName(){return name;}

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


access the java bean class

To access the java bean class, we should use getter and setter methods.
package mypack;  
public class Test{  
public static void main(String args[]){  
  
Employee e=new Employee();//object is created  
  
e.setName(“xxxx");//setting value to the object  
  
System.out.println(e.getName());  
  
}}  

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


MVC

Many web apps are based on the Model-


View-Controller (MVC) architecture pattern

Model Components

Controller View

HTTP HTTP
request response

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides
MVC

Typical JSP implementation of MVC

Model Components
(beans, DBMS)

Controller View
(Java servlet) (JSP document)

HTTP HTTP
request response

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


 Model–view–controller (MVC) is a software architectural pattern for
implementing user interfaces. It divides a given software application into three
interconnected parts, so as to separate internal representations of information from
the ways that information is presented to or accepted from the user

 A model is an object representing data or even activity, e.g. a database table The


model is responsible for managing the data of the application. It responds to the
request from the view and it also responds to instructions from the controller to
update itself.

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


The view A presentation of data in a particular format,
triggered by a controller's decision to present the data. They
are script based templating systems like JSP, ASP, PHP and
very easy to integrate with AJAX technology.

The controller The controller is responsible for responding


to user input and perform interactions on the data model
objects. The controller receives the input, it validates the input
and then performs the business operation that modifies the
state of the data model

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides

You might also like