Vous êtes sur la page 1sur 13

MCSL-054 Lab Manual Answers

Session 1: Exercise 1. Verify installation and setting of Web container/Web Server/Tomcat and prepare an installation report, which contains setting of class path, erver port, starting and shutting down of server etc. A.1 Tomcat requires java in order to run. If the computer already has java installed, we can skip this step, otherwise we need to install it in the following ways: Steps for installing java 1. Go to the download page of J2SE Version 1.4.2. 2. Select the version for Windows and click through the license acceptance. After two pages, you will be able to download the EXE file for installing java on windows. Look for the SDK version. 3. Download and run the EXE installation program. 4. We will need to accept the license agreement again. 5. Use the suggested directory for installing java (C:\j2sdk1.4.2_01). 6. We may use the remaining default settings for the installation. Setting the Java Environment Variable Tomcat will need to know where we have installed java. To do this, you will need to set the environment variable. JAVA_HOME to C:\j2sdk1.4.2_01 (where you installed java). Here are the steps for setting the environment variable : 1. 2. 3. 4. 5. 6. 7. Open the control panel under the start menu. Double-click on System. Click on the Advanced tab. Click on the Environment Variables button. Under System Variables, click on the New button. For variable name, type: JAVA_HOME For variable value, type: C:\j2sdk1.4.2_01

Other important variables that we need are: CATALINA_HOME: C:\tomcat CLASSPATH: C:\Program Files\Java\jdk1.7.0\lib;C:\tomcat\lib\servlet.jar TOMCAT_HOME: C:\tomcat Installing Tomcat 1

After setting the JAVA_HOME environment variable, you can install tomcat. 1. Go to the Tomcat Web page. 2. Click on Binaries under the Download label on the left side of the page. 3. Scroll down until you see Tomcat 4.1.x. (x will be some number greater than 10). 4. Click on the link ending with exe (e.g. 4.1.27 exe). 5. Download and run the exe file. 6. I suggest you install Tomcat at c:\tomcat4 7. Use the default settings and provide a password that you will remember. 8. now assume that your tomcat are installed at c:\tomcat4 Running Tomcat Here are the steps to see if Tomcat has been successfully installed 1. Start Tomcat by finding its start program in the Programs Menu (located in the Start menu). Look under Apache Tomcat 4.1 and select "Start Tomcat". 2. Open a Web browser and type in the following URL: o http://localhost:8080/ At this point, you should see the Tomcat home page, which is provided by the Tomcat Web server running on your computer. Note: if your computer has an internet name or an IP number, you may access your Tomcat server anywhere on the internet by substituting localhost with the full name or IP number. To shut down your server and remove the Console window, select "Stop Tomcat" in the same menu of where you selected "Stop Tomcat".

Session 2: Exercise 3. Write a servlet program that takes your name and address from an HTML Form and displays it. Servlet Program =============== import java.io.*; import javax.servlet.*; import javax.servlet.http.*; 2

public class FpServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); String Your_name = req.getParameter("name"); out.println("<html>"); out.println("<head><title>Hello, " + Your_name + "</title>"); out.println("</head><body>"); out.println("Hello mr. " + Your_name); out.println("</body></html>"); } } HTML form ========= <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Servlet to show your name</title> </head> <body> <form method="get" action="servlet/FpServlet"> Please Enter your Name : <input type="text" name="name"> <br> <input type="submit"> </form> </body> </html>

Exercise 4. Write a servlet program that displays current date and time. Your servlet should also indicate the number of times it has been assessed since it has been loaded. import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class DateServlet extends HttpServlet{ int count = 0; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ PrintWriter pw = response.getWriter(); Date today = new Date(); pw.println("<html><body bgcolor='#7B99E1'>"); pw.println( "<b><h1>Date and Time with Servlet</h1>" +today+ "<br>"); count++; pw.println("Since loading, this servlet has been accessed " +count+ " times.</b></body></html>"); } }

Session 3: Exercise 6. Write a Servlet Program that displays server information (server name, port etc.). import java.io.*; import javax.servlet.*; public class ServerInfo extends GenericServlet { public void service(ServletRequest req, ServletResponse res) 4

throws ServletException, IOException { res.setContentType("text/html;charset=UTF-8"); PrintWriter out = res.getWriter(); try { /* Code for retrive some information from the server*/ out.println("<b>Name of Server:</b> " + req.getServerName()); out.println("<BR> <b>Port Address of server :</b> " + req.getServerPort()); out.println("<BR> <b>Server Information :</b> " + getServletContext().getServerInfo()); out.println("<BR> <b>Server attribute :</b> " + getServletContext().getAttribute("attribute")); out.println("<BR> <b>Server information name :</b>" + getServerInfoName(getServletContext().getServerInfo())); out.println("<BR> <b>Server Version :</b> " + getServletInfoVersion(getServletContext().getServerInfo())); } finally { out.close(); } } private String getServerInfoName(String serverInfo) { //throw new UnsupportedOperationException("Not yet implemented"); int out = serverInfo.indexOf('/'); if (out == -1) { return serverInfo; } else { return serverInfo.substring(0, out); } } private String getServletInfoVersion(String serverInfo) { //throw new UnsupportedOperationException("Not yet implemented"); return serverInfo; } }

Exercise 8. Write program of Exercise 7 with login and password protection. Display a message if login and password are not correctly given. <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Servlet to show your name</title> </head> <body> <form method="get" action="servlet/TestServlet"> Please enter your login details: <input type="text" name="account"> <br> <input type="password" name="password"> <br> <input type="text" name="pin"> <br> <input type="submit"> </form> </body> </html> Servlet program import java.io.IOException; import java.io.PrintWriter; import import import import import javax.servlet.ServletException; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; javax.servlet.http.HttpSession;

public class LoginHandler extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws Servl etException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); String account = req.getParameter("account"); String password = req.getParameter("password");

if (!allowUser(account, password)) { out.println("<HTML><HEAD><TITLE>Access Denied</TITLE></HEAD>"); out.println("<BODY>Your login and password are invalid.<BR>"); out.println("You may want to <A HREF=\"/login.html\">try again</A>"); out.println("</BODY></HTML>"); } else { // Valid login. Make a note in the session object. HttpSession session = req.getSession(); session.setAttribute("logon.isDone", account); // Try redirecting the client to the page he first tried to access try { String target = (String) session.getAttribute("login.target"); if (target != null) { res.sendRedirect(target); return; } } catch (Exception ignored) { } // Couldn't redirect to the target. Redirect to the site's home page. res.sendRedirect("/"); } } protected boolean allowUser(String account, String password, String pin) { return true; // trust everyone } }

Session 4: Exercise 10. Write a JSP program to output, "Welcome to JSP world. The time now is: system current time. Use a scriptlet for the complete string, including the HTML tags. <%@page contentType="text/html" import="java.util.*" %> <html> <body> <p>&nbsp;</p> <div align="center"> <center> 7

<table border="0" cellpadding="0" cellspacing ="0" width="460" bgcolor="#EEFFCA"> <tr> <td width="100%"><b>&nbsp; Welcome to JSP world. The time now is:&nbsp; <font color="#FF0000"> <%= new java.util.Date() %> </font></b></td> </tr> </table> </center> </div> </body> </html>

Exercise 11. write a JSP page that display a randomly generated number in first visit to this page and repeat displaying this same number in subsequent visits. <HTML> <HEAD> <TITLE>Random Number</TITLE> </HEAD> <%! private double randomNum = Math.random(); %> <BODY> <H2>Random Number: <%= randomNum %></H2> </BODY> </HTML>

Session 5: Exercise 12. Write a JSP page to output the values returned by System.getProperty for various system properties such as java.version, java.home, os.name, user.name, user.home, user.dir etc. Each property should be displayed in a separate row. <%@ page language="java" %> <html> <body> <table border="1"> <tr><td><b>Property Names</b></td> <td><b>Property Values</b></td></tr> <% final String[] properties = { "java.runtime.name", "java.vm.vendor", "java.runtime.version", "java.vendor.url", "user.timezone", "user.language", "os.name", "sun.desktop" }; for (int i = 0; i < properties.length; i++) { String pname = properties[i]; String pvalue = System.getProperty(pname); %> <tr> <td><%= pname %></td> <td><%= pvalue %></td> </tr> <% } %> </table> </body> </html>

Session 6: Exercise 15. Create an HTML form to take customer information (Name, Address, Mobile No.). Write a JSP program to validate this information of customers. User Table Structure of MySQL:

create table `customer` ( `name` varchar (50), `address` varchar (200), `mobile` int (10) ); Validation.java

import java.io.*; import java.util.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class Validation extends HttpServlet{ private ServletConfig config; public void init(ServletConfig config) throws ServletException{ this.config=config; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{ PrintWriter out = response.getWriter(); String connectionURL = "jdbc:mysql://localhost:3306/customer"; Connection connection=null; ResultSet rs; String custName=new String(""); String addr=new String(""); String mob=new String(""); response.setContentType("text/html"); try { // Load the database driver Class.forName("org.gjt.mm.mysql.Driver"); // Get a Connection to the database connection = DriverManager.getConnection(connectionURL, "root", "123456"); //Add the data into the database String sql = "select name,address,mobile from User"; Statement s = connection.createStatement(); s.executeQuery (sql); 10

rs = s.getResultSet(); while (rs.next ()){ custName=rs.getString("name"); addr=rs.getString("address"); mob=rs.getString("mobile"); } rs.close (); s.close (); }catch(Exception e){ System.out.println("Exception is ;"+e); } if(custName.equals(request.getParameter("name")) && addr.equals(request.getParameter("address")) && mob.equals(request.getParameter("mobile"))){ out.println("Customer is Valid"); } else{ out.println("You are not a Valid Customer"); } } } Session 7: Exercise 18. Write a JSP program which display a web page containing your personal information such as: Name, Date of Birth, Sex, Area of Interest, Specialisation and a paragraph explaining what you want to be in the next five years.

<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@page info="a jsp webpage" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>My Personal Information</title> </head> <body bgcolor="#ffffff" > <h1 style="font-size: 20pt;font-style: italic;color: purple">My Personal Information</h1> <p><strong>Name:</strong> Hashim</p> <p><strong>Date of Birth:</strong> 5th November 1985</p> 11

<p><strong> Sex:</strong>Male</p> <p><strong> Area of Interest:</strong> Internet and automobile technology</p> <p><strong>Specialisation:</strong> Webdesign</p> <p><strong> What I want to be in the </strong><br /> <strong>next five years: </strong> No goals set yet, I'll go where life takes me.</p> </body> </html>

Session 8 Exercise 20.The following example is a note to Ramu from Deenu, stored in XML: <note> <to> Ramu </to> <from>Deenu</from> <heading>Festival Wishes</heading> <body>May God give you all the happiness</body> </note> Extend this document by adding some more information in this document. Ans: <note> <to> Ramu </to> <from>Deenu</from> <heading>Festival Wishes</heading> <body>May God give you all the happiness</body> </note> <note> <to> Shamu </to> <from>Teenu</from> <heading>Birthday Wishes</heading> <body>Many many Happy returns of the day</body> </note>

Exercise 21. Imagine that this is the description of a book: My First Servlet Introduction to Servlet What is Servlet What are the advantages of Servlet Servlet Life Cycle 12

Servlet Initialisation Servlet Realoading Destroying a Servlet Write an XML document that describes this book. Ans: <?xml version='1.0' encoding='us-ascii'?> <MyFirstServlet> <Chapter1 Name="Introduction to Servlet " > <Lesson1>What is Servlet </Lesson1> <Lesson2>What are the advantages of Servlet </Lesson2> </Chapter1>

<Chapter2 Name="Servlet Life Cycle"> <Lesson1>Servlet Initialisation </Lesson1> <Lesson2>Servlet Realoading</Lesson2> <Lesson3>Destroying a Servlet </Lesson3> </Chapter2> </MyFirstServlet> Exercise 22. Write an XML program to show that white space is preserved in XML. <poem xml:space="default"> <author> <givenName>Alix</givenName> <familyName>Krakowski</familyName> </author> <verse xml:space="preserve"> <line>Roses are red,</line> <line>Violets are blue.</line> <signature xml:space="default">-Alix</signature> </verse> </poem>