Вы находитесь на странице: 1из 30

Understand JSP

1.

Apply knowledge and skills to create a user


interfaces for an interactive Java programming.
(C3, P3, PLO1,PLO2)

2.

Design a program that integrates the database


and web to build a Java web based application.
(C5, P3, PLO1, PLO2)

3.

Produce an interactive application program


using
appropriate
Java
programming
environment. (A3, P4, PLO2, PLO4)

Using Java Server Pages(JSP)


o Define JSP.
o Compare between Servlet and JSP.
o Explain JSP scripting elements .
o Describe Java Beans and JSP.
o Illustrate the process output generated by Servlet

process
o Integrate Servlets and JSP
o Write a program that connect JSP to the database

JSP is an extension of servlet technology


Each JSP is translated by the JSP container
into a servlet.
Unlike Servlet, JSP separates presentation
from content.
JSP enable web application programmers to
create dynamic content by:
Reusing predefined components
b. Interacting with components using server-side
scripting
a.

JSP programmers can use special software


components called JavaBeans that
encapsulate complex, dynamic functionality.
A JavaBean is a reusable component that
follows certain conventions for class design.
For example, JavaBeans classes that allow
reading and writing of instance variable must
provide appropriate get and set method.

Example From Lab Excercise


<jsp:useBean id="objPelajar" scope="request"
class="Person.Pelajar"/>
<jsp:setProperty name="objPelajar" property="*"/>
//Example : Accessing the object method
objPelajar.searchAllEmployee();
objPelajar.getName();

JSPs contain:
Static template data: HTML, XML, and WML
o JSP elements: JSP tags and Java code to construct
dynamic content
o

GET/POST

HTTP
Server

Client
Browser
HTML

JSP page

JSP Engine:
Compile

Servlet

JSP provides a simplified, fast way to create


web pages that display dynamicallygenerated content

Java Web Applications are packaged as Web


Archive (WAR) and it has a defined structure. You
can export above dynamic web project as WAR
file and unzip it to check the hierarchy. It will be
something like below image.

web.xmlfile is the deployment descriptor of the


web application and contains mapping for
servlets (prior to 3.0), welcome pages, security
configurations, session timeout settings etc.

SERVLETS

JSP

A servlet is a server-side program

JSP is an interface on top of Servlets

Executes inside a Web server, such as


Tomcat

A JSP program is compiled into a Java


servlet before execution

Receives HTTP requests from users and


provides HTTP responses

Easier to write than servlets as it is similar


to HTML.

Written in Java, with a few additional APIs


specific to this kind of processing

Can make use of JavaBeans also

In MVC architecture Servlet acts as


controller.

In MVC architecture JSP acts as view.

Servlet advantages include:


Performance-get loaded upon first
request
and
remains
in
memory
idenfinately.
Simplicity- Run inside controlled server
environment. No specific client software
is needed:web broser is enough
Session
Management-overcomes
HTTPs stateless nature

JSP Provides an extensive infrastructure for:


Tracking sessions.
Managing cookies.
Reading and sending HTML headers.
Parsing and decoding HTML form data.
JSP is Efficient:Every request for a JSP is
handled by a simple Java thread
JSP is Scalable: Easy integration with other
backend services
Seperation of roles: Developers, Content
Authors/Graphic Designers/Web Masters

Used in JSP pages, pages that end *.jsp


Comment <%-- Comment --%>
JSP Srcriplet <%Java statement %>
Java Directive <%@ %>
o

The directives include:page,include,taglib.

Declaration <%! int x = 0; %>


Expression <%= expression %>
o Outputs to the Response stream
o Like a printf to the browser
o Do NOT use semi-colon to terminate the line

Scriplets - contains Java Code


<% code fragments %>
<% if (value.getName().length != 0) { %>
<H2>The value is: <%= value.getName() %></H2>
<% } else { %>
<H2>Value is empty</H2>
<% } %>
Implicit objects always available in the JSP Page
o request Browsers Request Object
Use to get HTTP headers, length etc..
o response - HttpResponse Object

JSP Directives
o Are messages or instructions to the JSP container
o Do not produce any output
o page directive

<%@ page import=person.Student %>


Commonly used for importing class paths
o include directive

<%@ include file=header.htm %>


Good for including static content

Embed Java expressions in JSP pages by putting them


between the <%= and %> character sequences
Allow you to write blocks of Java code inside the JSP.
Place your Java code between <% and %>
characters without the = sign
<HTML>
<body>
<h2>Hello World!</h2>
<%-// This is a scriptlet. Notice that the "date"
// variable we declare here is available in the
// embedded expression later on.
--%>
<%
java.util.Date date = new java.util.Date();
%>
Hello! The time is now <%= date %>
</body>
</HTML>

two very useful pre-defined variables are


"request and response
A "request" in server-side processing refers to
the transaction between a browser and the
server.
o Exm: request.getParameter(VARIABLE);

The JSP "request" variable is used to obtain


information from the request as sent by the
browser.
A similar variable is "response". This can be
used to affect the response being sent to the
browser.
o Exm: response.sendRedirect(anotherUrl): send a

response to the browser that it should load a different


URL.

public void addEmployee(){


try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/java_lab", "root", "1234");
String sql = "INSERT INTO maklumatpelajar VALUES " +
"(?,?,?,?,?,?,?,?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1,Nama);
statement.setString(2,IcNo);
statement.setString(3,Bangsa);
statement.setString(4,TarikhLahir);
statement.setString(5,Alamat);
statement.setString(6,Poskod);
statement.setString(7,Daerah);
statement.setString(8,Negeri);
statement.execute();
}
catch (Exception e)
{e.printStackTrace();}
}

public ArrayList searchAllEmployee(){


ArrayList al = new ArrayList();
try{
ResultSet rs = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/java_lab", "root", "1234");
String sql = "SELECT * FROM maklumatpelajar ORDER BY NamaPelajar";
PreparedStatement statement = conn.prepareStatement(sql);
rs = statement.executeQuery();
while(rs.next()) {
Pelajar obj = new Pelajar();
obj.setNama(rs.getString("NamaPelajar"));
obj.setIcNo(rs.getString("NoIC"));
obj.setBangsa(rs.getString("Bangsa"));
obj.setTarikhLahir(rs.getString("TarikhLahir"));
obj.setAlamat(rs.getString("Alamat"));
obj.setPoskod(rs.getString("Poskod"));
obj.setDaerah(rs.getString("Daerah"));
obj.setNegeri(rs.getString("Negeri"));
al.add(obj);
}
}
catch (Exception e)
{e.printStackTrace();}
return al;
}

public ArrayList searchByPelajarICNo(){


ArrayList al = new ArrayList();
try{
ResultSet rs = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/java_lab",
"root", "1234");
String sql = "SELECT * FROM maklumatpelajar WHERE NoIC=?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1,IcNo);
rs = statement.executeQuery();
while(rs.next()) {
Pelajar obj = new Pelajar();
obj.setNama(rs.getString("NamaPelajar"));
obj.setIcNo(rs.getString("NoIC"));
obj.setBangsa(rs.getString("Bangsa"));
obj.setTarikhLahir(rs.getString("TarikhLahir"));
obj.setAlamat(rs.getString("Alamat"));
obj.setPoskod(rs.getString("Poskod"));
obj.setDaerah(rs.getString("Daerah"));
obj.setNegeri(rs.getString("Negeri"));
al.add(obj);
}
}
catch (Exception e)
{e.printStackTrace();}
return al;
}

public void deletePelajar(){


try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/java_lab", "root",
"1234");
String sql = "DELETE FROM maklumatpelajar WHERE NoIC = ?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1,IcNo);
statement.execute();
}
catch (Exception e)
{e.printStackTrace();}
}

public void updatePelajar(){


try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/java_lab", "root", "1234");
String sql = "UPDATE maklumatpelajar SET " +
"
NamaPelajar=?,NoIC=?,Bangsa=?,TarikhLahir=?,Alamat=?,Poskod=?,Daerah=?,Negeri=? WHERE
NoIC=?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1,Nama);
statement.setString(2,IcNo);
statement.setString(3,Bangsa);
statement.setString(4,TarikhLahir);
statement.setString(5,Alamat);
statement.setString(6,Poskod);
statement.setString(7,Daerah);
statement.setString(8,Negeri);
statement.setString(9,IcNo);
statement.execute();
}
catch (Exception e)
{e.printStackTrace();}
}

Similar to how Java Beans are used in


Swing and AWT
o But do not need the full implementation
Must have no constructor or no-arg
constructor
Must have setter and getter methods for
each property value
JSP constructs/tags use Java Beans
Bean : consist of getter & setter
o To represent the database entity

AJavaBeanis a Java class which conforms to the


following rules:
1. It has a no-arg constructor.
2. It does not have public variables.
3. It is defined in a named package. It cannot be kept in the

default no-name package.


4. For
a
private
variablexxx,
there
is
a
public
gettergetXxx()(orisXxx()forboolean)
and
a
public
settersetXxx().
5. For an eventxxxEvent, there is an interfacexxxListener, and
methodsaddXxxListener()andremoveXxxListener().
6. It implementsSerializableinterface, so that its state can be
stored and retrieved to and from external storage, for
persistent.

According to Java white paper;


o It is a reusable software component.
o A bean encapsulates many objects into one object,

so we can access this object from multiple places.


o It provides the easy maintenance.

<jsp:useBean>
o Create a new bean instance. The bean class must be kept in

"<WebContextRoot>\WEB-INF\classes" within a proper package


directory structure.
<jsp:useBean id="beanName" class="packageName.ClassName"
scope="page|request|session|application" />
// Equivalent to JSP Declaration:
// <%! PackageName.className beanName = new
PackageName.className();%> // setAttribute according to
the scope.
The attributescopespecifies the scope of this bean:
o page: default, stored inPageContext, available to this page only.
o request: stored inServletRequest, can be forwarded to another JSP
page or servlet.
o session: stored inHttpSession, available to all pages and servlets
within this session.
o application: stored inServletContext, shared by all servlets and JSP
pages in this web context (application).

<jsp:setProperty>
o Set the value of a property (variable) of a bean, by

invoking its setter.


<jsp:setProperty name="beanName"
property="propertyName"
value="propertyValue" />
// Equivalent to Scriptlet:
<% beanName.setPropertyName(propertyValue); %>

<jsp:getProperty>
o Get the value of a property (variable) of a bean, by

invoking its getter.


<jsp:getProperty name = "beanName property =
"propertyName" />
//Equivalent to Expression: <%=
beanName.getPropertyName() %>

JSP actions are special tags that affect the output


stream and are normally used with Java beans
o Most commonly used:

<jsp:useBean>,<jsp:getProperty>,<jsp:setProperty
>

The code below will display the lastName property


of the student bean on the output stream
<jsp:useBean id="student" scope="request
class=person.Student" />
<jsp:getProperty name="student"
property="lastName" />

Вам также может понравиться