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) - LOGIC - 1.C ARCHITECTURE DIAGRAM - EXPLANATION- 1.D CRUD OPERATIONS EACH OPERATION 0.5 MARKS (4*0.5)- 2 M 2.A DIFFERENCES BETWEEN GENERIC & HTTP SERVLET ATLEAST 2-3 DIFFERENCES- 3M 4-DIFFERENCES- 5-DIFFERENCES - 4M 5M 2.B HTML FORM CREATION - SERVLET CODE IN POST METHOD IMPORT STATEMENTS - CLASS NAME AND METHOD (POST) - LOGIC - 2 M 2.C CLASS.FORNAME SYNTAX - EXPLANATION- DRIVERMANAGER SYNTAX- EXPLANATION - 3.A
Getmethod syntax - Get session syntax- Getcookies syntax- Explanation- 1m 1m 2m 3.b HTML FORM CREATION - 2 M SERVLET CODE IN POST METHOD IMPORT STATEMENTS - CLASS NAME AND METHOD (POST) - LOGIC - 3.c driver step- CONNECTION ESTABLSIHMENT- STATEMENT- QUESRY /RESULTSET- 4.A LIST ANY 4 TECHNOLOGIES 2 M ATLEAST 2 - B. GETPARAMETERNAMES SYNTAX- IMPORT UTIL - STRING OBJECT CREATION AND DISPLAY VALUES- 4.C HTML FORM CREATION - 2 M SERVLET CODE IN POST METHOD IMPORT STATEMENTS - CLASS NAME AND METHOD (POST) - LOGIC - 4.D STATEMENT SYNTAX- EXAMPLE - PREPARED STATEMENT SYNTAX- EXAMPLE-
TEST-3 KEY 1 (a) A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet 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. Architecture Diagram: The following figure depicts a typical servlet life-cycle scenario. 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. 1(b). <html> <form name=" IceCreamForm " method="post" action="icecreamservlet"> Email: <input type="text" name="email"/> <br/> Password: <input type="password" name="password"/> <br/> <select name= flavor > <option value="strawberry"> Strawberry </option> <option value="vanilla"> Vanilla </option> <option value="butterscotch"> Butterscotch </option> <option value="chocolate"> Chocolate </option></select> <input type="submit" value="icecreamform" /></form></html> Servlet Program: import java.io.ioexception;import java.io.printwriter; import javax.servlet.servletexception;import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet;import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse; public class icecreamservlet extends HttpServlet { protected void dopost(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { // read form fields String email = request.getparameter("email"); String password = request.getparameter("password"); String flavour = request.getparameter("flavor"); System.out.println("Email: " + email); System.out.println("password: " + password); System.out.println("Job category is: " + flavour); // do some processing here... // get response writer PrintWriter writer = response.getwriter(); // build HTML code String htmlrespone = "<html>"; htmlrespone += "<h2>your Email is: " + email + "<br/>"; htmlrespone += "Your password is: " + password + "</h2>"; htmlrespone += "Your Flavour is: " + flavour + "</h2>"; htmlrespone += "</html>"; // return response writer.println(htmlrespone); } } 1 C. JDBC Architecture The JDBC API supports both two-tier and three-tier processing models for database access. Figure 1: Two-tier Architecture for Data Access. In the two-tier model, a Java application talks directly to the data source. This requires a JDBC driver that can communicate with the particular data source being accessed. A user's commands are delivered to the database or other data source, and the results of those statements are sent back to the user. The data source may be located on another machine to which the user is connected via a network. This is referred to as a client/server configuration, with the user's machine as the client, and the machine housing the data source as the server. The network can be an intranet, which, for example, connects employees within a corporation, or it can be the Internet. In the three-tier model, commands are sent to a "middle tier" of services, which then sends the commands to the data source. The data source processes the commands and sends the results back to the middle tier, which then sends them to the user. MIS directors find the threetier model very attractive because the middle tier makes it possible to maintain control over access and the kinds of updates that can be made to corporate data. Another advantage is that it simplifies the deployment of applications. Finally, in many cases, the three-tier architecture can provide performance advantages. Figure 2: Three-tier Architecture for Data Access.
Until recently, the middle tier has often been written in languages such as C or C++, which offer fast performance. However, with the introduction of optimizing compilers that translate Java bytecode into efficient machine-specific code and technologies such as Enterprise JavaBeans, the Java platform is fast becoming the standard platform for middletier development. This is a big plus, making it possible to take advantage of Java's robustness, multithreading, and security features.with enterprises increasingly using the Java programming language for writing server code, the JDBC API is being used more and more in the middle tier of a three-tier architecture. Some of the features that make JDBC a server technology are its support for connection pooling, distributed transactions, and disconnected rowsets. The JDBC API is also what allows access to a data source from a Java middle tier. 1(d). CRUD stands for create, read, update, delete. Create statement in SQL looks like Create table mytab ( mynum number, name varchar2(25));read statement looks like Select * from mytab where mynum=25;update statement looks as Update mytab set mynum=88 where mynum=25; DELETE statement like Delete from mytab where mynum=88; 2(a). GENERICSERVLET Can be used with any protocol (means, can handle any protocol). Protocol independent. All methods are concrete except service() method. service() method is abstract method. service() should be overridden being abstract in super interface. It is a must to use service() method as it is a callback method. Extends Object and implements interfaces Servlet, ServletConfig and Serializable. Direct subclass of Servet interface. Defined javax.servlet package. HTTPSERVLET Should be used with HTTP protocol only (can handle HTTP specific protocols). Protocol dependent. All methods are concrete (non-abstract). service() is non-abstract method. service() method need not be overridden. Being service() is non-abstract, it can be replaced by doget() or dopost() methods. Extends GenericServlet and implements interface Serializable Direct subclass of GenericServlet. Defined javax.servlet.http package.
All the classes and interfaces belonging to javax.servlet package are protocol independent. Not used now-a-days. All the classes and interfaces present in javax.servlet.http package are protocol dependent (specific to HTTP). Used always. 2(b) <html><form name="agegender" method="post" action="agegenderservlet"> What is Your Age:<input type="checkbox" name="age" value="young" /> Young :<input type="checkbox" name="age" value="old" /> OldWhat is your Gender? <input type="radio" name="gender" value="male" />Male <input type="radio" name="gender" value="female" />Female <input type="submit" value="login" /></form><html> Servlet Code: import java.io.ioexception;import java.io.printwriter; import javax.servlet.servletexception;import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet;import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; @WebServlet("/loginServlet") public class LoginServlet extends HttpServlet { protected void dopost(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { // read form fields String age = request.getparametervalues("age"); if (age.equals( Old )) { System.out.println("Take care of your health"); else System.out.println("Live Young Live Free"); } String gender = request.getparameter("gender"); System.out.println("What is your age: " + age); System.out.println("Gender is: " + gender);} } 2 Class.forName():We can register the driver indirectly using the statement Class.forName("com.mysql.jdbc.Driver"); Class.forName loads the specified class When mysqldriver is loaded, it automaticallycreates an instance of itself registers this instance with the DriverManager Hence, the driver class can be given as an argument of the application DriverManager.getConnection():Every database is identified by a URL Given a URL, DriverManager looks for the driver that can talk to the corresponding database DriverManager tries all registered drivers, until a suitable one is found 3.A) HTTP servlet request-this interface gets data from the client to the servlet for use in the HttpServlet.service method. It allows the HTTP-protocol specified header information to be accessed from the service method. getcookies()
Gets the array of cookies found in this request. getmethod()gets the HTTP method (for example, GET, POST, PUT) with which this request was made. getsession()gets the current valid session associated with this request, if create is false or, if necessary, creates a new session for the request. 3.b) <html><body><form action= servlet1 method= get >My favorite Fruit <select name= fruit size=4 multiple ><option value= apple>apple </option> <option value= banana>banana </option><option value= apple>apple </option> <option value= apple>apple </option></select> Would u like a brochure <input type= checkbox name= brochure value= b ><input type= submit ></form> </body></html> Servlet Code: import java.io.ioexception;import java.io.printwriter; import javax.servlet.servletexception;import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet;import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; @WebServlet("/loginServlet") public class servlet1 extends HttpServlet { protected void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { String fruits[] = request.getparametervalues("fruit"); String opt=request.getparameter( brochure ); if (opt.equals( b )) { System.out.println("Brochure will be sent to your email"); else System.out.println("Thank you for visiting our website "); } } } 3.c The fundamental steps involved in the process of connecting to a database and executing a query consist of the following: Import JDBC packages. Load and register the JDBC driver. Open a connection to the database. Create a statement object to perform a query. Execute the statement object and return a query resultset. 4)a) server side programming technologies CGI (Common Gateway Interface) ASP (Active Server Page) Java Servlets PHP Perl b) getparameternames()
an Enumeration of String objects, each String containing the name of a request parameter; or an empty Enumeration if the request has no parameters import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; -----1 M public class CheckBox extends HttpServlet { public void dopost(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getwriter(); Enumeration paramnames = request.getparameternames(); --------1 M while(paramnames.hasmoreelements()) { String paramname = (String)paramNames.nextElement(); out.print("<tr><td>" + paramname + "</td>\n<td>"); -----1 M out.println("</tr>\n</table>\n</body></html>"); } } c) <html> form creation----2 M <head> <title> Form</title> </head> <body "> <form method="get" action="servlet1"> <table> <tr> <td> First Name: </td> <td> <input type="text" name="fname"> </td> </tr> <td> Last Name:: </td> <td> <input type="text " name= lname "> </td> <tr> <td> Full Name: </td> <td> <input type="text" name="flname"> </td> </tr> <tr> <td> Date of Birth: </td> <td> <input type="text" name="dob"> </td> </tr> <tr> <td> <input type="submit" value="submit "> </td> </tr> </table> </form></body></html> Import java.io.*; Import javax.servlet.*; Import javax.servlet.http.*; public class Servlet1 extends HttpServlet { ---- 3 M public void doget(httpservletrequest req,httpservletresponse res)throws ServletException,IOException { res.setcontenttype("text/html"); PrintWriter out=res.getwriter(); out.println("<html><body>"); out.println("firstname:"+req.getparameter("fname")); out.println("<br>lastnmae:"+req.getparameter("lname")); out.println("<br>fullname:"+req.getparameter("flname")); out.println("<br>date of Birth:"+req.getParameter("dob")); out.println("</body></html>"); }} d) A Statement Interface is used to create a statement i.e. a query to be executed against a database. In this process, two calls are made to the database system, one to get the table metadata and other to get the data itself. The statement object is also compiled every time it executes. A Prepared statement comes in handy as it is compiled and cached and only makes on database call when invoked. The compilation would be skipped even if the values in the where clause change Inserting a record in the table using statement 2 M Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", scott", tiger"); Statement stmt = con.createstatement(); int i= stmt.executeupdate( INSERT INTO pet VALUES(12, minou, Gwen, cat ) ); Inserting a record in the table using prepared statement Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", scott", tiger"); String query = "insert into dept(deptnum, deptname, deptloc) values(?,?,?)"; pstmt = con.preparestatement(query); pstmt.setint(1, 10); pstmt.setstring(2, SALES"); pstmt.setstring(3, LONDON"); pstmt.executeupdate();