Why server side programming ?. What is java servlet ?

Slides:



Advertisements
Similar presentations
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Advertisements

Introduction to Servlets Based on: Hall, Brown, Core Servlets and JavaServer Pages.
Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
An introduction to Java Servlet Programming
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
Servlets. A form The HTML source Chapter 1 Please enter your name and password then press start Name: Password: In Netbeans you can graphically create.
2/16/2004 Dynamic Content February 16, /16/2004 Assignments Due – Message of the Day Part 1 Due – Reading and Warmup Work on Message of the Day.
1 CS6320 – Servlet Structure and Lifecycle L. Grewe.
Object-Oriented Enterprise Application Development Introduction to Servlets.
Servlets Replace Common Gateway Interface Scripts Extend Server Functionality Modules (software components) Like applets to browsers No GUI.
Comp2513 Java Servlet Basics Daniel L. Silver, Ph.D.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
Michael Brockway Application Integration Servlets l Introduction & Overview l HTTP Servlets l HTTP get Requests l HTTP post Requests l Multi-tier Applications.
A Servlet’s Job Read explicit data sent by client (form data) Read implicit data sent by client (request headers) Generate the results Send the explicit.
Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
1 Servlet How can a HTML page, displayed using a browser, cause a program on a server to be executed?
Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server application to answer client requests. Servlets are.
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
Objectives Java Servlet Web Components
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
Java Servlets and Java Server Pages Carol Wolf Computer Science.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
111 Java Servlets Dynamic Web Pages (Program Files) Servlets versus Java Server Pages Implementing Servlets Example: F15 Warranty Registration Tomcat Configuration.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Session tracking There are a number of problems that arise from the fact that HTTP is a "stateless" protocol. In particular, when you are doing on- line.
Java Servlets. Servlets When we run small Java programs within a browser these are referred to as Applets... And when we run small Java programs within.
Mark Dixon 1 09 – Java Servlets. Mark Dixon 2 Session Aims & Objectives Aims –To cover a range of web-application design techniques Objectives, by end.
Java Servlets & Java Server Pages Lecture July 2013.
S ERVLETS Hits Counter 21-Nov-15. S ERVLETS - H ITS C OUNTER Many times you would be interested in knowing total number of hits on a particular page of.
A seminar on j2ee by saritha. s. What is J2EE J2EE (Java 2 Platform, Enterprise Edition) is a Java platform designed for the mainframe-scale computing.
Java Servlet API CGI / HTTP Concepts Java Servlet API.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
Top right corner for field-mark, customer or partner logotypes. See Best practice for example. Slide title 40 pt Slide subtitle 24 pt Text 24 pt Bullets.
Li Tak Sing COMPS311F. A web page that counts the number of times that you have visited the page. You can try the page at:
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
 2002 Prentice Hall. All rights reserved. 9.8 Multi-Tier Applications: Using JDBC from a Servlet Three-tier distributed applications –User interface –Business.
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
Servlets.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
Mark Dixon 1 11 – Java Servlets. Mark Dixon 2 Session Aims & Objectives Aims –To cover a range of web-application design techniques Objectives, by end.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
Introduction to Servlets. Introduction Servlet is a language to develop the server side applications, and it is also server side component. It can develop.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
Java Servlets Java Server Pages (JSP)
Java Servlets and Java Server Pages
How CGI and Java Servlets are Run By David Stein 14 November 2006.
Chapter 4 Request and Response. Servlets are controlled by the container.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
S ERVLETS Form Data 19-Mar-16. F ORM P ROCESSING You must have come across many situations when you need to pass some information from your browser to.
Java Database Connectivity JDBC. Open Database Connectivity developed by Microsoft to provide interaction with databases using SQL. Use the JDBC-ODBC.
Introduction to Servlets
Servlets.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Servlets Hits Counter 20-Jul-18.
Servlet.
Chapter 26 Servlets.
Servlets and Java Server Pages
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Web Search Interfaces.
Presentation transcript:

Why server side programming ?

What is java servlet ?

Practical applications of java servlets –Developing ecommerce –Web site that open up large legacy system on internet –Distributed object application on web

Alternatives for servlets CGI creates new process for each CGI request implemented in perl (require interpreter for every req. ) server side java script Javascript into precompiled HTML pages. Nerscape’s Enterprise and fasttrack server ASP Not precompiled tied to specific web server IIS

Why servlet? Efficient »Initialization only first time, then it call’s service Persistent »Maintain state between requests( It stay resident in memory) Portable »Because they are in java. Robust »Well define exception handling. Extensible »Polymorphism and inheritance Secure »Server side »Java security manager

Java servlet architecture > Javax.servlet.Servlet Init( ) getServletConfig( ) service( ) getServletInfo( ) Destroy() > Javax.servlet.ServletConfig getInitParameter( ) getServletContex( ) getInitParameterNames( ) > Javax.io.Serializable Javax.servlet.GenricServlet getInitParameter( ) getServletContext( ) getInitParameterNames( ) log( ) init() getServletConfig() service() getServletInfo() destory() Javax.servlet.http.HttpServlet doDelete() doGet() doOptions() doPost() doPut() doTrace() getLastModified() service()

Genericservlet and HttpServlet No main() it calls servlets service() method. GenericServlet.service() Public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException Httpservlet.sevice() Public abstract void service(HttpServletRequest rq, HttpServletResponse rs) throws ServletException, IOException It’s already implemented. Depending upon METHOD stored in request it overrides doGet() or doPost()

Life cycle of servlet java.servlet.Servlet interface –init() »Call immediately after server initialize. »It initializes resources that will be using for request. »Public void init(ServletConfig config) throws Servletexception –service() »Handle all request send by client. starts aftre init() »Public abstract void service (ServletRequest req, ServletResponse res) throws ServletException, IOException –destory() »End of servlet life »Return all resource eg close database connection »Good place to save persistent information »Public void destory();

Simple servlet to display hello

// simple servlet to display “Hello again servlet “ import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AgainHello extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print(" "); out.print(" Hello again Servlet "); }

import javax.servlet.ServletException; import javax.servlet.http. *; public class AgainHello extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { public void init (ServletConfig config) throws servletException {super.init(config)} protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print(" Doller Rs. "); for(i=1;i<10;i++) out.print(“ “ + i + “ “ + i*50 + “ ”); }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } public String getServletInfo() { return “Description for request method Created by A. Yeole on "; }

Java servlet architecture > Javax.servlet.Servlet > Javax.servlet.ServletConfig > Javax.io.Serializable Javax.servlet.GenricServlet Javax.servlet.http.HttpServlet AgainHello

The methods overridden by AgainHello init() doGet() doPost() getServletInfo()

Httpservlet request object getCookies(); getMethod(); getPathInfo(); getServletPath(); getContextPath();

//myservlet.java import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AgainHello extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(" Servlet myservlet at " + request.getContextPath () + " "); out.println(" servlet path : : " + request.getServletPath() +" "); out.println(" the name of this servlet : : " + getServletInfo() +" "); } public String getServletInfo() { return “Description for request methode Created by A. Yeole on "; }

Html form has action servlet

// html file myhtml.html

// file myservlet.java import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; public class myservlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println(" "); out.println(" "); out.println(" Servlet myservlet "); out.println(" "); out.println(" "); out.print(" MY FAVORITE SUBJECTS "); out.print(" Operating Systems "); out.print(" Java "); out.print(" Maths "); out.print(" C "); out.println(" "); out.println(" "); out.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } }

Retrieving form data in a servlet Three methods are used to retrieve request parameters are the ServletRequest’ Public Enumeration ServletRequest.getParameterNames(); Public String ServletRequest.getParameter(String name); Public String[] ServletRequest.getParameterValues(String n);

//form.html Are U registered user : Yes No

//formservlet.java prog for reading data from form import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.http.HttpServletRequest; public class formservlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(" "); out.println(" "); out.println(" "); out.println(" "); String = request.getParameter(" "); String rg = request.getParameter("reg"); out.println(" the mail id u have entered : : " + +" "); if (rg.equals("registered")) out.println(" Registered user "); if (rg.equals("unregistered")) out.println(" UnRegistered user "); out.println(" "); out.close(); }

Use of getParameterNames() Enumeration p = request.getParameterNames(); String s; While(p.hasMoreElements()) { s = (String)p.nextElement(); out.printnl(s + “ : “ + request.getParameter(s) ); }

import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class servlet2 extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading All Request Parameters"; out.println( " \n" + " " + title + " \n" + " \n" + " Parameter Name Parameter Value(s)"); Enumeration paramNames = request.getParameterNames(); while(paramNames.hasMoreElements()) { String paramName = (String)paramNames.nextElement(); out.println(" " + paramName + "\n "); String[] paramValues = request.getParameterValues(paramName);

if (paramValues.length == 1) { String paramValue = paramValues[0]; if (paramValue.length() == 0) out.print(" No Value "); else out.print(paramValue); } else { out.println(" "); for(int i=0; i<paramValues.length; i++) { out.println(" " + paramValues[i]); } out.println(" "); } out.println(" \n "); out.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } public String getServletInfo() { return "Short description"; } }

Listing All Form Data

// content of response - excel import java.io.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ApplesOranges extends javax.servlet.http.HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/vnd.ms-excel"); PrintWriter out = response.getWriter(); out.println("\tQ1\tQ2\tQ3\tQ4\tTOTAL"); out.println("Apples\t78\t87\t29\t10\t=Sum(b2:e2)"); out.println("Oranges\t77\t86\t93\t10\t=Sum(b3:e3)"); }

Parsing initialization parameters Initialization parameters are not part of request. they are passed to the servlet when it first loaded. Therefore u have access to them in init() method. The value of these parameter does not change until the servlet reloaded.

import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; public class myservlet1 extends HttpServlet { private String message; private String defaultMessage = "No message."; private int repeats = 1; public void init(ServletConfig config) throws ServletException { message = config.getInitParameter(“company"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println(“Wel come to ” + message); out.close(); } }

What is jdbc It is a pure java API used to execute sql statements. Basic step : 1.Open connection to database 2.Execute sql statement 3.Process the result 4.Close connection

JDBC driver is JDBC ODBC bridge provided by sun jdk1.1 and later. It provides jdbc access to database trough odbc.

Application space Java application JDBC ODBC bridge ODBC driver Database

Installing and setting up ODBC bridge Control panel

Establishing database connection 1. load JDBC driver 2. make connection

1. load JDBC driver The class name of the JDBC-ODBC bridge driver is sun.jdbc.odbc.JdbcOdbcDriver. When a driver is loaded, it registers itself with Drivermanager which is then used to get the Connection. 1.new JdbcOdbcDriver(); Will load a new driver object, calling its constructor. 2.Other way is class.forName(“JdbcOdbcDriver”) “forName” method of the “class” in “java.lang package”

2.Make connection We connect to database using the static method getConnection() method of DriverManager class that returns a connection. To get a connection, we need to specify a url for the actual database we wish to use. The form of this url is specific to the driver we are using. With the driver loaded, we can use the properties file above to get the database url. Using the Sun JDBC-ODBC bridge driver, the url of the database is jdb:odbc:xxx where xxx is the ODBC data source name registered for your database. String url = "jdbc:odbc:anjali"; String user=""; String password =""; Connection con =DriverManager.getConnection(url,user,password); Open connection to database. you will be using it to create JDBC statements to the database.

Using statment A Statement is obtained from a Connection: Statement stmt = con.createStatement() ; Once you have a Statement, you can use it to execute, and control the execution of, various kinds of SQL queries. Use stmt.executeUpdate with a string argument containing the text of an SQL update query (INSERT, DELETE or UPDATE). This returns an integer count of the number of rows updated. Use stmt.executeQuery with a string argument containing the text of an SQL SELECT query. This returns a ResultSet object which is used to access the rows of the query results. int count = stmt.executeUpdate("INSERT INTO Customers " + "(CustomerFirstName, CustomerLastName, CustomerAddress) " "VALUES ('Tony', 'Blair', '10 Downing Street, London')") ; ResultSet rs = stmt.executeQuery("SELECT * FROM Customers") ; // do something with count and RS

Retrieving Information When executing an SQL statement that returns results, we use the executeQuery method which returns Resultset containing the row of data that satisfy the query Executing ResultSet rs = stmt.exectueQuery (“SELECT * FROM customer”); returns the rows containing the names, add of all entries in customer.

Working with ResultSets If you do not know exactly the table structure (the schema) of the ResultSet, you can obtain it via a ResultSetMetaData object ResultSetMetaData rsmd = rs.getMetaData() ; int colCount = rsmd.getColumnCount() ; for (int i = 1 ; i <= colCount ; i++) { if (i > 1) out.print(", "); out.print(rsmd.getColumnLabel(i)) ; } out.println() ;

Sim.java

PreparedStatement The PreparedStatement interface inherits from Statement. 1.Instances of PreparedStatement contain an SQL statement that has already been compiled. 2.The SQL statement contained in a PreparedStatement object may have one or more IN parameters. Because PreparedStatement objects are precompiled, their execution can be faster than that of Statement objects.

Being a subclass of Statement, PreparedStatement inherits all the functionality of Statement. In addition, it adds a set of methods that are needed for setting the values to be sent to the database in place of the placeholders for IN parameters. Also, the three methods execute, executeQuery, and executeUpdate are modified so that they take no argument.

Pre.java

Transactions Transactions are a mechanism to group operations together so that either all of them complete together successfully or none of them do.

When a Connection is obtained, by default its AutoCommit property is set to true. This means that every query execution is committed immediately after it is executed and before the next one is executed. To enable grouping of operations in transactions, you have to switch the AutoCommit property off: con.setAutoCommit(false) ; Now you have to obtain new statement objects from the connection (the old ones won't work), and query or update as usual. When all operations that you want to group together have completed, you must commit the updates to the database: con.commit() ;

At this point you can continue with more operations which will be grouped into a new transaction or you can switch AutoCommit back on: con.setAutoCommit(true) ; anything goes wrong during a transaction (e.g. an Exception is thrown or an error means that you cannot complete your group of operations) then you have to undo all operations in your transaction so far: con.rollBack() ;

//formservlet.java prog for database connectivity import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.http.HttpServletRequest; public class formservlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(" "); out.println(" "); out.println(" "); out.println(" "); String = request.getParameter(" "); String rg = request.getParameter(“name"); try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:anjali","",""); Statement stmt = con.createStatement(); int rs = st.executeUpdate(“insert into directory values(“’+ +”’,”’+rg+””)”); Out.println(“record insetred “);

Statement stmt1 = con.createStatement(); ResultSet rs1= st1.executeQuery(“select * from directory”); While (rs1.next()) { Out.println(“ ” + rs1.getString(“ ”) + “ “ + rs1.getString(“phone”) ); Out.println( ); } Con.close(); } out.println(" "); out.close(); }

Session Tracking

HttpSession object Using sessions in servlets is quite straightforward. involves –looking up the session object associated with the current request. – creating a new session object when necessary. – looking up information associated with a session. – storing information in a session, and –discarding completed or abandoned sessions.

Looking up the HttpSession object associated with the current request. This is done by calling the getSession method of HttpServletRequest. If this returns null, you can create a new session, but this is so commonly done that there is an option to automatically create a new session if there isn't one already. Just pass true to getSession. HttpSession session = request.getSession(true);

Looking up Information Associated with a Session. HttpSession objects live on the server; they're just automatically associated with the requester. These session objects have a built-in data structure that let you store any number of keys and associated values getAttribute, setAttribute

Although the data that was explicitly associated with a session is the part you care most about, there are some other pieces of information that are sometimes useful as well. getId. This method returns the unique identifier generated for each session. It is sometimes used as the key name when there is only a single value associated with a session, or when logging information about previous sessions. isNew. This returns true if the client (browser) has never seen the session, usually because it was just created rather than being referenced by an incoming client request. It returns false for preexisting sessions getCreationTime. This returns the time, in milliseconds since the epoch, at which the session was made. To get a value useful for printing out, pass the value to the Date constructor or the setTimeInMillis method of GregorianCalendar. getLastAccessedTime. This returns the time, in milliseconds since the epoch, at which the session was last sent from the client. getMaxInactiveInterval. This returns the amount of time, in seconds, that a session should go without access before being automatically invalidated. A negative value indicates that the session should never timeout.

Httpsession1.java –last access date Httpsession2.java –No of access