Unit III- Server Side Technologies

Size: px
Start display at page:

Download "Unit III- Server Side Technologies"

Transcription

1 Web Technology Unit III- Server Side Technologies By Prof. B.A.Khivsara Note: The material to prepare this presentation has been taken from internet and are generated only for students reference and not for commercial use.

2 Outline Introduction to Server Side technology and TOMCAT, Servlet: Introduction to Servlet, need and advantages, Servlet Lifecycle, Creating and testing of sample Servlet, session management. JSP: Introduction to JSP, advantages of JSP over Servlet, elements of JSP page: directives, comments, scripting elements, actions and templates, JDBC Connectivity with JSP.

3 Servlets & Tomcat

4 Out Line Servlet Introduction Servlet Lifecycle Servlet Architecture Software Requirement to run Servlet Tomcat Introduction Tomcat Configuration in Eclipse Steps to run servlets in Eclipse Sample code Session Management

5 What are Servlets? Java Servlets are programs that run on a Web or Application server and act as a middle layer between a requests coming from a Web browser or other HTTP client and databases or applications on the HTTP server. Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.

6 Advantages of Servlet over CGI Performance is significantly better. Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request. Servlets are platform-independent because they are written in Java. servlets are trusted. The full functionality of the Java class libraries is available to a servlet.

7 Servlets Architecture

8 Servlets Packages Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet specification. Servlets can be created using the packages javax.servlet javax.servlet.http

9 Out Line Servlet Introduction Servlet Lifecycle Servlet Architecture Software Requirement to run Servlet Tomcat Introduction Tomcat Configuration in Eclipse Steps to run servlets in Eclipse Sample code

10 Servlet Life Cycle The servlet is initialized by calling the init() method. The servlet calls service() method to process a client's request. The servlet is terminated by calling the destroy() method. Finally, servlet is garbage collected by the garbage collector of the JVM.

11 The init() Method The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards. So, it is used for one-time initializations. When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doget or dopost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet. The init method definition looks like this public void init() throws ServletException { // Initialization code... }

12 The service() Method The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client. When server receives a request for a servlet, the service() method checks the HTTP request type (GET, POST) and calls doget, dopost, methods as appropriate. Here is the signature of this method public void service(servletrequest request, ServletResponse response) throws ServletException, IOException { }

13 The doget() Method A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doget() method. public void doget(httpservletrequest request, HttpServletResponse response) } throws ServletException, IOException { // Servlet code

14 The dopost() Method A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by dopost() method. public void dopost(httpservletrequest request, HttpServletResponse response) } throws ServletException, IOException { // Servlet code

15 The destroy() Method The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, and perform other such cleanup activities. After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this public void destroy() { // Finalization code... }

16 Out Line Servlet Introduction Servlet Lifecycle Servlet Architecture Software Requirement to run Servlet Tomcat Introduction Tomcat Configuration in Eclipse Steps to run servlets in Eclipse Sample code Session Management

17 Architecture Diagram First the HTTP requests coming to the server are delegated to the servlet container. The servlet container loads the servlet before invoking the service() method. Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet.

18 Out Line Servlet Introduction Servlet Lifecycle Servlet Architecture Software Requirement to run Servlet Tomcat Introduction Tomcat Configuration in Eclipse Steps to run servlets in Eclipse Sample code Session Management

19 Requirements Before running Servlet your machine requires following tools 1> Eclipse (IDE-integrated development environment) 2> Tomcat (Web Server)

20 Out Line Servlet Introduction Servlet Lifecycle Servlet Architecture Software Requirement to run Servlet Tomcat Introduction Tomcat Configuration in Eclipse Steps to run servlets in Eclipse Sample code Session Management

21 Apache-Tomcat Apache Tomcat, often referred to as Tomcat Server, is an open-source Java Servlet Container developed by the Apache Software Foundation (ASF). Tomcat implements several Java EE specifications including Java Servlet, JavaServer Pages (JSP), Java EL, and WebSocket, and provides a "pure Java" HTTP web server environment in which Java code can run.

22 Tomcat- Components Catalina Coyote Jasper Cluster High availability Web application

23 Tomcat- Components Catalina Catalina is Tomcat's servlet container. Catalina implements Sun Microsystems's specifications for servlet and JavaServer Pages (JSP). In Tomcat, a Realm element represents a "database" of usernames, passwords, and roles assigned to those users. Catalina to be integrated into environments where such authentication information is already being created and maintained, and then use that information to implement Container Managed Security as described in the Servlet Specification.

24 Tomcat- Components Coyote Coyote is a Connector component for Tomcat that supports the HTTP 1.1 protocol as a web server. This allows Catalina, nominally a Java Servlet or JSP container, to also act as a plain web server that serves local files as HTTP documents. Coyote listens for incoming connections to the server on a specific TCP port and forwards the request to the Tomcat Engine to process the request and send back a response to the requesting client.

25 Tomcat- Components Jasper Jasper is Tomcat's JSP Engine. Jasper parses JSP files to compile them into Java code as servlets (that can be handled by Catalina). At runtime, Jasper detects changes to JSP files and recompiles them. From Jasper to Jasper 2, important features were added: JSP Tag library pooling - Each tag markup in JSP file is handled by a tag handler class. Background JSP compilation - While recompiling modified JSP Java code, the older version is still available for server requests. Recompile JSP when included page changes - Pages can be inserted and included into a JSP at runtime JDT Java compiler - Jasper 2 can use the Eclipse JDT Java compiler

26 Tomcat- Components These components are added from Tomcat 7.0 version Cluster This component has been added to manage large applications. High availability A high-availability feature has been added to facilitate the scheduling of system upgrades (e.g. new releases, change requests) without affecting the live environment. Web application It has also added user- as well as system-based web applications enhancement to add support for deployment across the variety of environments.

27 Out Line Servlet Introduction Servlet Lifecycle Servlet Architecture Software Requirement to run Servlet Tomcat Introduction Tomcat Configuration in Eclipse Steps to run servlets in Eclipse Sample code Session Management

28 How to configure tomcat server in Eclipse? (One time Requirement) If you are using Eclipse IDE first time, you need to configure the tomcat server First. For configuring the tomcat server in eclipse IDE, click on servers tab at the bottom side of the IDE -> right click on blank area -> New -> Servers -> choose tomcat then its version -> next -> click on Browse button -> select the apache tomcat root folder previous to bin -> next -> addall -> Finish.

29 How to configure tomcat server in Eclipse?

30 How to configure tomcat server in Eclipse?

31 How to configure tomcat server in Eclipse?

32 How to configure tomcat server in Eclipse?

33 How to configure tomcat server in Eclipse?

34 How to configure tomcat server in Eclipse?

35 How to configure tomcat server in Eclipse?

36 How to configure tomcat server in Eclipse?

37 Out Line Servlet Introduction Servlet Lifecycle Servlet Architecture Software Requirement to run Servlet Tomcat Introduction Tomcat Configuration in Eclipse Steps to run servlets in Eclipse Sample code Session Management

38 Steps to run servlet in Eclipse Create a Dynamic web project create a servlet add servlet-api.jar file Run the servlet

39 Steps to run servlet in Eclipse Create a Dynamic web project create a servlet add servlet-api.jar file Run the servlet

40 Create the dynamic web project Start Eclipse and In Menu : File -> New -> Dynamic Web Project

41 Create the dynamic web project

42 Create the dynamic web project

43 Create the dynamic web project

44 Create the dynamic web project Structure of Dynamic Web Project

45 Steps to run servlet in Eclipse Create a Dynamic web project create a servlet add servlet-api.jar file Run the servlet

46 Create a servlet Right click on Src -> New -> Sevlet

47 Create a servlet Give name of class

48 Create a servlet

49 Create a servlet Either select doget or dopost

50 Create a servlet Servlet is created, you can write the code now.

51 Steps to run servlet in Eclipse Create a Dynamic web project create a servlet add servlet-api.jar file Run the servlet

52 Add servlet-api.jar file

53 Add servlet-api.jar file

54 Add servlet-api.jar file In Tomcat folder goto Lib folder and select servlet-api.jar file

55 Add servlet-api.jar file

56 Steps to run servlet in Eclipse Create a Dynamic web project create a servlet add servlet-api.jar file Run the servlet

57 Run the servlet Right click on project name -> click Run As -> Run on Server

58 Run the servlet

59 Run the servlet

60 Out Line Servlet Introduction Servlet Lifecycle Servlet Architecture Software Requirement to run Servlet Tomcat Introduction Tomcat Configuration in Eclipse Steps to run servlets in Eclipse Sample code Session Management

61 Example 1- To Print Hello World directly import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void init() throws ServletException { } public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<h1> Hello World </h1>"); } public void destroy() { } }

62 Example 2- To Print Hello World using init method import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { private String message; public void init() throws ServletException { message = "Hello World"; } public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<h1>" + message + "</h1>"); } public void destroy() { } }

63 Reading Form Data using Servlet getparameter() You call request.getparameter() method to get the value of a form parameter. getparametervalues() Call this method if the parameter appears more than once and returns multiple values, for example checkbox. getparameternames() Call this method if you want a complete list of all parameters in the current request.

64 Example 3- To read data from HTML file and print that. It requires 2 files: 1. HTML (s1.html)file 2. Servlet (s2.java) File First Run HTML file and after clicking on submit button it will run servel(.java) file.

65 Example 3- To read data from HTML file and print that. S1.html (html code) <html> <form method= post action= s2 > Enter Your Name <input type=text name= t1 > <br> <input type= submit value= submit > </form> </body> </html>

66 Example 3- To read data from HTML file and print that. S2.java (Servlet Code) import java.io.*; import javax.servlet.*; public class s2 extends HttpServlet { public void dopost(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html"); String a= request.getparameter("t1"); PrintWriter out= response.getwriter(); out.print("<br>your Name is: "+a); } }

67 Example 4 (HTML code) To read data from HTML checkbox values print that <!DOCTYPE html> <html> Name of Servlet File <body> <form method="post" action=s1> Hobbies <input type="checkbox" name="t1" value= Cricket"> Cricket <input type="checkbox" name="t1" value="music">music <input type="checkbox" name="t1" value= Dance">Dance <input type="submit" value="submit"> </form> </body> </html>

68 Example 4 (servlet code) To read data from HTML checkbox values print that protected void dopost(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html"); PrintWriter out=response.getwriter(); String[] values=request.getparametervalues("t1"); for(int i=0;i<values.length;i++) { out.println("<li>"+values[i]+"</li>"); } } }

69 Example 5 (HTML code) To print complete list of all parameters <!DOCTYPE html> <html> <body> <form method="post" action=s1> Hobbies Enter Name <input type= text" name="t1" > <br> Enter Address <input type= text" name="t2" > <br> Enter Class <input type= text" name="t3" > <br> <input type="submit" value="submit"> </form> </body> </html>

70 Example 5 (Servlet code) To print complete list of all parameters protected void dopost(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); } Enumeration e = request.getparameternames(); while(e.hasmoreelements()) { Object obj = e.nextelement(); out.println((string) obj+ "<br>"); }

71 Out Line Servlet Introduction Servlet Lifecycle Servlet Architecture Software Requirement to run Servlet Tomcat Introduction Tomcat Configuration in Eclipse Steps to run servlets in Eclipse Sample code Session Management

72 Session Tracking (Management) Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet. Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user. Why use Session Tracking? To recognize the user It is used to recognize the particular user.

73 Session Tracking Techniques Cookies Hidden Form Field URL Rewriting HttpSession

74 Session Tracking- Using Cookies A cookie is a small piece of information that is persisted between the multiple client requests. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. How Cookie works In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user.

75 Session Tracking- Using Cookies Types of Cookie Non-persistent cookie Persistent cookie Non-persistent cookie It is valid for single session only. It is removed each time when user closes the browser. Persistent cookie It is valid for multiple session. It is not removed each time when user closes the browser. It is removed only if user logout or signout.

76 Session Tracking- Using Cookies Advantage of Cookies Simplest technique of maintaining the state. Cookies are maintained at client side. Disadvantage of Cookies It will not work if cookie is disabled from the browser. Only textual information can be set in Cookie object.

77 Session Tracking- Using Cookies Useful Methods of Cookie class Method public void setmaxage(int expiry) public String getname() public String getvalue() public void setname(string name) public void setvalue(string value) Description Sets the maximum age of the cookie in seconds. Returns the name of the cookie. The name cannot be changed after creation. Returns the value of the cookie. changes the name of the cookie. changes the value of the cookie.

78 Session Tracking- Using Cookies How to create Cookie? Cookie ck=new Cookie("user","sonu");//creating cookie object response.addcookie(ck);//adding cookie in the response How to delete Cookie? Cookie ck=new Cookie("user","");//deleting value of cookie ck.setmaxage(0);//changing the maximum age to 0 seconds response.addcookie(ck);//adding cookie in the response How to get Cookies? Cookie ck[]=request.getcookies(); for(int i=0;i<ck.length;i++){ out.print("<br>"+ck[i].getname()+" "+ck[i].getvalue());//printing na me and value of cookie }

79 Session Tracking- Using Cookies Simple example of Servlet Cookies

80 Session Tracking- Using Cookies Simple example of Servlet Cookies index.html <form action="servlet1" method="post"> Name:<input type="text" name="username"/><br/> <input type="submit" value="go"/> </form>

81 Session Tracking- Using Cookies Simple example of Servlet Cookies Servlet1.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class FirstServlet extends HttpServlet { public void dopost(httpservletrequest request, HttpServletResponse response){ try{ response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); String n=request.getparameter("username"); out.print("welcome "+n); Cookie ck=new Cookie("uname",n);//creating cookie object response.addcookie(ck);//adding cookie in the response //creating submit button out.print("<form action='servlet2'>"); out.print("<input type='submit' value='go'>"); out.print("</form>"); out.close(); }catch(exception e){system.out.println(e);} } }

82 Session Tracking- Using Cookies Simple example of Servlet Cookies Servlet2.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void dopost(httpservletrequest request, HttpServletResponse response){ try{ response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); Cookie ck[]=request.getcookies(); out.print("hello "+ck[0].getvalue()); out.close(); }catch(exception e){system.out.println(e);} } }

83 Session Tracking Techniques Cookies Hidden Form Field URL Rewriting HttpSession

84 Session Tracking- Hidden Form Fields In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of an user. In such case, we store the information in the hidden field and get it from another servlet. Synax <input type="hidden" name="uname" value= Bhavana"> Here, uname is the hidden field name and Bhavana is the hidden field value.

85 Session Tracking- Hidden Form Fields Advantage of Hidden Form Field It will always work whether cookie is disabled or not. Disadvantage of Hidden Form Field: It is maintained at server side. Extra form submission is required on each pages. Only textual information can be used.

86 Session Tracking- Hidden Form Fields Example of passing username

87 Session Tracking- Hidden Form Fields Example of passing username index.html <form method="post" action= First"> Name:<input type="text" name="user" /><br/> Password:<input type="text" name="pass" ><br/> <input type="submit" value="submit"> </form>

88 Session Tracking- Hidden Form Fields Example of passing username First.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class First extends HttpServlet { } protected void dopost(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { } response.setcontenttype("text/html;charset=utf-8"); PrintWriter out = response.getwriter(); String user = request.getparameter("user"); //creating a new hidden form field out.println("<form action='second'>"); out.println("<input type='hidden' name='user' value='"+user+"'>"); out.println("<input type='submit' value='submit' >"); out.println("</form>");

89 Session Tracking- Hidden Form Fields Example of passing username Second.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Second extends HttpServlet { protected void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html;charset=utf-8"); PrintWriter out = response.getwriter(); } } //getting parameter from the hidden field String user = request.getparameter("user"); out.println("welcome "+user);

90 Session Tracking Techniques Cookies Hidden Form Field URL Rewriting HttpSession

91 Session Tracking- URL Rewriting If the client has disabled cookies in the browser then session management using cookie wont work. In that case URL Rewriting can be used as a backup. URL rewriting will always work. In URL rewriting, a token(parameter) is added at the end of the URL. The token consist of name/value pair separated by an equal(=) sign. For Example:

92 Session Tracking- URL Rewriting When the User clicks on the URL having parameters, the request goes to the Web Container with extra bit of information at the end of URL. The Web Container will fetch the extra part of the requested URL and use it for session management. The getparameter() method is used to get the parameter value at the server side. Advantage of URL Rewriting It will always work whether cookie is disabled or not (browser independent). Extra form submission is not required on each pages. Disadvantage of URL Rewriting It will work only with links. It can send only textual information.

93 Session Tracking- URL Rewriting Example index.html <form method="post" action="validate"> Name:<input type="text" name="user" /><br/> Password:<input type="text" name="pass" ><br/> <input type="submit" value="submit"> </form>

94 Session Tracking- URL Rewriting Example Validate.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { } protected void dopost(httpservletrequest request, HttpServletResponse response) } throws ServletException, IOException { response.setcontenttype("text/html;charset=utf-8"); String name = request.getparameter("user"); String pass = request.getparameter("pass"); } if(pass.equals("1234")) { response.sendredirect("first?user_name="+name+"");

95 Session Tracking- URL Rewriting Example First.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class First extends HttpServlet { protected void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html;charset=utf-8"); PrintWriter out = response.getwriter(); String user = request.getparameter("user_name"); out.println("welcome "+user); } }

96 Session Tracking Techniques Cookies Hidden Form Field URL Rewriting HttpSession

97 Session Tracking- HttpSession The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. You would get HttpSession object by calling the public method getsession() of HttpServletRequest, as below HttpSession session = request.getsession();

98 Session Tracking- HttpSession How to get the HttpSession object? public HttpSession getsession():returns the current session associated with this request, or if the request does not have a session, creates one. Commonly used methods of HttpSession interface public String getid():returns unique identifier value. public long getcreationtime():returns the time when this session was created. public long getlastaccessedtime():returns the last time the client sent a request associated with this session. public void invalidate():invalidates this session then unbinds any objects bound to it.

99 Session Tracking- HttpSession Example Hit Count HTML File <h3>hit Count Example with HttpSession</h3> <form method="get" action= HitCount"> Click for Hit Count <input type="submit" value="get HITS"> </form> </body>

100 Session Tracking- HttpSession Example Hit Count public class HitCount extends HttpServlet { public void service(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { res.setcontenttype("text/html") ; PrintWriter out = res.getwriter( ); HttpSession session = req.getsession(); Integer hitnumber = (Integer) session.getattribute("rama"); if (hitnumber == null) { hitnumber = new Integer(1); } else { hitnumber = new Integer(hitNumber.intValue()+1) ; } session.setattribute("rama", hitnumber); // storing the value with session object out.println("your Session ID: " + session.getid()); // never changes in the whole session out.println("<br>session Creation Time: " + new Date(session.getCreationTime())); out.println("<br>time of Last Access: " + new Date(session.getLastAccessedTime())); out.println("<br>latest Hit Count: " + hitnumber); // increments by 1 for every hit

101 Session Tracking- HttpSession Example Hit Count output

102 JSP

103 Outline Introduction to JSP Advantages of JSP over Servlet JSP Life cycle JSP Creation in Eclipse Elements of JSP page: directives, comments, scripting elements, actions and templates JDBC Connectivity with JSP.

104 Introduction to JSP JSP technology is used to create web application just like Servlet technology. It can be thought of as an extension to servlet because it provides more functionality than servlet such as expression language, jstl etc. A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to maintain than servlet because we can separate designing and development. It provides some additional features such as Expression Language, Custom Tag etc.

105 Outline Introduction to JSP Advantages of JSP over Servlet JSP Life cycle JSP Creation in Eclipse Elements of JSP page: directives, comments, scripting elements, actions and templates JDBC Connectivity with JSP.

106 Advantages of JSP vs. Active Server Pages (ASP) The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use. Second, it is portable to other operating systems and non- Microsoft Web servers. vs. JavaScript JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to perform complex tasks like database access and image processing etc.

107 Advantage of JSP over Servlet 1) Extension to Servlet JSP technology is the extension to servlet technology. We can use all the features of servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression language and Custom tags in JSP, that makes JSP development easy. 2) Easy to maintain JSP can be easily managed because we can easily separate our business logic with presentation logic. In servlet technology, we mix our business logic with the presentation logic. 3) Fast Development: No need to recompile and redeploy If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code needs to be updated and recompiled if we have to change the look and feel of the application. 4) Less code than Servlet In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code. Moreover, we can use EL, implicit objects etc.

108 Outline Introduction to JSP Advantages of JSP over Servlet JSP Life cycle JSP Creation in Eclipse Elements of JSP page: directives, comments, scripting elements, actions and templates JDBC Connectivity with JSP.

109 Life cycle of a JSP Page The JSP pages follows these phases: Translation of JSP Page Compilation of JSP Page Classloading (class file is loaded by the classloader) Instantiation (Object of the Generated Servlet is created). Initialization ( jspinit() method is invoked by the container). Reqeust processing ( _jspservice() method is invoked by the container). Destroy ( jspdestroy() method is invoked by the container).

110 Life cycle of a JSP Page In the end a JSP becomes a Servlet JSP pages are converted into Servlet by the Web Container. The Container translates a JSP page into servlet class source(.java) file and then compiles into a Java Servlet class.

111 JSP Compilation When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page. The compilation process involves three steps Parsing the JSP. Turning the JSP into a servlet. Compiling the servlet.

112 JSP Initialization When a container loads a JSP it invokes the jspinit() method before servicing any requests. If you need to perform JSP-specific initialization, override the jspinit() method public void jspinit(){ // Initialization code... } Typically, initialization is performed only once and as with the servlet init method, you generally initialize database connections, open files, and create lookup tables in the jspinit method.

113 JSP Execution This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed. Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspservice() method in the JSP. The _jspservice() method as follows void _jspservice(httpservletrequest request, HttpServletResponse response) { // Service handling code... } The _jspservice() method of a JSP is invoked on request basis. This is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods, i.e, GET, POST, DELETE, etc.

114 JSP Cleanup The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container. The jspdestroy() method is the JSP equivalent of the destroy method for servlets. The jspdestroy() method has the following form public void jspdestroy() { // Your cleanup code goes here. }

115 Outline Introduction to JSP Advantages of JSP over Servlet JSP Life cycle JSP Creation in Eclipse Elements of JSP page: directives, comments, scripting elements, actions and templates JDBC Connectivity with JSP.

116 Creating a JSP Page A JSP page looks similar to an HTML page, but a JSP page also has Java code in it. We can put any regular Java Code in a JSP file using a scriplet tag which start with <% and ends with %>. JSP pages are used to develop dynamic responses.

117 Creating a JSP Page Open Eclipse, Click on New Dynamic Web Project

118 Creating a JSP Page Give a name to your project and click on OK

119 Creating a JSP Page You will see a new project created in Project Explorer

120 Creating a JSP Page To create a new JSP file right click on Web Content directory, New JSP file

121 Creating a JSP Page Give a name to your JSP file and click Finish.

122 Creating a JSP Page Write something in your JSP file. The complete HTML and the JSP code, goes inside the <body> tag, just like HTML pages.

123 Creating a JSP Page To run your project, right click on Project, select Run As Run on Server

124 Creating a JSP Page To start the server, Choose existing server name and click on finish

125 Creating a JSP Page See the Output in your browser.

126 Outline Introduction to JSP Advantages of JSP over Servlet JSP Life cycle JSP Creation in Eclipse Elements of JSP page: directives, comments, scripting elements, actions and templates JDBC Connectivity with JSP.

127 Elements of JSP Scripting Element Example Comment <%-- comment --%> Directive directive %> Declaration <%! declarations %> Scriptlet <% scriplets %> Expression <%= expression %>

128 JSP Comments JSP comment marks text or statements that the JSP container should ignore. Syntax of the JSP comments <%-- This is JSP comment --%> Example shows the JSP Comments <html> <body> <h2>a Test of Comments</h2> <%-- This comment will not be visible in the page source --%> </body> </html>

129 JSP Directives A JSP directive affects the overall structure of the servlet class. It usually has the following form <%@ directive attribute="value" %> There are three types of directive tag

130 The Scriptlet A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language. syntax of Scriptlet <% code fragment %> first example for JSP <html> <head><title>hello World</title></head> <body> Hello World!<br/> <% out.println("your IP address is " + request.getremoteaddr()); %> </body> </html>

131 JSP Declarations A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file. Syntax for JSP Declarations <%! declaration; %> Example for JSP Declarations <%! int i = 0; %> <%! int a, b, c; %> <%! Circle a = new Circle(2.0); %>

132 JSP Expression A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. you cannot use a semicolon to end an expression. Syntax of JSP Expression <%= expression %> Example shows a JSP Expression <html> <body> <%= "Welcome "+request.getparameter("uname") %> </body> </html>

133 JSP Actions JSP actions use to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. Syntax <jsp:action_name attribute = "value" />

134 JSP Actions S.No. Syntax & Purpose 1 jsp:include - Includes a file at the time the page is requested. 2 jsp:usebean - Finds or instantiates a JavaBean. 3 jsp:setproperty - Sets the property of a JavaBean. 4 jsp:getproperty - Inserts the property of a JavaBean into the output. 5 jsp:forward - Forwards the requester to a new page. 6 jsp:plugin - Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin. 7 jsp:element - Defines XML elements dynamically. 8 jsp:attribute - Defines dynamically-defined XML element's attribute. 9 jsp:body - Defines dynamically-defined XML element's body. 10 jsp:text - Used to write template text in JSP pages and documents.

135 JSP Templates If a Website has multiple pages with identical formats, which is common, even simple layout changes require modifications to all of the pages. To minimize the impact of layout changes, we need a mechanism for including layout in addition to content; that way, both layout and content can vary without modifying files that use them. That mechanism is JSP templates. (Same like CSS in HTML)

136 JSP Templates Templates are JSP files that include parameterized content. The templates have a set of custom tags: template:get, template:put, template:insert. Example <template:get name='header'/> <template:get name='content'/> <template:get name='footer'/> <template:insert template='/articletemplate.jsp'> <template:put name='header' content='/header.html' /> <template:put name='sidebar' content='/sidebar.jsp' /> <template:put name='content' content='/introduction.html'/> <template:put name='footer' content='/footer.html' /> </template:insert>

137 Outline Introduction to JSP Advantages of JSP over Servlet JSP Life cycle JSP Creation in Eclipse Elements of JSP page: directives, comments, scripting elements, actions and templates JDBC Connectivity with JSP.

138 JDBC Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers to connect with the database. Before JDBC, ODBC API was the database API to connect and execute query with the database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).

139 JDBC Driver JDBC Driver is a software component that enables java application to interact with the database. There are 4 types of JDBC drivers: 1. JDBC-ODBC bridge driver 2. Native-API driver (partially java driver) 3. Network Protocol driver (fully java driver) 4. Thin driver (fully java driver)

140 JDBC Connectivity with JSP Software Requirement 1 MySQL 2 MySQL Connector (Jar file) 3 Apache Tomcat Server 4 Eclipse Important Note: Copy MySQL Connector (Jar file) into Tomcat s Bin and Lib folder Before running program right click on project name -> Build path -> Configure build path -> Libraries -> Add External Jar file -> Mysql.jar file -> ok

141 JDBC Connectivity with JSP- Create table and add rows in database(mysql) Create the Employee table in the db1 database as follows mysql> Create database db1; mysql> use db1; mysql> create table emp ( id int, name varchar (255) ); Query OK, 0 rows affected (0.08 sec)

142 JDBC Connectivity with JSP- Create table and add rows in database(mysql) Insert Data mysql> INSERT INTO emp VALUES (100, 'Zara''); mysql> INSERT INTO Employees VALUES (101, 'Mamta');

143 JSP Code in Eclipse File->New->Web->Dynamic Web Project->Give Project Name Right click on Project name->new->package->give package name For Writing JSP Code project-> Right click->new->jsp file-> Give file name with.jsp Extension In Body tag write java code in script let tag <% %> Right click on.jsp file -> Run -> Run as Server

144 JDBC Connectivity with JSP- Example 1- JSP Code for to select data from emp table page import ="java.sql.*" %> page import ="javax.sql.*" %> <% Class.forName("com.mysql.jdbc.Driver"); java.sql.connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","root"); Statement st= con.createstatement(); ResultSet rs=st.executequery("select * from emp"); out.print("<h2 align=center>employee Database</h2>"); out.print("<table border=1 align=center>"); out.print("<tr><th> ENo</th> <th>ename</th></tr>");

145 JDBC Connectivity with JSP- Example 1- JSP Code for to select data from emp table while(rs.next()) { out.print("<tr align=center>"); out.print("<td>"); out.print(rs.getint(1)); out.print("</td>"); out.print("<td>"); out.print(rs.getstring(2)); out.print("</td>"); out.print("</tr>"); } %>

146 JDBC Connectivity with JSP- Example 2- JSP Code for insert data in emp table and display the inserted data from table It requires 2 files 1. S1.html (Html file to take values from user) 2. s2.jsp (jsp file to insert data in database and to display the inserted data)

147 JDBC Connectivity with JSP- Example 2- JSP Code for insert data in emp table and display the inserted data from table S1.html <html> <body> <form method="post" action= s2.jsp"> Enter Employee No<input type="text" name="t1"><br> Enter Empoyee Name <input type="text" name="t2"><br> <input type="submit" value="submit"> </form> </body> </html>

148 JDBC Connectivity with JSP- Example 2- JSP Code for insert data in emp table and display the inserted data from table S2.jsp page import ="java.sql.*" %> page import ="javax.sql.*" %> <% Class.forName("com.mysql.jdbc.Driver"); java.sql.connection con = DriverManager.getConnection("jdbc:mysql://localhost:3307/db1","root","root"); Statement st= con.createstatement(); int id= Integer.parseInt(request.getParameter("t1")); String name=request.getparameter("t2"); st.executeupdate("insert into emp values("+id+",'"+name+"')");

149 JDBC Connectivity with JSP- Example 2- JSP Code for insert data in emp table and display the inserted data from table ResultSet rs=st.executequery("select * from emp"); out.print("<h2 align=center>employee Database</h2>"); out.print("<table border=1 align=center>"); out.print("<tr><th> ENo</th><th>Ename</th></tr>"); while(rs.next()) { out.print("<tr align=center>"); out.print("<td>"); out.print(rs.getint(1)); out.print("</td>"); out.print("<td>"); out.print(rs.getstring(2)); out.print("</td>"); out.print("</tr>"); } %>

150 References

Unit III- Server Side Technologies

Unit III- Server Side Technologies Web Technology Unit III- Server Side Technologies By Prof. B.A.Khivsara Note: The material to prepare this presentation has been taken from internet and are generated only for students reference and not

More information

Unit-4: Servlet Sessions:

Unit-4: Servlet Sessions: 4.1 What Is Session Tracking? Unit-4: Servlet Sessions: Session tracking is the capability of a server to maintain the current state of a single client s sequential requests. Session simply means a particular

More information

JAVA SERVLET. Server-side Programming PROGRAMMING

JAVA SERVLET. Server-side Programming PROGRAMMING JAVA SERVLET Server-side Programming PROGRAMMING 1 AGENDA Passing Parameters Session Management Cookie Hidden Form URL Rewriting HttpSession 2 HTML FORMS Form data consists of name, value pairs Values

More information

JSP - SYNTAX. Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple and first example for JSP:

JSP - SYNTAX. Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple and first example for JSP: http://www.tutorialspoint.com/jsp/jsp_syntax.htm JSP - SYNTAX Copyright tutorialspoint.com This tutorial will give basic idea on simple syntax ie. elements involved with JSP development: The Scriptlet:

More information

Advantage of JSP over Servlet

Advantage of JSP over Servlet JSP technology is used to create web application just like Servlet technology. It can be thought of as an extension to servlet because it provides more functionality than servlet such as expression language,

More information

SERVLETS INTERVIEW QUESTIONS

SERVLETS INTERVIEW QUESTIONS SERVLETS INTERVIEW QUESTIONS http://www.tutorialspoint.com/servlets/servlets_interview_questions.htm Copyright tutorialspoint.com Dear readers, these Servlets Interview Questions have been designed especially

More information

Database Systems Lab. 11. JSP I 충남대학교컴퓨터공학과 데이타베이스시스템연구실

Database Systems Lab. 11. JSP I 충남대학교컴퓨터공학과 데이타베이스시스템연구실 데이타베이스시스템연구실 Database Systems Lab. 11. JSP I 충남대학교컴퓨터공학과 데이타베이스시스템연구실 Overview http://www.tutorialspoint.com/jsp/index.htm What is JavaServer Pages? JavaServer Pages (JSP) is a server-side programming

More information

AJP. CHAPTER 5: SERVLET -20 marks

AJP. CHAPTER 5: SERVLET -20 marks 1) Draw and explain the life cycle of servlet. (Explanation 3 Marks, Diagram -1 Marks) AJP CHAPTER 5: SERVLET -20 marks Ans : Three methods are central to the life cycle of a servlet. These are init( ),

More information

Unit 4 - Servlet. Servlet. Advantage of Servlet

Unit 4 - Servlet. Servlet. Advantage of Servlet Servlet Servlet technology is used to create web application, resides at server side and generates dynamic web page. Before Servlet, CGI (Common Gateway Interface) was popular as a server-side programming

More information

UNIT -5. Java Server Page

UNIT -5. Java Server Page UNIT -5 Java Server Page INDEX Introduction Life cycle of JSP Relation of applet and servlet with JSP JSP Scripting Elements Difference between JSP and Servlet Simple JSP program List of Questions Few

More information

Module 4: SERVLET and JSP

Module 4: SERVLET and JSP 1.What Is a Servlet? Module 4: SERVLET and JSP A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the Hyper

More information

Servlets and JSP (Java Server Pages)

Servlets and JSP (Java Server Pages) Servlets and JSP (Java Server Pages) XML HTTP CGI Web usability Last Week Nan Niu (nn@cs.toronto.edu) CSC309 -- Fall 2008 2 Servlets Generic Java2EE API for invoking and connecting to mini-servers (lightweight,

More information

Unit 5 JSP (Java Server Pages)

Unit 5 JSP (Java Server Pages) Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications. It focuses more on presentation logic

More information

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps.

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps. About the Tutorial Servlets provide a component-based, platform-independent method for building Webbased applications, without the performance limitations of CGI programs. Servlets have access to the entire

More information

Introduction. This course Software Architecture with Java will discuss the following topics:

Introduction. This course Software Architecture with Java will discuss the following topics: Introduction This course Software Architecture with Java will discuss the following topics: Java servlets Java Server Pages (JSP s) Java Beans JDBC, connections to RDBMS and SQL XML and XML translations

More information

Experiment No: Group B_2

Experiment No: Group B_2 Experiment No: Group B_2 R (2) N (5) Oral (3) Total (10) Dated Sign Problem Definition: A Web application for Concurrent implementation of ODD-EVEN SORT is to be designed using Real time Object Oriented

More information

Web based Applications, Tomcat and Servlets - Lab 3 -

Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems Web based Applications, - - CMPUT 391 Database Management Systems Department of Computing Science University of Alberta The Basic Web Server CMPUT 391 Database Management

More information

JdbcResultSet.java. import java.sql.*;

JdbcResultSet.java. import java.sql.*; 1)Write a program to display the current contents of the tables in the database where table name is Registration and attributes are id,firstname,lastname,age. JdbcResultSet.java import java.sql.*; public

More information

CE212 Web Application Programming Part 3

CE212 Web Application Programming Part 3 CE212 Web Application Programming Part 3 30/01/2018 CE212 Part 4 1 Servlets 1 A servlet is a Java program running in a server engine containing methods that respond to requests from browsers by generating

More information

Chettinad College of Engineering and Technology CHETTINAD COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY

Chettinad College of Engineering and Technology CHETTINAD COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY CHETTINAD COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY UNIT IV SERVLETS 1. What is Servlets? a. Servlets are server side components that provide a powerful mechanism

More information

Ch04 JavaServer Pages (JSP)

Ch04 JavaServer Pages (JSP) Ch04 JavaServer Pages (JSP) Introduce concepts of JSP Web components Compare JSP with Servlets Discuss JSP syntax, EL (expression language) Discuss the integrations with JSP Discuss the Standard Tag Library,

More information

JavaServer Pages (JSP)

JavaServer Pages (JSP) JavaServer Pages (JSP) The Context The Presentation Layer of a Web App the graphical (web) user interface frequent design changes usually, dynamically generated HTML pages Should we use servlets? No difficult

More information

Servlet Fudamentals. Celsina Bignoli

Servlet Fudamentals. Celsina Bignoli Servlet Fudamentals Celsina Bignoli bignolic@smccd.net What can you build with Servlets? Search Engines E-Commerce Applications Shopping Carts Product Catalogs Intranet Applications Groupware Applications:

More information

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003 Introduction This course Software Architecture with Java will discuss the following topics: Java servlets Java Server Pages (JSP s) Java Beans JDBC, connections to RDBMS and SQL XML and XML translations

More information

COMP9321 Web Application Engineering

COMP9321 Web Application Engineering COMP9321 Web Application Engineering Java Server Pages (JSP) Dr. Basem Suleiman Service Oriented Computing Group, CSE, UNSW Australia Semester 1, 2016, Week 3 http://webapps.cse.unsw.edu.au/webcms2/course/index.php?cid=2442

More information

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle Introduction Now that the concept of servlet is in place, let s move one step further and understand the basic classes and interfaces that java provides to deal with servlets. Java provides a servlet Application

More information

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature INTRODUCTION TO SERVLETS AND WEB CONTAINERS Actions in Accord with All the Laws of Nature Web server vs web container Most commercial web applications use Apache proven architecture and free license. Tomcat

More information

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http? What are Servlets? Servlets1 Fatemeh Abbasinejad abbasine@cs.ucdavis.edu A program that runs on a web server acting as middle layer between requests coming from a web browser and databases or applications

More information

SSC - Web applications and development Introduction and Java Servlet (I)

SSC - Web applications and development Introduction and Java Servlet (I) SSC - Web applications and development Introduction and Java Servlet (I) Shan He School for Computational Science University of Birmingham Module 06-19321: SSC Outline Outline of Topics What will we learn

More information

SNS COLLEGE OF ENGINEERING, Coimbatore

SNS COLLEGE OF ENGINEERING, Coimbatore SNS COLLEGE OF ENGINEERING, Coimbatore 641 107 Accredited by NAAC UGC with A Grade Approved by AICTE and Affiliated to Anna University, Chennai IT6503 WEB PROGRAMMING UNIT 04 APPLETS Java applets- Life

More information

The Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4

The Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4 CMPUT 391 Database Management Systems The Basic Web based Applications, - - CMPUT 391 Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems

More information

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1 Java Enterprise Edition Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1 Java Beans Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 2 Java Bean POJO class : private Attributes public

More information

UNIT-V. Web Servers: Tomcat Server Installation:

UNIT-V. Web Servers: Tomcat Server Installation: UNIT-V Web Servers: The Web server is meant for keeping Websites. It Stores and transmits web documents (files). It uses the HTTP protocol to connect to other computers and distribute information. Example:

More information

Advanced Internet Technology Lab # 4 Servlets

Advanced Internet Technology Lab # 4 Servlets Faculty of Engineering Computer Engineering Department Islamic University of Gaza 2011 Advanced Internet Technology Lab # 4 Servlets Eng. Doaa Abu Jabal Advanced Internet Technology Lab # 4 Servlets Objective:

More information

a. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22.

a. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22. Answers 1. What is the super interface to all the JDBC Drivers, specify their fully qualified name? a. Java.sql.Driver i. JDBC-ODBC Driver ii. Java-Native API Driver iii. All Java Net Driver iv. Java Native

More information

COMP9321 Web Application Engineering

COMP9321 Web Application Engineering COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 http://webapps.cse.unsw.edu.au/webcms2/course/index.php?cid=2411 1 Review:

More information

PSD1B Advance Java Programming Unit : I-V. PSD1B- Advance Java Programming

PSD1B Advance Java Programming Unit : I-V. PSD1B- Advance Java Programming PSD1B Advance Java Programming Unit : I-V PSD1B- Advance Java Programming 1 UNIT I - SYLLABUS Servlets Client Vs Server Types of Servlets Life Cycle of Servlets Architecture Session Tracking Cookies JDBC

More information

Introduction to JSP and Servlets Training 5-days

Introduction to JSP and Servlets Training 5-days QWERTYUIOP{ Introduction to JSP and Servlets Training 5-days Introduction to JSP and Servlets training course develops skills in JavaServer Pages, or JSP, which is the standard means of authoring dynamic

More information

Fast Track to Java EE 5 with Servlets, JSP & JDBC

Fast Track to Java EE 5 with Servlets, JSP & JDBC Duration: 5 days Description Java Enterprise Edition (Java EE 5) is a powerful platform for building web applications. The Java EE platform offers all the advantages of developing in Java plus a comprehensive

More information

Java Server Pages. JSP Part II

Java Server Pages. JSP Part II Java Server Pages JSP Part II Agenda Actions Beans JSP & JDBC MVC 2 Components Scripting Elements Directives Implicit Objects Actions 3 Actions Actions are XML-syntax tags used to control the servlet engine

More information

JAVA SERVLET. Server-side Programming INTRODUCTION

JAVA SERVLET. Server-side Programming INTRODUCTION JAVA SERVLET Server-side Programming INTRODUCTION 1 AGENDA Introduction Java Servlet Web/Application Server Servlet Life Cycle Web Application Life Cycle Servlet API Writing Servlet Program Summary 2 INTRODUCTION

More information

sessionx Desarrollo de Aplicaciones en Red A few more words about CGI CGI Servlet & JSP José Rafael Rojano Cáceres

sessionx Desarrollo de Aplicaciones en Red A few more words about CGI CGI Servlet & JSP José Rafael Rojano Cáceres sessionx Desarrollo de Aplicaciones en Red José Rafael Rojano Cáceres http://www.uv.mx/rrojano A few more words about Common Gateway Interface 1 2 CGI So originally CGI purpose was to let communicate a

More information

Session 8. Introduction to Servlets. Semester Project

Session 8. Introduction to Servlets. Semester Project Session 8 Introduction to Servlets 1 Semester Project Reverse engineer a version of the Oracle site You will be validating form fields with Ajax calls to a server You will use multiple formats for the

More information

INTERNET PROGRAMMING TEST-3 SCHEME OF EVALUATION 1.A 3 LIFE CYCLE METHODS - 3M 1.B HTML FORM CREATION - 2 M

INTERNET PROGRAMMING TEST-3 SCHEME OF EVALUATION 1.A 3 LIFE CYCLE METHODS - 3M 1.B HTML FORM CREATION - 2 M INTERNET PROGRAMMING TEST-3 SCHEME OF EVALUATION 1.A 3 LIFE CYCLE METHODS - 3M EXPLANATION - 1.B HTML FORM CREATION - 2 M SERVLET CODE IN POST METHOD IMPORT STATEMENTS - CLASS NAME AND METHOD (POST) -

More information

Database Applications Recitation 6. Project 3: CMUQFlix CMUQ s Movies Recommendation System

Database Applications Recitation 6. Project 3: CMUQFlix CMUQ s Movies Recommendation System 15-415 Database Applications Recitation 6 Project 3: CMUQFlix CMUQ s Movies Recommendation System 1 Project Objective 1. Set up a front-end website with PostgreSQL as the back-end 2. Allow users to login,

More information

Servlet Basics. Agenda

Servlet Basics. Agenda Servlet Basics 1 Agenda The basic structure of servlets A simple servlet that generates plain text A servlet that generates HTML Servlets and packages Some utilities that help build HTML The servlet life

More information

Servlets. An extension of a web server runs inside a servlet container

Servlets. An extension of a web server runs inside a servlet container Servlets What is a servlet? An extension of a web server runs inside a servlet container A Java class derived from the HttpServlet class A controller in webapplications captures requests can forward requests

More information

Unit 4 Java Server Pages

Unit 4 Java Server Pages Q1. List and Explain various stages of JSP life cycle. Briefly give the function of each phase. Ans. 1. A JSP life cycle can be defined as the entire process from its creation till the destruction. 2.

More information

Session 9. Introduction to Servlets. Lecture Objectives

Session 9. Introduction to Servlets. Lecture Objectives Session 9 Introduction to Servlets Lecture Objectives Understand the foundations for client/server Web interactions Understand the servlet life cycle 2 10/11/2018 1 Reading & Reference Reading Use the

More information

Table of Contents. Introduction... xxi

Table of Contents. Introduction... xxi Introduction... xxi Chapter 1: Getting Started with Web Applications in Java... 1 Introduction to Web Applications... 2 Benefits of Web Applications... 5 Technologies used in Web Applications... 5 Describing

More information

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests What is the servlet? Servlet is a script, which resides and executes on server side, to create dynamic HTML. In servlet programming we will use java language. A servlet can handle multiple requests concurrently.

More information

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013 Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013 Overview Dynamic web content genera2on (thus far) CGI Web server modules Server- side scrip2ng e.g. PHP, ASP, JSP Custom web server Java

More information

LAB 1 PREPARED BY : DR. AJUNE WANIS ISMAIL FACULTY OF COMPUTING UNIVERSITI TEKNOLOGI MALAYSIA

LAB 1 PREPARED BY : DR. AJUNE WANIS ISMAIL FACULTY OF COMPUTING UNIVERSITI TEKNOLOGI MALAYSIA LAB 1 PREPARED BY : DR. AJUNE WANIS ISMAIL FACULTY OF COMPUTING UNIVERSITI TEKNOLOGI MALAYSIA Setting up Java Development Kit This step involves downloading an implementation of the Java Software Development

More information

Java Server Page (JSP)

Java Server Page (JSP) Java Server Page (JSP) CS 4640 Programming Languages for Web Applications [Based in part on SWE432 and SWE632 materials by Jeff Offutt] [Robert W. Sebesta, Programming the World Wide Web] 1 Web Applications

More information

Handout 31 Web Design & Development

Handout 31 Web Design & Development Lecture 31 Session Tracking We have discussed the importance of session tracking in the previous handout. Now, we ll discover the basic techniques used for session tracking. Cookies are one of these techniques

More information

2. Follow the installation directions and install the server on ccc. 3. We will call the root of your installation as $TOMCAT_DIR

2. Follow the installation directions and install the server on ccc. 3. We will call the root of your installation as $TOMCAT_DIR Installing a Web Server 1. Install a sample web server, which supports Servlets/JSPs. A light weight web server is Apache Tomcat server. You can get the server from http://tomcat.apache.org/ 2. Follow

More information

Introduction to Java Servlets. SWE 432 Design and Implementation of Software for the Web

Introduction to Java Servlets. SWE 432 Design and Implementation of Software for the Web Introduction to Java Servlets James Baldo Jr. SWE 432 Design and Implementation of Software for the Web Web Applications A web application uses enabling technologies to 1. make web site contents dynamic

More information

Fast Track to Java EE

Fast Track to Java EE Java Enterprise Edition is a powerful platform for building web applications. This platform offers all the advantages of developing in Java plus a comprehensive suite of server-side technologies. This

More information

This course is intended for Java programmers who wish to write programs using many of the advanced Java features.

This course is intended for Java programmers who wish to write programs using many of the advanced Java features. COURSE DESCRIPTION: Advanced Java is a comprehensive study of many advanced Java topics. These include assertions, collection classes, searching and sorting, regular expressions, logging, bit manipulation,

More information

Advance Java. Configuring and Getting Servlet Init Parameters per servlet

Advance Java. Configuring and Getting Servlet Init Parameters per servlet Advance Java Understanding Servlets What are Servlet Components? Web Application Architecture Two tier, three tier and N-tier Arch. Client and Server side Components and their relation Introduction to

More information

Java4570: Session Tracking using Cookies *

Java4570: Session Tracking using Cookies * OpenStax-CNX module: m48571 1 Java4570: Session Tracking using Cookies * R.G. (Dick) Baldwin This work is produced by OpenStax-CNX and licensed under the Creative Commons Attribution License 4.0 Abstract

More information

Servlet And JSP. Mr. Nilesh Vishwasrao Patil, Government Polytechnic, Ahmednagar. Mr. Nilesh Vishwasrao Patil

Servlet And JSP. Mr. Nilesh Vishwasrao Patil, Government Polytechnic, Ahmednagar. Mr. Nilesh Vishwasrao Patil Servlet And JSP, Government Polytechnic, Ahmednagar Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To write servlet for cookies and session

More information

Servlets by Example. Joe Howse 7 June 2011

Servlets by Example. Joe Howse 7 June 2011 Servlets by Example Joe Howse 7 June 2011 What is a servlet? A servlet is a Java application that receives HTTP requests as input and generates HTTP responses as output. As the name implies, it runs on

More information

3. The pool should be added now. You can start Weblogic server and see if there s any error message.

3. The pool should be added now. You can start Weblogic server and see if there s any error message. CS 342 Software Engineering Lab: Weblogic server (w/ database pools) setup, Servlet, XMLC warming up Professor: David Wolber (wolber@usfca.edu), TA: Samson Yingfeng Su (ysu@cs.usfca.edu) Setup Weblogic

More information

ServletConfig Interface

ServletConfig Interface ServletConfig Interface Author : Rajat Categories : Advance Java An object of ServletConfig is created by the web container for each servlet. This object can be used to get configuration information from

More information

Welcome To PhillyJUG. 6:30-7:00 pm - Network, eat, find a seat 7:00-7:15 pm - Brief announcements 7:15-8:30 pm - Tom Janofsky's presentation

Welcome To PhillyJUG. 6:30-7:00 pm - Network, eat, find a seat 7:00-7:15 pm - Brief announcements 7:15-8:30 pm - Tom Janofsky's presentation Welcome To PhillyJUG 6:30-7:00 pm - Network, eat, find a seat 7:00-7:15 pm - Brief announcements 7:15-8:30 pm - Tom Janofsky's presentation Web Development With The Struts API Tom Janofsky Outline Background

More information

JavaServer Pages. What is JavaServer Pages?

JavaServer Pages. What is JavaServer Pages? JavaServer Pages SWE 642, Fall 2008 Nick Duan What is JavaServer Pages? JSP is a server-side scripting language in Java for constructing dynamic web pages based on Java Servlet, specifically it contains

More information

Introduction. This course Software Architecture with Java will discuss the following topics:

Introduction. This course Software Architecture with Java will discuss the following topics: Introduction This course Software Architecture with Java will discuss the following topics: Java servlets Java Server Pages (JSP s) Java Beans JDBC, connections to RDBMS and SQL XML and XML translations

More information

Java Servlets. Preparing your System

Java Servlets. Preparing your System Java Servlets Preparing to develop servlets Writing and running an Hello World servlet Servlet Life Cycle Methods The Servlet API Loading and Testing Servlets Preparing your System Locate the file jakarta-tomcat-3.3a.zip

More information

Session 20 Data Sharing Session 20 Data Sharing & Cookies

Session 20 Data Sharing Session 20 Data Sharing & Cookies Session 20 Data Sharing & Cookies 1 Reading Shared scopes Java EE 7 Tutorial Section 17.3 Reference http state management www.ietf.org/rfc/rfc2965.txt Cookies Reading & Reference en.wikipedia.org/wiki/http_cookie

More information

Chapter 10 Servlets and Java Server Pages

Chapter 10 Servlets and Java Server Pages Chapter 10 Servlets and Java Server Pages 10.1 Overview of Servlets A servlet is a Java class designed to be run in the context of a special servlet container An instance of the servlet class is instantiated

More information

112. Introduction to JSP

112. Introduction to JSP 112. Introduction to JSP Version 2.0.2 This two-day module introduces JavaServer Pages, or JSP, which is the standard means of authoring dynamic content for Web applications under the Java Enterprise platform.

More information

Principles and Techniques of DBMS 6 JSP & Servlet

Principles and Techniques of DBMS 6 JSP & Servlet Principles and Techniques of DBMS 6 JSP & Servlet Haopeng Chen REliable, INtelligent and Scalable Systems Group (REINS) Shanghai Jiao Tong University Shanghai, China http://reins.se.sjtu.edu.cn/~chenhp

More information

Introduction to Java Server Pages. Enabling Technologies - Plug-ins Scripted Pages

Introduction to Java Server Pages. Enabling Technologies - Plug-ins Scripted Pages Introduction to Java Server Pages Jeff Offutt & Ye Wu http://www.ise.gmu.edu/~offutt/ SWE 432 Design and Implementation of Software for the Web From servlets lecture. Enabling Technologies - Plug-ins Scripted

More information

Component Based Software Engineering

Component Based Software Engineering Component Based Software Engineering Masato Suzuki School of Information Science Japan Advanced Institute of Science and Technology 1 Schedule Mar. 10 13:30-15:00 : 09. Introduction and basic concepts

More information

Lab session Google Application Engine - GAE. Navid Nikaein

Lab session Google Application Engine - GAE. Navid Nikaein Lab session Google Application Engine - GAE Navid Nikaein Available projects Project Company contact Mobile Financial Services Innovation TIC Vasco Mendès Bluetooth low energy Application on Smart Phone

More information

Using Java servlets to generate dynamic WAP content

Using Java servlets to generate dynamic WAP content C H A P T E R 2 4 Using Java servlets to generate dynamic WAP content 24.1 Generating dynamic WAP content 380 24.2 The role of the servlet 381 24.3 Generating output to WAP clients 382 24.4 Invoking a

More information

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introducing Object Oriented Programming... 2 Explaining OOP concepts... 2 Objects...3

More information

One application has servlet context(s).

One application has servlet context(s). FINALTERM EXAMINATION Spring 2010 CS506- Web Design and Development DSN stands for. Domain System Name Data Source Name Database System Name Database Simple Name One application has servlet context(s).

More information

112-WL. Introduction to JSP with WebLogic

112-WL. Introduction to JSP with WebLogic Version 10.3.0 This two-day module introduces JavaServer Pages, or JSP, which is the standard means of authoring dynamic content for Web applications under the Java Enterprise platform. The module begins

More information

CS506 Web Design & Development Final Term Solved MCQs with Reference

CS506 Web Design & Development Final Term Solved MCQs with Reference with Reference I am student in MCS (Virtual University of Pakistan). All the MCQs are solved by me. I followed the Moaaz pattern in Writing and Layout this document. Because many students are familiar

More information

EXPERIMENT- 9. Login.html

EXPERIMENT- 9. Login.html EXPERIMENT- 9 To write a program that takes a name as input and on submit it shows a hello page with name taken from the request. And it shows starting time at the right top corner of the page and provides

More information

Enterprise Java Unit 1- Chapter 3 Prof. Sujata Rizal Introduction to Servlets

Enterprise Java Unit 1- Chapter 3 Prof. Sujata Rizal Introduction to Servlets 1. Introduction How do the pages you're reading in your favorite Web browser show up there? When you log into your favorite Web site, how does the Web site know that you're you? And how do Web retailers

More information

COMP9321 Web Application Engineering

COMP9321 Web Application Engineering COMP9321 Web Application Engineering Semester 2, 2017 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 http://webapps.cse.unsw.edu.au/webcms2/course/index.php?cid=2465 1 Review:

More information

Servlet and JSP Review

Servlet and JSP Review 2006 Marty Hall Servlet and JSP Review A Recap of the Basics 2 JSP, Servlet, Struts, JSF, AJAX, & Java 5 Training: http://courses.coreservlets.com J2EE Books from Sun Press: http://www.coreservlets.com

More information

CS433 Technology Overview

CS433 Technology Overview CS433 Technology Overview Scott Selikoff Cornell University November 13, 2002 Outline I. Introduction II. Stored Procedures III. Java Beans IV. JSPs/Servlets V. JSPs vs. Servlets VI. XML Introduction VII.

More information

LearningPatterns, Inc. Courseware Student Guide

LearningPatterns, Inc. Courseware Student Guide Fast Track to Servlets and JSP Developer's Workshop LearningPatterns, Inc. Courseware Student Guide This material is copyrighted by LearningPatterns Inc. This content shall not be reproduced, edited, or

More information

JSP Scripting Elements

JSP Scripting Elements JSP Scripting Elements Core Servlets & JSP book: More Servlets & JSP book: www.moreservlets.com Servlet and JSP Training Courses: courses.coreservlets.com 1 Slides Marty Hall, http://, book Sun Microsystems

More information

Advanced Web Technology

Advanced Web Technology Berne University of Applied Sciences Dr. E. Benoist Winter Term 2005-2006 Presentation 1 Presentation of the Course Part Java and the Web Servlet JSP and JSP Deployment The Model View Controler (Java Server

More information

PES INSTITUTE OF TECHNOLOGY, SOUTH CAMPUS DEPARTMENT OF MCA INTERNAL TEST (SCHEME AND SOLUTION) II

PES INSTITUTE OF TECHNOLOGY, SOUTH CAMPUS DEPARTMENT OF MCA INTERNAL TEST (SCHEME AND SOLUTION) II PES INSTITUTE OF TECHNOLOGY, SOUTH CAMPUS DEPARTMENT OF MCA INTERNAL TEST (SCHEME AND SOLUTION) II Subject Name: Advanced JAVA programming Subject Code: 13MCA42 Time: 11:30-01:00PM Max.Marks: 50M ----------------------------------------------------------------------------------------------------------------

More information

CSC309: Introduction to Web Programming. Lecture 10

CSC309: Introduction to Web Programming. Lecture 10 CSC309: Introduction to Web Programming Lecture 10 Wael Aboulsaadat WebServer - WebApp Communication 2. Servlets Web Browser Get servlet/serv1? key1=val1&key2=val2 Web Server Servlet Engine WebApp1 serv1

More information

Servlet. Web Server. Servlets are modules of Java code that run in web server. Internet Explorer. Servlet. Fire Fox. Servlet.

Servlet. Web Server. Servlets are modules of Java code that run in web server. Internet Explorer. Servlet. Fire Fox. Servlet. Servlet OOS Lab Servlet OOS Servlets are modules of Java code that run in web server. Internet Explorer Web Server Fire Fox Servlet Servlet Servlet Java Application 2 Servlet - Example OOS import java.io.*;

More information

Writing Servlets and JSPs p. 1 Writing a Servlet p. 1 Writing a JSP p. 7 Compiling a Servlet p. 10 Packaging Servlets and JSPs p.

Writing Servlets and JSPs p. 1 Writing a Servlet p. 1 Writing a JSP p. 7 Compiling a Servlet p. 10 Packaging Servlets and JSPs p. Preface p. xiii Writing Servlets and JSPs p. 1 Writing a Servlet p. 1 Writing a JSP p. 7 Compiling a Servlet p. 10 Packaging Servlets and JSPs p. 11 Creating the Deployment Descriptor p. 14 Deploying Servlets

More information

Advanced Java Programming

Advanced Java Programming Advanced Java Programming Length: 4 days Description: This course presents several advanced topics of the Java programming language, including Servlets, Object Serialization and Enterprise JavaBeans. In

More information

First Simple Interactive JSP example

First Simple Interactive JSP example Let s look at our first simple interactive JSP example named hellojsp.jsp. In his Hello User example, the HTML page takes a user name from a HTML form and sends a request to a JSP page, and JSP page generates

More information

Backend. (Very) Simple server examples

Backend. (Very) Simple server examples Backend (Very) Simple server examples Web server example Browser HTML form HTTP/GET Webserver / Servlet JDBC DB Student example sqlite>.schema CREATE TABLE students(id integer primary key asc,name varchar(30));

More information

Université du Québec à Montréal

Université du Québec à Montréal Laboratoire de Recherches sur les Technologies du Commerce Électronique Université du Québec à Montréal Rapport de recherche Latece 2017-3 Identifying KDM Model of JSP Pages Anas Shatnawi, Hafedh Mili,

More information

JSP - ACTIONS. There is only one syntax for the Action element, as it conforms to the XML standard:

JSP - ACTIONS. There is only one syntax for the Action element, as it conforms to the XML standard: http://www.tutorialspoint.com/jsp/jsp_actions.htm JSP - ACTIONS Copyright tutorialspoint.com JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically

More information

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2 Java Servlets Adv. Web Technologies 1) Servlets (introduction) Emmanuel Benoist Fall Term 2016-17 Introduction HttpServlets Class HttpServletResponse HttpServletRequest Lifecycle Methods Session Handling

More information

ICOM 5016 Database Systems. Database Users. User Interfaces and Tools. Chapter 8: Application Design and Development.

ICOM 5016 Database Systems. Database Users. User Interfaces and Tools. Chapter 8: Application Design and Development. Chapter 8: Application Design and Development ICOM 5016 Database Systems Web Application Amir H. Chinaei Department of Electrical and Computer Engineering University of Puerto Rico, Mayagüez User Interfaces

More information