Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Servlet & JSP Serkan Erdur & Levent Özgür. 2 What is Servlet? Java application that runs on the server side Answers html requests and produces dynamic.

Similar presentations


Presentation on theme: "1 Servlet & JSP Serkan Erdur & Levent Özgür. 2 What is Servlet? Java application that runs on the server side Answers html requests and produces dynamic."— Presentation transcript:

1 1 Servlet & JSP Serkan Erdur & Levent Özgür

2 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 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.

4 4 Servlet Work Flow

5 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 20 Servlet Example public class MerhabaServlet extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException { res.setContentType(“text/html”); printWriter out = res.getWriter(); out.println(“ MERHABA SERVLET ”); out.println(“ MERHABA DUNYA “); out.println(“ ”); }

21 21

22 22 JavaServer Pages (JSP)

23 23 Goals JavaServer Pages technology JSP in web applications Basic JSP syntax

24 24

25 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 26 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 27 A Simple JSP JSP Tarih :

28 28

29 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.

30 First run of a JSP

31 31 JSP Elements Directives Declarations Scriptlets Expressions Comments

32 32 Directives JSP directives are messages to the JSP Engine Syntax: JSP 1.0 directives : page, include, taglib

33 33 Page Directive Properties that are specific to that page Attr_list: Ex: language=“scripting language” “java” import=“package list”"java.util.*" session=“true/false” buffer=“none|sizekb”

34 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 35 Include ve Taglib Directive’leri include directive To make additions to include jsp file from another file Ex: taglib directive To define jsp tag library Seen with JSP 1.0

36 36 Declerations 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

37 37 Declerations Eg: <%! private int i =0; private void arttır(){ i++; } %>

38 38 Scriptlets 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 39 Scriptlets Eg: <%if (Calendar.getInstance().get(Calendar.AM_PM)== Calendar.AM) {%> Good Morning <%}else {%> Good Afternoon

40 40 Expressions 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 41 Expressions ClassCastException is throwed if the result of expression can not be converted to String object Ex: All Java primitive types (int,short,long..) can be converted to String automatically. Classses should have toString method for conversion.

42 42 Comments Two types of comments used in JSP 1. Output comment: comment is in browser 2. Fully secret comment: Comment is not in browser Comments can be constructed dynamicly by adding expressions in it comment text -->

43 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 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

45 45 A JSP

46 Tarih Ekranı <%if (Calendar.getInstance().get(Calendar.AM_PM)==Calendar.AM) {%> Bu sabah nasılsınız, Bu öğlen nasılsınız, <%} %> WebSphere 3.5 Kullanıcısı ? Tarih Gösteren JSP ");%> tarih.jsp source code

47 <%! 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); } %> Bugünün Tarihi: Bu sayfa: kere yüklenmiştir

48 48 Actions Standard Actions:

49 49 jsp:useBean Scripts and tags that are used for initialisation of bean 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 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 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 52 jsp:setProperty 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 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 54 jsp:getProperty Take the value of property, convert it to String and writes in output stream name: name of bean object property: property of bean

55 55 A JSP toplam :

56 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; }

57 57

58 58 jsp:include Static or dynamic page can be added into jsp file ya da...

59 59 jsp:forward ya da … 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 60 A Simple JSP testdb.jsp DataBase Erişim Örneği NO AD SOYAD 

61 <% 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()){ %> <%} connection.close(); } catch(Exception ex){out.println(ex);} %>


Download ppt "1 Servlet & JSP Serkan Erdur & Levent Özgür. 2 What is Servlet? Java application that runs on the server side Answers html requests and produces dynamic."

Similar presentations


Ads by Google