1 servlet & jsp serkan erdur & levent Özgür. 2 what is servlet? java application that runs...
TRANSCRIPT
2
What is Servlet?
Java application that runs on the server side Answers html requests and produces
dynamic html responses to send them to the
client independent server and platform Java alternative to cgi scripts
3
Servlet Work Flow Client sends request to server
1. Server sends the request knowledge to servlet
2. Servlet produces dynamic result and send it to server
3. Server sends the result to client.
5
Advantages of Servlet
Platform independent because of Java use Persistency and as a result increase in
performance Java background
Not scripting, a real programming language Object oriented programming Uses all advantages of Java
6
Temporary & Permanent Servlets
A temporary servlet is started when a request arrives and shut down after the response is generated.
A permanent servlet is loaded when the server is started and lives until the server is shut down. is useful when startup costs are high Provides faster response to client requests
7
Using Servlets
Install Java Servlet Development (JSDK).
Servlets can be tested with the utility program servlet runner
Servlet API is a standard extension for the JDK under javax
8
Performance Advantages Servlet and Application Server runs in the
same JVM. Runs and remains in memory Can be loaded when request comes or start to run
when server runs Hold session information Can use system advantages in
multiprocessor systems and heterogeneous systems. (clustered servers and workload management)
9
Life Cycle of Servlet init
First method to be called Work with the servlet is created
service (doGet, doPost) Run whenever there is any client call
destroy Method that runs before servlet is destroyed
Generally there is one servlet object in the memory that is shared by all clients
10
init method
The init method is invoked when the servlet is first started. For permanent servlets, this is when the server is started.
The init method is called only once and is guaranteed to finish before any calls to the service method.
11
service method public void service (ServletRequest req,
ServletResponse res) Each request message from the client results
in invoking the service method. More than one instance of the service method
can be invoked at one time to respond to multiple requests.
12
destroy method
Called when the servlet in unloaded to clean up any open resources.
Although the server normally waits until all service calls are terminated to invoke destroy, it may not be possible, and your destroy method should make sure that resources are not being used.
13
Java Servlet API Consists of java classes that define standard
communication between web client & web server Consists of two packages
javax.servlet javax.servlet.http
javax.servlet packet is general, protocol independent and have classes that supports servlet
javax.servlet.http packet additionally owns private classes of http protocol.
14
HttpServlet (javax.servlet.http.HttpServlet)
Special servlet type for http requests Methods:
doGet(): runs when getrequest comes doPost(): runs when postrequest comes
doGet() and doPost() called by service() method
Subclasses overrides these methods and also init() & destroy() methods can be overrided.
15
Requests and Responses
Service(), doGet() and doPost() take two parameters. HttpServletRequest:
Enables us to read Request parameters, HttpSession and other info. Comes with request.
HttpServletResponse Enables us to return an answer to the client
Ingeneral, servlet programming is reading requests + writing responses
16
Request Protocol
getParameterNames() Returns the parameter names comes with the
request. getParameter(String name)
Returns the value of the parameter comes with the request
getReader() Returns request body as BufferedReader object.
17
Response Protocol
Provides data communication channel to Client
Can return contents and errors Can set content header Can redirect url to another url
18
Response Protocol
getWriter() produces PrintWriter object Html tags are written in this object
setContentType(String type) Content type of response message(Eg: text/html)
sendRedirect(String URL) Redirect url to another url
19
Utility Classes
Two exception classes in the servlet API
javax.servlet.ServletException: servlet should throw this exception to server in event of general failure
javax.servlet.UnavailableException:servlet can report this at any time to server. The servlet may write a log entry so that an administrator can take some action.
20
Servlet Examplepublic class MerhabaServlet extends HttpServlet{public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException {
res.setContentType(“text/html”);printWriter out = res.getWriter();out.println(“<title>MERHABA SERVLET</title> <HTML><BODY>”);out.println(“ MERHABA DUNYA “);out.println(“</BODY></HTML>”);
} }
25
Web Page content
Content of the page that is sent to client: static dynamic
Page design and style can be done by HTML, XSL,..
26
Server-side Scripting Server-side Scripting
Page that is composed of dynamic and static parts are prepared in server before sent to client
Code in the server side is run to produce dynamic parts
Example technologies: JavaServer Pages (JSP) Active Server Pages (ASP)
ASP and JSP files are similar in shape to html files
27
A Simple JSP
<HTML><HEAD>
<TITLE>JSP</TITLE></HEAD><BODY>
Tarih : <%= new java.util.Date() %></BODY>
</HTML>
29
JSP Execution Model
Java Server Page is first converted to servlet and then run
This is page compilation JSP source code parsed Java sevlet code produced Servlet code compiled, loaded and run.
32
Directives JSP directives are messages to the JSP
Engine Syntax:
<%@ directive {attribute=“value”}* %> JSP 1.0 directives :
page, include, taglib
33
Page Directive
Properties that are specific to that page <%@ page attr_list %> Attr_list: Ex:
language=“scripting language” “java”
import=“package list”"java.util.*"
session=“true/false”
buffer=“none|sizekb”
34
Page Directive
Attr_list (continue):
errorPage=“error jsppage_url”
isErrorPage=“true|false”
contentType=“Type|Type;charSet=CHARSET”
Eg: contentType=“text/html;charSet=ISO-8859-9”
autoFlush=“true/false”
extends=“className”
35
Include ve Taglib Directive’leri include directive
To make additions to include jsp file from another file
<%@ include file=“relativeURLspec” %> Ex: <%@ include file="copyright.html"%>
taglib directive To define jsp tag library <%@ taglib uri=“tagLibraryURI” prefix=“tagPrefix”
%> Seen with JSP 1.0
36
Declerations
<%! Decleration %> includes java code Variables and methods defined Code that is written in tag is included in
servlet class as class members (outside the methods) So that parameters will take te same value in all
instances of the servlet
38
Scriptlets
<% java code %> Enables us to use java code Written in service method in which java code
will be implemented Run with every request coming to server Scriptlets are combined with the same
ordering of their order in jsp file
39
Scriptlets
Eg:<%if
(Calendar.getInstance().get(Calendar.AM_PM)==
Calendar.AM)
{%>
Good Morning
<%}else
{%>
Good Afternoon
<%}%>
40
Expressions
<%= expression %> Expression is the java code in which, its result
is converted to String object The result is sent to output stream to be
shown in browser Usually for running and showing results of the
methods of Java beans which is defined in JSP or defined in decleration.
41
Expressions ClassCastException is throwed if the result of
expression can not be converted to String object
Ex:<%= i %>
All Java primitive types (int,short,long..) can be converted to String automatically. Classses should have toString method for conversion.
42
Comments
Two types of comments used in JSP1. Output comment: comment is in browser
<!-- comments ... -->
2. Fully secret comment: Comment is not in browser<%-- comment text --%>
Comments can be constructed dynamicly by adding expressions in it
<!--comment text <%=expression %> comment text -->
43
Implicit Objects
Implicit Objects: Objects that can be used in scripts and
expressions without defining them before. request: javax.servlet.HttpServletRequest
request object that is the reason for the servlet to run response: javax.servlet.HttpServletResponse
Response for the request session: javax.servlet.http.HttpSession
Session object for the client
44
Implicit Objects
out: javax.servlet.jsp.JspWriter Output stream writer
pageContext : javax.servlet.jsp.PageContext By getPage, getSession, getException methods , it
enables us to reach JSP objects page : java.lang.Object
Instance of the class which is composed of the page that answers the request
<html><title>Tarih Ekranı</title><body><!--D I R E C T I V E S --><%@page language ="java"%><%@page import ="java.util.*"%><%@page contentType ="TEXT/HTML"%><!--S C R I P T L E T S--><H3><%if (Calendar.getInstance().get(Calendar.AM_PM)==Calendar.AM){%>Bu sabah nasılsınız,<%}else {%>Bu öğlen nasılsınız,<%}%>WebSphere 3.5 Kullanıcısı ?</H3><HR><!--A C C E S S I N G I M P L I C I T O B J E C T S --><%out.println("İşte <b>Tarih Gösteren JSP</b>");%>
tarih.jsp source code
<!--D E C L A R A T I O N S --><%!private int calledCount =0;private String getDate(GregorianCalendar gcalendar){StringBuffer dateStr =new StringBuffer();dateStr.append(gcalendar.get(Calendar.DATE));dateStr.append("/");dateStr.append(gcalendar.get(Calendar.MONTH)+1);dateStr.append("/");dateStr.append(gcalendar.get(Calendar.YEAR));return (dateStr.toString());}private int incrementCounter(){return (++calledCount);}%><H1>Bugünün Tarihi:<%=getDate(new GregorianCalendar())%></H1><H1>Bu sayfa:<%=incrementCounter()%> kere yüklenmiştir</H1></body></html>
48
Actions
Standard Actions:
<jsp:useBean /> <jsp:setProperty /> <jsp:getProperty /> <jsp:include /> <jsp:forward />
49
jsp:useBean <jsp:useBean id=“name” scope=“page|request|session|
application” beanDetails >Scripts and tags that are used for initialisation of bean
</jsp:useBean> beanDetails is one of the following:
class=“className” class=“className” type=“typeName” beanName=“beanName” type=typeName” type=“typeName” ;optional. Tha same value as class by default
id : name to use bean object Scope: scope of the referance for bean. Default: page
50
jsp:useBean
Scope: Page:
Object reference cleared after Servlet.service() method was run
New object created for every client request Request
Object still survives when HttpRequest object is used although request passes to another page.
New object created for every client request
51
jsp:useBean Session
Object is connected to HttpSession New object created for every client request and object
survives during session time Application
Longest time Connected to object ServletContext Same object for every client
52
jsp:setProperty <jsp:setProperty name=“beanName”
propertyDetails /> Set the property of beans that we define with
useBean propertDetails is one of the following:
property=“*” all properties are set with parameter of same name in the
request object property=“propertyName”
Set with the parameter of the same name
53
jsp:setProperty propertyAyrıntıları (continue)
property=“propertyName” param=“parameterName” Set with the parameter given
property = “propertyName” value=“propertyValue” Set with the property given . It can be constant string or an
expression
String values are converted to types of properties by using the related conversion methods.
54
jsp:getProperty
<jsp:getProperty name=“name” property=“propertyName” />
Take the value of property, convert it to String and writes in output stream
name: name of bean object property: property of bean
55
A JSP<html><jsp:useBean id="topla" class="test.Toplama" /><jsp:setProperty name="topla" property="sayi1"
value="2" /><jsp:setProperty name="topla" property="sayi2"
value="5" /><% topla.topla(); %>toplam : <jsp:getProperty name="topla"
property="toplam" /></html>
package test;public class Toplama{
private int sayi1;private int sayi2;private int toplam;
public Toplama() {super();
}public int getSayi1() {
return sayi1;}public int getSayi2() {
return sayi2;}public int getToplam() {
return toplam;}public void setSayi1(int i) {
sayi1=i;}public void setSayi2(int i) {
sayi2=i;}public void topla() {
toplam=sayi1+sayi2;}
}
58
jsp:include
Static or dynamic page can be added into jsp file <jsp:include page=“filename” flush=“true” />
ya da
<jsp:include page=“urlSpec” flush=“true”>
<jsp:param name=“paramname” value=“paramvalue” />
...
</jsp:include>
59
jsp:forward <jsp:forward page=“url” />
ya da
<jsp:forward page=“url”>
<jsp:param name=“paramname” value=“paramvalue” />
…
</jsp:forward> Request is passed to another JSP, servlet or static address Jsp that is used erased from buffer and if new parameters
added , request is reorganised and target page is loaded
60
A Simple JSP
testdb.jsp
<%@ page contentType="text/html; charset=ISO-8859-9" %> <%@ page import="java.sql.*" %><HTML><HEAD><META http-equiv="Content-Style-Type"
content="text/css"><TITLE>DataBase Erişim Örneği</TITLE></HEAD>
<BODY BGCOLOR="#FFFFFF"><table border="1"><th>NO</th><th>AD</th><th>SOYAD</th>
<% try{ Connection connection = null; Statement statement = null; ResultSet results = null; Class.forName("com.ibm.as400.access.AS400JDBCDriver"); String url = "jdbc:as400://192.168.0.201"; //AS400 IP adresi String query="SELECT * from OYKINSNKT.PERSONEL"; connection = DriverManager.getConnection(url,"adm","pass"); statement= connection.createStatement(); results = statement.executeQuery(query); while (results.next()){ %><tr> <td><%= results.getString(1) %> </td> <td><%= results.getString(2) %> </td> <td><%= results.getString(3) %> </td></tr><%} connection.close(); }catch(Exception ex){out.println(ex);}%>
</table></BODY></HTML>