1 / 93

Programming in Java, 2e

Programming in Java, 2e. Sachin Malhotra Saurabh Choudhary. Chapter 16. Introduction to Advanced Java. Objectives. Handle databases Do server side programming with Servlets Learn basic of JSP Learn basic of Java beans and jar files Create remote application using RMI Learn basics of EJB.

moyes
Download Presentation

Programming in Java, 2e

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. Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

  2. Chapter 16 Introduction to Advanced Java

  3. Objectives • Handle databases • Do server side programming with Servlets • Learn basic of JSP • Learn basic of Java beans and jar files • Create remote application using RMI • Learn basics of EJB

  4. DATABASE HANDLING USING JDBC • JDBC stands for Java database connectivity. • a standard API for all Java programs to connect to databases. The JDBC API is available in two packages: • Core API java.sql. • Standard extension to JDBC API javax.sql (supports connection pooling, transactions, etc.) • JDBC defines a few steps to connect to a database and retrieve/insert/update databases. • The steps are as follows: • Load the driver • Establish connection • Create statements • Execute query and obtain result • Iterate through the results

  5. Load the Driver • The driver is loaded with the help of a static method, • Class.forName(drivername) • Every database has its own driver. • All the JDBC drivers have been classified into four categories: • Type 1: JDBC ODBC bridge driver • Type 2: Native-API/partly Java driver • Type 3: Net-protocol driver • Type 4: Pure Java driver

  6. Driver Names

  7. JDBC ODBC Bridge Driver

  8. Native API/ Partly Java Driver

  9. Type 3: Net Protocol Driver

  10. Type 4: Pure Java Driver

  11. Establish a Connection • A connection to the database is established using the static method getConnection(databaseUrl) of the DriverManager class. • The DriverManager class is class for managing JDBC drivers. • The database URL takes the following shape jdbc:subprotocol:subname. • If any problem occurs during accessing the database, an SQLException is generated, else a Connection object is returned which refers to a connection to a database. • Connection is actually an interface in java.sql package. • Connection con=DriverManager.getConnection(databaseUrl);

  12. Few Database URLs

  13. Create Statement • The connection is used to send SQL statements to the database. • three interfaces are used for sending SQL statements to databases • Statement and its two sub-interfaces, • PreparedStatement and Callable Statement. • Three methods of the Connection object are used to return objects of these three statements. • A Statement object is used to send a simple SQL statement to the database with no parameters. • Statement stmt = con.createStatement();

  14. Create Statement (contd.) • A PreparedStatement object sends precompiled statements to the databases with or without IN parameters. • If n rows need to be inserted, then the same statement gets compiled n number of times. • So to increase efficiency, we use precompiled PreparedStatement. • only the values that have to be inserted are sent to the database again and again. • PreparedStatement ps = con.prepareStatement(String query); • A CallableStatement object is used to call stored procedures. • CallableStatement cs = con.prepareCall(String query);

  15. Execute Query • Three methods are used • ResultSet executeQuery(String sqlQuery) throws SQLException • int executeUpdate(String sqlQuery) throws SQLException • boolean execute(String sqlQuery) throws SQLException • executeQuery is used for executing SQL statements that return a single ResultSet, e.g. a select statement. • The rows fetched from database are returned as a single ResultSet object. For example, • ResultSet rs=stmt.executeQuery(“select * from emp”); • executeUpdate is used for DDL and DML SQL statements like insert,update, delete, and create. • returns an integer value for DML to indicate the number of rows affected and 0 for DDL statements which do not return anything.

  16. Execute Query (contd.) • PreparedStatement ps = con.prepareStatement(“update emp set salary=? where empid=?”); • The statement is sent to database and is prepared for execution, only the value of the IN (?) parameters need to be sent. • ps.setInt(1,100000); • ps.setString(2,”Emp001”); • ps.executeUpdate(); • The execute method is used when the statement may return more than one ResultSet or update counts or a combination of both. • This happens when stored procedures are executed.

  17. Iterate ResultSet • while (rs.next()) • { • System.out.println(rs.getString(1)); • System.out.println(rs.getInt(2)); • …….. • }

  18. Result Set Meta Data ResultSetMetaData rsmd=rs.getMetaData(); System.out.println(“Column in ResultSet:”+rsmd.getColumnCount()); for(int i=1;i<=rsmd.getColumnCount();i++) { System.out.println(“Column Name :”+rsmd.getColumnName(i)); System.out.println(“Column Type :”+rsmd.getColumnTypeName (i)); }

  19. Example import java.sql.*; class DatabaseConnection{ public static void main(String args[]) throws Exception{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); Connection con=DriverManager.getConnection(“jdbc:odbc:sac”); PreparedStatement ps=con.prepareStatement(“insert into emp values (?,?,?)”); ps.setString(1,”Emp001”); ps.setString(2,”Peter”); ps.setInt(3,10000); System.out.println(“Row inserted : “+ps.execute Update()); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery(“select * from emp”);

  20. Example (contd.) ResultSetMetaData rsmd=rs.getMetaData(); int cc=rsmd.getColumnCount(); System.out.println(“Number of columns in result set: “+cc); for(int i=1;i<=cc;i++) System.out.print(rsmd.getColumnName(i)+”\t”); System.out.println(); while(rs.next()){ System.out.print(rs.getString(1)+”\t”); System.out.print(rs.getString(2)+”\t”); System.out.print(rs.getString(3)+”\n”);} } }

  21. Scrollable Result Sets • JDBC 2.1 introduced the concept of moving the cursor in the backward direction also. • You can even position the cursor of a ResultSet object on a specific row. • A scrollable ResultSet is obtained as follows • Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); • General Syntax: • Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException

  22. Result Set and Concurrency Types

  23. Transactions • a set of statements that if executed should complete in entirety • If any of the statement fails the entire transaction is rolled back • First Step: the auto commit feature should be turned off. • con.setAutoCommit(false); • Transactions can be rolled backed by using the rollback method on the connection object. • con.rollback();

  24. Transaction (contd.) • try { • con.setAutoCommit(false); • Statement stmt1=con.createStatement(); • Statement stmt2=con.createStatement(); • stmt1.executeUpdate("Query 1"); • stmt1.executeUpdate("Query 2"); • con.commit(); • ... • } catch(SQLException se){ • try{ • con.rollback(); } • catch(SQLException se) {} • }

  25. Batch Updates • try { • con.setAutoCommit(false); • Statement stmt1 = con.createStatement(); • stmt1.addBatch("Query1"); • stmt1.addBatch("Query2"); • int[] i = stmt1.executeBatch(); • con.commit(); • ... • } catch(BatchUpdateException be) { • try{ • stmt1.clearBatch(); • }catch(SQLException se){} }

  26. Savepoint • try { • con.setAutoCommit(false); • Statement stmt1 = con.createStatement(); • Statement stmt2 = con.createStatement(); • stmt1.executeUpdate("Query 1"); • Savepoint sp1 = con.setSavepoint("SavePoint1"); • stmt1.executeUpdate("Query 2"); • con.commit(); • ... • } catch(SQLException se){ • try{ con.rollback(sp1); } • catch(SQLException se){}}

  27. Servlets • Servlets are Java server-side programs that accept client’s request (usually http request), process them and generate (usually http response) responses. • The requests originate from client’s web browser and are routed to a servlet located inside an appropriate web server. • Servlets execute within a servlet Containers which resides in a web server like Apache Tomcat. • Normally HTTP (hyper text transfer protocol) is used between web client and servlets, but other protocols like FTP (file transfer protocol) can also be used.

  28. Life cycle of Servlets

  29. First Servlet import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class FirstServlet extends HttpServlet{ public void service(ServletRequest req, Servlet Response res) throws ServletException,IOException{ res.setContentType(“text/plain”); PrintWriter pw=res.getWriter(); pw.println(“My First Servlet is running”); }}}

  30. How to run the servlet? • The First step is to compile the servlet: • set classpath = %classpath%; C:\Apache\Tomcat 7.0\lib\servlet-api.jar; • javac FirstServlet.java • Install a web server or a servlet container. • Use Apache Tomcat 7.0 • The third step is to place the compiled servlet class into an appropriate directory in the Tomcat.

  31. Directory structure for Placing Servlets

  32. web.xml file

  33. The Output

  34. Reading Client Data • The client’s data is sent to the server from the client’s browser via two methods of http protocols: • get and post. • The get method appends data to the URL (of the servlet handling the request) and passes it to the server. • The drawbacks of this approach are: • The URLs are of fixed size and it puts a restriction on the amount of data that can be transmitted to the server. • Moreover, whatever data is sent to the server is visible in clear text. • On the other hand, post method overcomes these limitations by sending data to the server as a part of http header format instead of appending it to the URL.

  35. Methods to fetch data

  36. Example <html> <head> <title> form data</title></head><body> <center><h1><U>Registration Form</u></h1> <form method = get action = “http://localhost:8080/myproj/servlet/ReadData”> Name <input type=text name=fname><br> Address <input type=text name=add><br> User id <input type=text name=uid><br> Password <input type=password name=pass><br> Gender :male <input type=radio name=gender value=male> female <input type=radio name=gender value=female><br> Hobbies:Dancing <input type=checkbox name=hobbies value=dance> Music <input type=checkbox name=hobbies value=music> Travel <input type=checkbox name=hobbies value=travel><br> <input type=submit><input type=reset></center> </body> </html>

  37. Example import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class ReadData extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ res.setContentType(“text/html”); PrintWriter out=res.getWriter(); Enumeration e=req.getParameterNames(); out.println(“<html><head><title> client data</title></head>”); out.println(“<body><B>”); while(e.hasMoreElements()){ String name=(String)e.nextElement(); String[] values=req.getParameterValues(name); for(int i=0;i<values.length;i++){ out.println(name +” : <i>”+values [i]+”</i><br>”); }} out.println(“</body></html>”);} public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ doGet(req,res);}}

  38. The Output

  39. The Output

  40. Http Redirect • Http redirect is a way of redirecting a user to another location on the Internet. • Http redirect is a way of telling the client’s browser about the new URL. • All the requests that arrive on the old URL are redirected to the new URL. • res.sendRedirect (“http://localhost:8080/myproj/ Formdata.html”);

  41. Cookies • Cookies are basically small pieces of information stored on the client’s machine by the browser. • A cookie contains information like user browsing preferences, user id and password combinations, session id, number of times a user has visited a page, etc. • This information is stored in pairs, i.e. name-value pairs. • This information wrapped in a cookie object is sent to the client browser by a servlet, which stores it somewhere in its temporary Internet files. • Whenever a request is sent to that particular server (from where cookie was downloaded), all the cookies (stored in the client’s machine from that very server) are attached to the http request and sent to the server.

  42. Example import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class CookieDemo extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException{ res.setContentType(“text/html”); PrintWriter out=res.getWriter(); Cookie c[]=req.getCookies(); if(c==null){ Cookie counts=new Cookie(“Counts”,”1”); out.println(“<html><head><title> client data</title></head>”); out.println(“<body><B>”); out.println(“Welcome <br>”); out.println(“This is the first time you have visited this page”); out.println(“</body></html>”);

  43. Example res.addCookie(counts);} else{ out.println(“<html><head><title> client data</title></head>”); out.println(“<body><B>”); for(int i=0;i<c.length;i++) { String name=c[i].getName(); String val=c[i].getValue(); int accessCount=(Integer.parseInt(val) +1); out.println(“Welcome back<br>”); out.println(“Number of times you have visited this page: “+accessCount); Cookie counts=new Cookie(name,new Integer(accessCount).toString()); res.addCookie(counts); } out.println(“</body></html>”); }} public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException{ doGet(req,res);}}

  44. The Output

  45. Session Management • Session is used to track the user between successive requests from the same client to the same server. • The real problem is to maintain the state of the client across various requests. • The http protocol is stateless so it does not maintain client information • Either the client or the server will maintain the sessions. • (a) hidden fields, • (b) URL rewriting, • (c) cookies, or • (d) HttpSession API.

  46. Hidden Fields • are html fields not visible to the users. • The state is maintained (at client side) in hidden fields and embedded in the responses generated by the servlet. • sent back to the server with the http request and extracted by the servlet. • <INPUT TYPE="hidden" NAME="Id" VALUE="Unique Identifier"> • <INPUT TYPE="hidden" NAME="Customer Name" VALUE="Tom">

  47. Drawbacks of Hidden fields • they will only be sent to the server once the form is submitted and not when a user clicks on a hyperlink • can be used when information is less. • Hidden fields can viewed by selecting the “View Source”option in the browser, • cannot be used for security purposes.

  48. URL Rewriting • history/session information/state of the client is appended to the URL before sending the page back to the client • http://server:port/servlet/ServletName?sessionid=123456 & userid=sac123 &... • precaution must be taken in maintaining and appending the parameters every time while rewriting URL’s until the session completes. • Moreover, you cannot have static pages; each page will be dynamically generated if this approach is used.

  49. Cookies • is a small amount of information stored on the client’s machine within the browser’s files • It is a key value pair sent by the server to the client. • This pair is automatically attached with every request to the server from where it was downloaded and then sent to the server. • Problem if the users disable cookies

  50. Session API • HttpSession API is used for creating and maintaining sessions among clients and servers. • HttpSession is an interface within javax.servlet.http package and it maintains all the sessions • A HttpSession Object is created using a getSession method of the request object. • HttpSession session=request.getSession(true); • setAttribute() and getAttribute() are used to store and retrieve objects from the session object. • session.setAttribute("name","Tom"); • String n=(String) session.getAttribute(name); • session can be destroyed by using the invalidate() function

More Related