1 / 57

Why server side programming ?

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

Télécharger la présentation

Why server side programming ?

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Why server side programming ?

  2. What is java servlet ?

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

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

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

  6. Java servlet architecture <<interface>> Javax.servlet.ServletConfig ------------------------------ ------------------------------ getInitParameter( ) getServletContex( ) getInitParameterNames( ) <<interface>> Javax.servlet.Servlet ------------------------------ ------------------------------ Init( ) getServletConfig( ) service( ) getServletInfo( ) Destroy() <<interface>> 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()

  7. 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()

  8. 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();

  9. Simple servlet to display hello

  10. // 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("<hr/>"); out.print("<h3>Hello again Servlet</h3>"); } }

  11. 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("<table border=2><tr><th>Doller</th><th>Rs.</th></tr>"); for(i=1;i<10;i++) out.print(“<tr><td>“ + i + “</td><td>“ + i*50 + “</td></tr>”); } }

  12. 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 3-6-2006 "; } }

  13. Java servlet architecture <<interface>> Javax.servlet.ServletConfig ------------------------------ ------------------------------ <<interface>> Javax.servlet.Servlet ------------------------------ <<interface>> Javax.io.Serializable ------------------------------ ------------------------------ Javax.servlet.GenricServlet ------------------------------------- ------------------------------------- Javax.servlet.http.HttpServlet ------------------------------------- ------------------------------------- AgainHello

  14. The methods overridden by AgainHello • init() • doGet() • doPost() • getServletInfo()

  15. Httpservlet request object • getCookies(); • getMethod(); • getPathInfo(); • getServletPath(); • getContextPath();

  16. //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("<h1>Servlet myservlet at " + request.getContextPath () + "</h1>"); out.println("<p> servlet path : : " + request.getServletPath() +" </p>"); out.println("<p>the name of this servlet : : " + getServletInfo() +" </p>"); } public String getServletInfo() { return “Description for request methode Created by A. Yeole on 3-6-2006 "; } }

  17. Html form has action servlet

  18. // html file myhtml.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> </head> <body> <form action="myservlet“ method=“GET" > <input type="submit" value="click me" name="b1" /> </form> <form action="myservlet" method="POST" enctype="multipart/form-data"> <input type="submit" value="click me post" /> </form> </body> </html>

  19. // 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("<html>"); out.println("<head>"); out.println("<title>Servlet myservlet</title>"); out.println("</head>"); out.println("<body>"); out.print("<h1>MY FAVORITE SUBJECTS</h1>"); out.print("<li>Operating Systems</li>"); out.print("<li>Java</li>"); out.print("<li>Maths</li>"); out.print("<li>C</li>"); out.println("</body>"); out.println("</html>"); 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); } }

  20. 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);

  21. //form.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> </head> <body> <form name="form1" action="formservlet"> <br> Email : <input type="text" name="email" value="" size="20" /><br> <br> Are U registered user : <input type="radio" name="reg" value="registered" checked="checked" />Yes <input type="radio" name="reg" value="unregistered" />No<br><br> <input type="submit" value="submit" name="submit" /><br> </form> </body> </html>

  22. //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("<html>"); out.println("<head>"); out.println("</head>"); out.println("<body>"); String email = request.getParameter("email"); String rg = request.getParameter("reg"); out.println("<p>the mail id u have entered : : " + email +" </p>"); if (rg.equals("registered")) out.println("<h1> Registered user </h1>"); if (rg.equals("unregistered")) out.println("<h1> UnRegistered user </h1>"); out.println("</body>"); out.close(); }

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

  24. 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( "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + "<TH>Parameter Name<TH>Parameter Value(s)"); Enumeration paramNames = request.getParameterNames(); while(paramNames.hasMoreElements()) { String paramName = (String)paramNames.nextElement(); out.println("<TR><TD>" + paramName + "\n<TD>"); String[] paramValues = request.getParameterValues(paramName);

  25. if (paramValues.length == 1) { String paramValue = paramValues[0]; if (paramValue.length() == 0) out.print("<I>No Value</I>"); else out.print(paramValue); } else { out.println("<UL>"); for(int i=0; i<paramValues.length; i++) { out.println("<LI>" + paramValues[i]); } out.println("</UL>"); } } out.println("</TABLE>\n</BODY></HTML>"); 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"; } }

  26. Listing All Form Data

  27. // 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)"); } }

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

  29. 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(); } }

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

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

  32. Application space Java application JDBC ODBC bridge ODBC driver Database

  33. Installing and setting up ODBC bridge Control panel

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

  35. 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”

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

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

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

  39. 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() ;

  40. Sim.java

  41. PreparedStatement • The PreparedStatement interface inherits from Statement . • Instances of PreparedStatement contain an SQL statement that has already been compiled. • 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.

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

  43. Pre.java

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

  45. 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() ;

  46. 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() ;

  47. //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("<html>"); out.println("<head>"); out.println("</head>"); out.println("<body>"); String email = request.getParameter("email"); 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(“’+email+”’,”’+rg+””)”); Out.println(“record insetred “);

More Related