Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
UNIT IV UNIT IV MULTI-TIER APPLICATION DEVELOPMENT Server side programming – servlets – Java Server Pages - Applet to Applet communication – applet to Servlet communication - JDBC – Applications on databases – Multimedia streaming applications – Java Media Framework. 1. Explain about servlets and the life cycle of servlets with an example program. (8) Servlets: Servlets are small Java programs that run inside servers. Servlets extends the server’s functionality and Applets extend the functionality of a web browser. Java Servlet technology is one of many technologies available for generating responses dynamically when an HTTP request is received. (or) Java servlets are executed upon request from a web browser. . Request Servlet Response Client Server All servlets execute inside aservlet container,also referred to as aservlet server or a servlet engine. A servlet container is a single process that runs a JVM (Java Virtual Machine). JVM is used to handle each servlets. Servlet is just a Java class that a web server instantiates when the server is started. A particular method is called on this instance when the web server receives certain HTTP request from the web client through the web browsers Servlet Architecture Explanation of the architecture diagram: A client application (web browser) sends an HTTP request to the web server. The servlet container receives the request and directs it to be processed by the appropriate servlet. The servlet does its processing, which may include components, such as other servlets or JSP’s. interacting with a database or other server- side The servlet returns its results to the client- normally in the form of an HTML, XHTML, or XML document to display in the browser. UNIT-4 Page 1 Life Cycle of Servlet o Package javax.servlet.Servlet. o The three life cycle methods init(), service(), and destroy() are present in this servlet communication which should be implemented by all servlets. init() The lifecycle of servlet begins here. This method is called only once to initialize the servlet. service() Defines an entry point for servicing the requests. It is executed for every incoming requests. It is called only after the servlet is initialized. destroy() The end of servlet life cycle is indicated by this method. All the resources initialized for servicing the request are cleaned up. Servlet Interface o The servlet packages define two abstract classes that implement servlet interface Class GenericServlet (from the package javax.servlet) The generic Class HttpServlet (from the package javax.servlet.http) It is an interfaces and classes that are implemented and extended by all servlets are contained in this class. (service method) extension or this class is inherited from javax.servlet package. An example would be a simple servlet that responds using html. (and contains doGet() and doPost() methods) o The two most common HTTP request types (also known as request methods) are get and post. GET Request A get request retrieves information from a server. Typically, an HTML document /XML documents. POST Request o o A post request sends data to a server. Typically, post requests are used to pass user input to a data- handling process, store or update data on a server. The key method in every servlet is service, which accepts both a ServletRequest object and a ServletResponse object. These object provide access to input and output streams that allow the servlet to read data from and send data to the client. If a problem occurs during the execution of a servlet, either ServletExceptions or IOExceptions are thrown to indicate a problem. Servlet Interface Methods: Public void init(ServletConfig config) throws ServletException Marks the beginning of a servlets life. It is called only once. The argument ServletConfig encapsulates the initial parameters and startup configuration of servlet. Public void service(ServletRequestreq, ServletResponse res) throws ServletException, IOException UNIT-4 Page 2 Defines an entry point for servicing the requests. It is executed for every incoming client requests. Public void destroy() Marks the end of the servlet’s life. It is executed only once, when the servlet is removed from the service. When a client connects to a server and request it using HTTP, the request can be of several different types, called methods. The most commonly and frequently used method are the following, HTTP GET H T T The P HTTP GET method is used to get information like a document, a chart or results from a database query. P O S addition, it can include some of its own information as part of the request by appending them using query In T string. HTTP GET But it is not allowed to send large amount of information and some servers limitthe length of the URL’s and query string to about 240 characters. public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException HTTP POST The HTTPPOST method is used to post information that is to be stored in the The post method uses adifferent technique because it may need to send database. magabytes of information. It passes its entire request as data of unlimited length, directly over the socket connection. public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException Servlet program: myfirstpage.html <html> <head> <title>The servlet example </title> </head> <body> <h1>A simple web application</h1> <form method="POST" action="WelcomeServlet"> <label for="name">Enter your name </label> <input type="text" id="name" name="name"/><br><br> <input type="submit" value="Submit Form"/> <input type="reset" value="Reset Form"/> </form> </body></html> WelcomeServlet.java UNIT-4 Page 3 import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class WelcomeServlet extends HttpServlet { @Override public void init(ServletConfig config) throws ServletException { super.init(config); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * Get the value of form parameter */ String name = request.getParameter("name"); String welcomeMessage = "Welcome "+name; /* * Set the content type(MIME Type) of the response. */ response.setContentType("text/html"); PrintWriter out = response.getWriter(); /* * Write the HTML to the response */ out.println("<html>"); out.println("<head>"); out.println("<title> A very simple servlet example</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>"+welcomeMessage+"</h1>"); //out.println("<a href="/servletexample/pages/form.html">"+"Click here to go back to input page "+"</a>"); out.println("</body>"); out.println("</html>"); out.close(); } public void destroy() { } } Output: http://localhost:8081/ServeltWithHTML/caller.html UNIT-4 Page 4 Servlet response: web.xml <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <session-config> <session-timeout> 30 </sessiontimeout> </sessionconfig> <servlet> <servlet-name>WelcomeServlet</servlet-name> <servlet-class>WelcomeServlet</servlet-class> </servlet> UNIT-4 Page 5 <servlet-mapping> <servletname>WelcomeServlet</servlet-name> <urlpattern>/WelcomeServlet</url-pattern> </servlet-mapping> </web-app> 2. Explain applet to applet and applet to servlet communication with suitable program. (16) Applet To Applet Communication AppletToApplet.html <HTML> <HEAD> <TITLE> Applet-Applet Communicaton </TITLE> </HEAD> <BODY BGCOLOR="#FFFFFF"> <h1> Applet-Applet Communicaton </h1> <applet code="Two" width="400" height="300" name="Two"> </applet> <br> <hr> <br> <applet code="One" width="400" height="300" name="One"> </applet> </BODY> </HTML> First Applet: One.java import javax.swing.*; import java.awt.*; public class One extends JApplet { JTextArea taOutput; public void init() { getContentPane().setLayout( new FlowLayout()); taOutput = new JTextArea(5,20); getContentPane().add (taOutput); } public void putText(String str) { taOutput.append( str + "\n"); } UNIT-4 Page 6 } Second Applet: Two.java import javax.swing.*; import java.awt.event.*; import java.applet.AppletContext; import java.awt.*; public class Two extends JApplet implements ActionListener { JTextField txtInput; AppletContext ac; JButton btnSend; public void init() { getContentPane().setLayout( new FlowLayout()); txtInput = new JTextField(25); getContentPane().add (txtInput); btnSend = new JButton("Send"); getContentPane().add(btnSend); btnSend.addActionListener(this); } public void actionPerformed(ActionEvent ae) { ac = getAppletContext(); One obj = (One) ac.getApplet("One"); if(obj != null) { obj.putText(txtInput.getText()); txtInput.setText(""); } } } OUTPUT: UNIT-4 Page 7 APPLET TO SERVLET COMMUNICATION Sender Applet EchoApplet.java import java.applet.Applet; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; /** * Simple demonstration for an Applet <-> Servlet communication. */ public class EchoApplet extends Applet { private TextField inputField = new TextField(); private TextField outputField = new TextField(); private TextArea exceptionArea = new TextArea(); /** * Setup the GUI. */ public void init() { // set new layout setLayout(new GridBagLayout()); // add title Label title = new Label("Echo Applet", Label.CENTER); title.setFont(new Font("SansSerif", Font.BOLD, 14)); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = GridBagConstraints.REMAINDER; c.weightx = 1.0; c.fill = GridBagConstraints.HORIZONTAL; UNIT-4 Page 8 c.insets = new Insets(5, 5, 5, 5); add(title, c); // add input label, field and send button c = new GridBagConstraints(); c.anchor = GridBagConstraints.EAST; add(new Label("Input:", Label.RIGHT), c); c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; add(inputField, c); Button sendButton = new Button("Send"); c = new GridBagConstraints(); c.gridwidth = GridBagConstraints.REMAINDER; add(sendButton, c); sendButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onSendData(); } }); // add output label and non-editable field c = new GridBagConstraints(); c.anchor = GridBagConstraints.EAST; add(new Label("Output:", Label.RIGHT), c); c = new GridBagConstraints(); c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; add(outputField, c); outputField.setEditable(false); // add exception label and non-editable textarea c = new GridBagConstraints(); c.anchor = GridBagConstraints.EAST; add(new Label("Exception:", Label.RIGHT), c); c = new GridBagConstraints(); c.gridwidth = GridBagConstraints.REMAINDER; c.weighty = 1; c.fill = GridBagConstraints.BOTH; add(exceptionArea, c); exceptionArea.setEditable(false); } /** * Get a connection to the servlet. */ private URLConnection getServletConnection() throws MalformedURLException, IOException { // Connection zum Servlet öffnen URL urlServlet = new URL(getCodeBase(), "echo"); UNIT-4 Page 9 URLConnection con = urlServlet.openConnection(); // konfigurieren con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestProperty( "Content-Type", "application/x-javaserialized-object"); // und zurückliefern return con; } /** * Send the inputField data to the servlet and show the result in the outputField. */ private void onSendData() { try { // get input data for sending String input = inputField.getText(); // send data to the servlet URLConnection con = getServletConnection(); OutputStream outstream = con.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(outstream); oos.writeObject(input); oos.flush(); oos.close(); // receive result from servlet InputStream instr = con.getInputStream(); ObjectInputStream inputFromServlet = new ObjectInputStream(instr); String result = (String) inputFromServlet.readObject(); inputFromServlet.close(); instr.close(); // show result outputField.setText(result); } catch (Exception ex) { ex.printStackTrace(); exceptionArea.setText(ex.toString()); } } } EchoServlet.java UNIT-4 Page 10 import java.io.*; import javax.servlet.ServletException; import javax.servlet.http.*; /** * Simple demonstration for an Applet <-> Servlet communication. */ public class EchoServlet extends HttpServlet { /** * Get a String-object from the applet and send it back. */ public void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { response.setContentType("application/x-java-serialized-object"); // read a String-object from applet // instead of a String-object, you can transmit any object, which // is known to the servlet and to the applet InputStream in = request.getInputStream(); ObjectInputStream inputFromApplet = new ObjectInputStream(in); String echo = (String) inputFromApplet.readObject(); // echo it to the applet OutputStream outstr = response.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(outstr); oos.writeObject(echo); oos.flush(); oos.close(); } catch (Exception e) { e.printStackTrace(); } } } web.xml <web-app> <!-- General description of your web application - > <display-name>Echo Servlet</display-name> <description> Echo Servlet </description> <!-- define servlets and mapping -> <servlet> <servlet-name>echo</servlet-name> UNIT-4 Page 11 <servlet -class>EchoServlet</servletclass> </servlet> <servlet-mapping> <servletname>echo</servlet-name> <url-pattern>/echo</url-pattern> </servlet-mapping> </web-app> OUTPUT: 3. Explain the JDBC architecture and write a program to integrate an application with a database. (8) OR Explain how the Database connectivity can be achieved in java and write a test program to show the database connectivity. Java Database Connectivity(JDBC) JDBC is a SQL-level API--one that allows you to execute SQL statements and retrieve the results. JDBC Drivers The JDBC API, found in the java.sql package, contains only a few concrete classes JDBC drivers are available for most database platforms, from a number of vendors and in a number of different flavours. There are four driver categories: Type 1- JDBC-ODBC Bridge Driver Type 2- Native-API Partly-Java Driver Type 3- Net-Protocol All-Java Driver Type 4- Native-Protocol All-Java Driver Getting a Connection UNIT-4 Page 12 The first step in using a JDBC driver to get a database connection involves loading the specific driver class into the application's JVM An easy way to load the driver class is to use the Class.forName() method Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); DriverManager class to open a connection to a given database Connection con = DriverManager.getConnection("jdbc:odbc:somedb", "user", "passwd"); Executing SQL Queries use a database, need to execute queries Statement stmt = con.createStatement(); A query that returns data can be executed using the executeQuery() method of Statement ResultSet rs = stmt.executeQuery("SELECT * FROM CUSTOMERS"); ResultSet object as a representation of the query result returned one row at a time. next()method of ResultSet to move from row to row. The ResultSet interface also boasts a multitude of methods designed for retrieving data from the current row. Jspwithmysql.jsp <%@page import="java.sql.*"%> <% response.setHeader("Pragma","no-cache"); response.setHeader("Cache-Control","no-cache"); response.setDateHeader("Expires",-1); try { String query=request.getParameter("sql"); if(query!=null) { new com.mysql.jdbc.Driver(); String url="jdbc:mysql://localhost:3306/test"; Connection con=DriverManager.getConnection(url,"root","root"); UNIT-4 Page 13 Statement stmt=con.createStatement(); if(stmt.execute(query)==false) { out.println(stmt.getUpdateCount()+"rows affected"); } else { ResultSet rs=stmt.getResultSet(); ResultSetMetaData md=rs.getMetaData(); out.println("<table border=\"1\"><tr>"); for(int i=1;i<=md.getColumnCount();i++) { out.print("<th>"+md.getColumnName(i)+"</th>"); } out.println("</tr>"); while(rs.next()) { out.println("<tr>"); for(int i=1;i<=md.getColumnCount();i++) { out.print("<td>"+rs.getString(i)+"</td>"); } out.println("</tr>"); } out.println("</table>"); rs.close(); } stmt.close(); con.close(); } } catch(Exception e) { out.println(e); } %> <form name="sqlForm" methods="post"> SQL statement:<br><input type="text" name="sql" size="50"><br/> <input type="reset"><input type="submit" value="Execute"> </form> Connect the database to JSP Program through the following steps: o o o o Load the driver Class.forName(―sun.jdbc.odbc.JdbcOdbcDriver‖) Establish connection Connection conn=DriverManager.getConnection(―jdbc:odbc:sample1‖); Create a statement that runs sql statements Statement st=conn.createStatement(); Execute the sql statements ResultSet rs=st.executeQuery("select *from Table1"); OUTPUT: UNIT-4 Page 14 UNIT-4 Page 15 4. Explain the BLOB AND CLOB with an example program. OR Explain the multimedia database application using java. (8) - Collection Of Binary Data Stored As Single Entity In DBMS No Encoding Schema Used, Bytes Storage Usually Large, Size 4 GB BLOB Data Not Stored In Table, Table Contains Reference Address JDBC Offers Interface java.sql.Blob Provide Generic Functionalities To Handle BLOB Data In DB Handle BLOB Data As byte Array Also, Handled By Java.io.InputStream Class How MySQL handles BLOBs Description of the code: 1. First create connection to the database from where you want to retrieve image saved as blob. 2. Create a mysql query to retrieve image value from table column. 3. Retrieves the value of the designated column in the current row of this ResultSet object as a UNIT-4 Page 16 Blob object by using getBlob() method. 4. Write data on standard output device. InsertImage.jsp <%@ page import="java.sql.*"%> <%@ page import="java.io.*"%> <% Connection con=null; ResultSet rs=null; PreparedStatement psmt=null; FileInputStream fis; String url="jdbc:mysql://localhost:3306/test"; try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); con=DriverManager.getConnection(url,"root","root"); File image=new File("E:/mike.jpg"); psmt=con.prepareStatement("insert into image(name,city,image)"+"values(?,?,?)"); psmt.setString(1,"Michael"); psmt.setString(2,"Chennai"); fis=new FileInputStream(image); psmt.setBinaryStream(3, (InputStream)fis, (int)(image.length())); int s = psmt.executeUpdate(); if(s>0) { %> <b><font color="Blue"> <% out.println("Image Uploaded successfully !"); %> </font></b> <% } UNIT-4 Page 17 else { out.println("unsucessfull to upload image."); } con.close(); psmt.close(); }catch(Exception ex){ out.println("Error in connection : "+ex); } RetrieveImage2.jsp <%@ page import="java.sql.*" %> <%@ page import="java.io.*" %> <% String url = "jdbc:mysql://localhost:3306/test"; ResultSet rs = null; PreparedStatement psmnt = null; Connection con=null; InputStream sImage; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); con=DriverManager.getConnection(url,"root","root"); psmnt = con.prepareStatement("SELECT image FROM image WHERE name = ?"); psmnt.setString(1, "Michael"); rs = psmnt.executeQuery(); if(rs.next()) { byte[] bytearray = new byte[1048576]; int size=0; sImage = rs.getBinaryStream(1); response.reset(); response.setContentType("image/jpeg"); while((size=sImage.read(bytearray))!= -1 ){ response.getOutputStream().write(bytearray,0,size); } } } catch(Exception ex){ UNIT-4 Page 18 out.println("error :"+ex); } finally { rs.close(); psmnt.close(); con.close(); } %> OUTPUT: Mysql Query: CREATE TABLE `image` ( `id` int(11) NOT NULL auto_increment, `name` varchar(32) NOT NULL, `image` longblob NOT NULL, city varchar(32), PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=27 ; Overview Of CLOB - A Clob is a Character Large Object in a Database. - A large character data file can be stored asCLOB type - JDBC provides java.sql.Clob interface for handling large character/text object - Mysql Supports CLOB there are four Data Types TINYTEXT, TEXT, MEDIUMTEXT and LONGTEXT which can be taken as CLOB type and have the maximum lengths and storage requirements - The maximum length of TINYTEXT has 255 character (8 bits) UNIT-4 Page 19 - TEXT has 16,535 character (16 bits) MEDIUMTEXT has 16,777,216 character (24 bits) LONGTEXT has 4,294,967,295 character (32 bits) INSERTING CLOB VALUES WITH SQL INSERT STATEMENT 1. Use SQL INSERT statement and include the character string a SQL String literal in the statement 2. Compilation and execution of this program 3. Using String Literals To Insert CLOB Values into database 4. Using prepared statement 5. The CLOB object offers some methods Length() – returns the number of character in CLOB object, returns long getSubString(long pos, int length)returns a substring of character from CLOB object getCharacterStream() – resturns a Reader object from a clob object, resd content free() – releases resource that clob object holds 5.Explain JMF architecture and its applications. (8) The Java Media Framework (JMF) is a recent API for Java dealing with real-time multimedia presentation and effects processing. JMF handles time-based media, media which changes with respect to time Various Stages: input stage - data is read from a source and passed in buffers to the processing stage. The processing stage consists of a number of codecs and effects designed to modify the data stream to one suitable for output Once the processing stage has applied its transformations to the stream, it passes the information to the output stage For example, a JMF system may read input from a TV capture card from the local system capturing input from a VCR in the input stage Component Architecture Media Handlers MediaHandlers are registered for each type of file that JMF must be able to handle. To support new file formats, a new MediaHandler can be created. Data Sources A DataSource handler manages source streams from various inputs. These can be for network protocols, such as http or ftp, or for simple input from disk. UNIT-4 Page 20 Codecs/Effects Codecs and Effects are components that take an input stream, apply a transformation to it and output it. Codecs may have different input and output formats, while Effects are simple transformations of a single input format to an output stream of the same format. Renderers A renderer is similar to a Codec, but the final output is somewhere other than another stream. A VideoRenderer outputs the final data to the screen, but another kind of renderer could output to different hardware, such as a TV out card. Mux/Demuxes Multiplexers and Demultiplexers are used to combine multiple streams into a single stream or viceversa, respectively. They are useful for creating and reading a package of audio and video for saving to disk as a single file, or transmitting over a network. Using the Player The Player class is an easy way to embed multimedia in an application. It handles the setup of the file handler, video and audio decoders, and media renderers automatically Capturing Real-time Data Video and audio data can be captured in real-time from input sources and streamed to files on the local filesystem. Capturing Audio To capture audio, the specified sampling frequency, sample size and number of channels must be specified. The source object returned from the Processor can then be turned into a Player object by calling Manager.createPlayer(). To capture it to an audio file instead, a DataSink can take the data instead: DataSink sink; MediaLocator dest = new MediaLocator("file://output.wav"); try { sink = Manager.createDataSink(source, dest); sink.open(); sink.start(); } catch (Exception e) { } Capturing Video Capturing video is identical to capturing audio. Most video sources have an accompanying audio track that must be encoded DataSink filewriter = null; try { filewriter = Manager.createDataSink( source, dest ); filewriter.open(); filewriter.start(); } catch ( Exception e ) { } p.start();