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

JSP ACTION

What is JSP action


• JSP action are
• HTML-Like syntax
• predefined tags and attributes
• perform action based on information
• <jsp:usebean id=“xxx” .. />

• JSP provides a list of standard action tags for specific


tasks to interact with java bean objects

• Action elements are predefined functions and simplify


programming implementation
JSP Action Syntax
• represent dynamic actions to be performed at runtime

<prefix: action-name attr1=“value1” attr2=“value2”>


action_body
</prefix:action-name>

<prefix: action-name attr1=“value1” attr2=“value2” />


Standard Actions
• <jsp:param>
• adds a parameter to a request handed over to another servlet or
JSP page
• <jsp:include>
• Include the response from a servlet or JSP page during the request
processing phase
• <jsp:forward>
• Forwards the processing of a request to a servlet or JSP page
5

Standard Actions
• <jsp:useBean>
• makes a java bean component available to a page
• <jsp:getProperty>
• gets a property value from a JavaBean components and adds it to
the response
• <jsp:setProperty>
• Set a JavaBean property value
6

The include directive <jsp:include>


• To include a file at the request time
• to merge the content of other external files with the
current JSP
• can be anywhere in the JSP page.

• <jsp:include page="relative url" />

• Include content with parameter


• <jsp:include page="relative url" >
• <jsp:param>
• </jsp:include>
7

include.jsp
<!DOCTYPE html>
<html> <body>
<jsp:include page="header.jsp"/>

<jsp:include page=“info.jsp">
<jsp:param value="Wong" name="name"/>
<jsp:param value="LWL" name="campus"/>
</jsp:include>

<jsp:include page="info.jsp"> Use include action


<jsp:param value="Jesse" name="name"/> to create a template
<jsp:param value="TY" name="campus"/>
</jsp:include>
</body> add additional
</html> parameter to the
template using
param
8

header.jsp
<h3>ITP4912 Web Application development Frameworks</h3>

info.jsp
obtain parameter
name
<center>
<b><i>Name:
<%=request.getParameter("name")%>. </i></b> ,
<span style="font-style:italic">Campus:
<% out.print(request.getParameter("campus"));%>
</span> <br/>
IVE ICT Department Copyright © 2012
</center>
<hr >
9
<jsp:forward>
• Pass control to another JSP page or servlet
• the execution of the current JSP page is terminated and
control is fully passed to the target JSP

• Without Parameter
• <jsp:forward page=“pagePath” />

• With Parameters
• <jsp:forward page=“pagePath” >
• <one or more <jsp:param> actions
• </jsp:forward>
jsp:forward

• <jsp:forward page=“nextPage.jsp”>
• <jsp:param name=“aParam” value=“aValue” />
• </jsp:forward>

• <jsp:forward page=“nextPage.jsp” />



12

forward.jsp

<% prepare the rand


double rand = Math.random(); value
%>

<jsp:forward page="conditional.jsp">
<jsp:param name="chance" value="<%=rand%>" /> forward the control
</jsp:forward> to conditional.jsp
with a parameter of
chance with the
rand value
13

conditional.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head> </head>
<body>
<%
double rand = Double.valueOf(request.getParameter("chance"));
if (rand < 0.5) {
out.println(" I like <b>Web Server Programming with Java</b>");
} else {
out.println(" I like <b> Swing Programming with Java </b>");

}%>
</body>
</html>
14

The url is not changed and is still


forward.jsp, but program is executed
by conditional.jsp
15

Example using froward

Mark.jsp determines
the whether the student
is passed or failed.

The final output is


handled by passed.jsp
or failed respectively.

both mark and name parameters send to the mark.jsp


parameters in the request is available in the forward chain

e.g. passed.jsp and failed will also obtain parameter


16
17

make decision and forward to appropriate page


mark.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
int mark = Integer.valueOf(request.getParameter("mark"));
String url = "passed.jsp";
if (mark < 40) {
url="failed.jsp";
}
%>
<jsp:forward page="<%=url%>" />
1. parameter from the original request will
</body>
dispatch the next request.
</html>
e.g. mark and name will dispatch to the
next request
18

passed.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
Dear <%=request.getParameter("name")%> : <br/>
<p>
You are passed.
</p>
</body>
</html>
19

failed.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
Dear <%=request.getParameter("name")%> : <br/>
<p>
Sorry, You are failed.
</p>
</body>
</html>d
20

JAVA BEAN AND JSP


ACTION
21

Progressing an input form


Client (Browser) Server

url:ex1form.jsp
ex1form.jsp
The
form
with url: formHandler.jsp
different form Hander.jsp
Progress form
input request.getParameter ()
request.getParameterValues
elements :
:
show the
result
Java Beans
• Used in JSP as a containers for dynamic content

• A bean encapsulates data about one entity


• A reusable component
• to separate Business logic from the Presentation logic
• A Java class with some special format
23

Java Bean Class


• Java classes that follow certain coding conventions
• Define in a package, ex ict.bean
• must have a no-argument constructor/ default constructor
• data in the bean is referred to as properties
• bean properties are accessed through getter and setter methods
• a property is either read-only, write-only or read-write
• a property is case-sensitive and starts with a lower-case letter
• implements Serializable

Serialization is a process of converting an Object into stream of bytes so


that it can be transferred over a network or stored in a persistent storage.
Java Beans Pet

properties
id: int (read/write)
name: String (read/write)
species: String (read/write)
This is Pet class
owner: String (read/write)

Pet()

methods
int getId()
void setId(int)
String getName()
void setName(String)
String getSpecies()
void setSpecies(String)
boolean getBirthDate()
String getOwner()
void setOwner(String)
25

Getter and Setter Method (Accessor)


• define a getter method represents
• a read-only property
• define a setter method represents a write-only
property has
• define both represent a
• a read-write property
26

Java Beans Accessor Methods


• get (set) + name of the property with first character of
the name capitalized
• Ex: if property name is fileName
• setter method is setFileName() private filename;
• getter method is getFileName()

• a getter method has no arguments


String getFileName() {..}
• a setter method returns void
• parameter should be the same data type of the property

void setFileName(String fileName) {..}


27
How to use Java Bean in JSP
<jsp:useBean>
• declare it JSP using <jsp:useBean> standard action:

<jsp:useBean id=“pet” class=“ict.bean.Pet” scope=“page” />

the id attribute
• should be a valid Java variable name, e.g. starting with a
letter and lower case
the id must be unique in the page,
the class attribute
• creates an instance of the bean in the container
• Scope attribute define it shareable among JSPs (discuss
it later)
29

What are the scopes available in <jsp:useBean>?


• page scope
• It specifies that the object will be available for the entire JSP page
but not outside the page.
• request scope
• It specifies that the object will be associated with a particular
request and exist as long as the request exists.
• session scope
• It specifies that the object will be available throughout the session
with a particular client.
• application scope
• It specifies that the object will be available throughout the entire
Web application but not outside the application.
30

Use Bean Example


<jsp:useBean id=“pet” class=“ict.bean.Pet” scope=“page” />

• Similar as
• <%
• ict.bean.Pet pet = new ict.bean.Pet();
• %>
An instance of
ict.bean.Pet is
created in the
page scope. The
variable name is
pet
How to use update the Property in Java Bean
<jsp:setProperty>

<jsp:setProperty name=“pet” property=“species” value=“cat” />

the name attribute


• should be match with id attribute which defined in the
useBean action
the property attribute
• must be match with the property with the property name
defined in the java bean class
the value attribute
• is the value to be updated in the bean claas
Update the Properties in Java Bean
• <jsp:setProperty> standard action

• <jsp:setProperty name=“pet” property=“name”


value=“Fluffy” />
• <jsp:setProperty name=“pet” property=“species” value=“cat” />

The object pet is


• Same as updated where
name is “fluffy”
<% and species is
pet.setName("Fluffy"); “cat”
pet.setSpecies("cat");
%> You. need to
update one
property at a time
How to show the Property in Java Bean
<jsp:getProperty>

<jsp:getProperty name=“pet” property=“species” >

the name attribute


• should be match with id attribute which defined in the
useBean action
the property attribute
• The value of the property will be print out to the JSP
34

Display Bean Properties


• <jsp:getProperty name=“pet” property=“name” />
• <jsp:getProperty name=“pet” property=“species” />

• Same as
• <%= pet.getName() %>
• <% out.println( pet.getSpecies()); %>

Values returned by <jsp:getProperty> are


always converted to String
35

pet.jsp Combine together

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head> <title>JSP Page</title> </head>
<body>
The object pet is created
<jsp:useBean id="pet" class="ict.bean.Pet" scope="page" />
The value of object pet is updatedy
<jsp:setProperty name="pet"property="name"value="Fluffy"/>
<jsp:setProperty name="pet"property="species"value="cat"/>
The value output is output
<ul><li>Name:
<jsp:getProperty name="pet"property="name"/></li>
<li>Species
<jsp:getProperty name="pet"property="species"/></li>
</ul>
</body>
36

Output of Pet.jsp
37

Progressing an input form


Client (Browser) Server

The
form
with
different
input
elements url: formHandler.jsp form Hander.jsp
Progress form
request.getParameter ()
request.getParameterValues
:
:
show the
result
38

Handling form input with JSP and beans


• Basic concept
• JSP uses request.getParameter("name1") to get form input

• Skills involved in getting input from text field, checkbox, radio


button are the same as what we discussed before in the servlet
section
39

Setting Bean properties


• There ways to set bean properties by specifying attribute
• 1. value
• 2. param
• 3. property


40

Attribute : value
• Set bean property at request time with input parameters
item is of type String
Get the input value form the request
<%
String name = request.getParameter("name");
int grade = Integer.parseInt(request.getParameter("grade"));
String[] course = request.getParameterValues("course");
%>
use jspExpression to update the property in the
the bean object
<jsp:setProperty name="s" property="name" value="<%=name%>"/>
<jsp:setProperty name="s" property="grade" value="<%=grade%>"/>
<jsp:setProperty name="s" property="course" value="<%=course%>"/>
41

use param attribute

<jsp:setProperty name="s" property="name" param="name"/>


<jsp:setProperty name="s" property="grade" param="grade" />
<jsp:setProperty name="s" property="course" param="course" />

course is the parameter name for the request. i.e input field name
course is the property name in the bean class

value = request.getParameter(“course”);
s.setCourse (value);

Type conversion is automatically performed

Directly associate an input parameter with a property


42

Set All Bean Properties with Input Parameters

<jsp:setProperty name=“s" property="*" />

each input field name must match with the property in the bean
class.

• Notes:
• No action is taken if an input parameter is missing. No null is
passed
• Error page might be needed to guard against invalid input, like
inputting 123abc for numItems
44

Student.java
public class Student implements Serializable {

private String name;


private int grade;
private String[] course;
public Student () {}

public String[] getCourse() { return course; }


public void setCourse(String[] course) { this.course = course; }
public int getGrade() { return grade; }

public void setGrade(int grade) { this.grade = grade; }


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

studentForm.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="studentByValue.jsp" method="get">
Name: <input type="text" name="name" value="" /> <br/>
Garde: <input type="text" name="grade" value="" /> grade 1 to 12<br/>
Course: <input type="checkbox" name="course" value="maths" /> Maths
<input type="checkbox" name="course" value="physics" /> Physics
<input type="checkbox" name="course" value="chemistry" />
Chemistry<br/>
<input type="submit" value="submit" />
</form>
</body>
</html>
46

studentByValue.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
<jsp:useBean id="s" class="ict.bean.Student" scope="page" />
<%
String name = request.getParameter("name");
int grade = Integer.parseInt(request.getParameter("grade"));
String[] course = request.getParameterValues("course");
%>
<jsp:setProperty name="s" property="name" value="<%=name%>"/>
<jsp:setProperty name="s" property="grade" value="<%=grade%>"/>
<jsp:setProperty name="s" property="course" value="<%=course%>"/>
<jsp:forward page="studentInfo.jsp" />
</body>
</html>
47

studentByParam.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<jsp:useBean id="s" class="ict.bean.Student" scope="request" />

<jsp:setProperty name="s" property="name" param="name"/>


<jsp:setProperty name="s" property="grade" param="grade" />
<jsp:setProperty name="s" property="course" param="course" />

<jsp:forward page="studentInfo.jsp" />


</body>
48

studentByProperty.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-
8">
<title>JSP Page</title>
</head>
<body>
<jsp:useBean id="s" class="ict.bean.Student" scope="request" />
<jsp:setProperty name="s" property="*" />
<jsp:forward page="studentInfo.jsp" />
</body>
</html>
Since the bean scope is defined in
49
request scope in the
studentByXXX.jsp, the bean will be
available until the request in
studentInfo.jsp finished.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head></head>
<body>
<jsp:useBean id="s" class="ict.bean.Student" scope="request" />
<ul><li>Name <jsp:getProperty name="s"property="name" /></li>
<li>Grade <jsp:getProperty name="s"property="grade" /></li>
<li>Course
<%
String[] selectedCourse = s.getCourse();
if (selectedCourse == null) {
out.println("no course selected");
} else {
out.println("<ol>");
for (int i = 0; i < selectedCourse.length; i++) {
out.println("<li>" + selectedCourse[i] + "</li>");
out.println("</ol>");
}
}
50

Try modifying the action in studentFrom.jsp


• See if you can get the same result
JAVA BEAN SCOPE ATTRIBUTE
• Page
• Request
• Session
• Application
PAGE
• Any object whose scope is the page will disappear
as soon as the current page finishes generating.
The object with a page scope may be modified as
often as desired within the particular page but the
changes are lost as soon as the page exists.
• By default all beans have page scope.
REQUEST
• Any objects created in the request scope will be
available as long as the request object is.
• For example if the JSP page uses an jsp:forward
tag, then the bean should be applicable in the
forwarded JSP also, if the scope defined is of
Request scope.
SESSION
• In JSP terms, the data associated with the user has
session scope. A session does not correspond
directly to the user; rather, it corresponds with a
particular period of time the user spends at a site.
Typically, this period is defined as all the visits a
user makes to a site between starting and existing
his browser
APPLICATION
• An object bound to application object means that
your object will stay as long as the application
remains loaded.
• This can be useful when for instance you want to
count page views or daily sessions for your site.
Model-View-Controller Design
• Separation of
• data and business logic (Model)
• data presentation (View)
• data interaction (Controller)

• The user interacts with the Controller to ask for things to


be done.
• Controller forward the request to the Model
• the result of the request is displayed by the View
Model-View-Controller Design

Request Controller
(Servlet) Data
Model
(JavaBean)
Response View
(JSP) Data

Browser JSP/Servlet Container Data Tier


58

Some action elements :


Action element Description
<jsp:useBean> Makes a JavaBeans component available
Gets a property value from a JavaBeans component
<jsp:getProperty> and adds
it to the response
<jsp:setProperty> Sets a JavaBeans component property value
Includes the response from a servlet or JSP page
<jsp:include> during the
request processing phase
Forwards the processing of a request to servlet or
<jsp:forward>
JSP page
Adds a parameter value to a request handed off to
<jsp:param> another servlet
or JSP page using <jsp:include> or <jsp:forward>

You might also like