Sei sulla pagina 1di 15

Date: 22 November 2012 Program Number: 27

/* AIM: Write an Applet program that displays the life cycle of an Applet. */
import java.awt.*; import java.applet.*; public class Sample extends Applet{ String msg; public void init(){ setBackground(Color.cyan); setForeground(Color.red); msg="Inside init() -->"; } public void start(){ msg+="Inside start() -->"; } public void paint(Graphics g){ msg+="Inside paint -->"; g.drawString(msg,10,30); } }

/* OUTPUT */

Date: 22 November 2012 Program Number: 28

/* AIM: Write an Applet displaying line, rectangle, rounded rectangle, filled rectangle, filled rounded rectangle, circle, ellipse, arc, filled arc and polygon, all in different colours. */
importjava.awt.*; importjava.applet.*; //<applet code="appletdemo.class" width="500" height="500"></applet> public class appletdemo extends Applet{ public void paint(Graphics g){ int []a={10,100}; int []x={300,400,400,350,300}; int []y={350,350,400,425,400}; g.drawLine(10,10,100,100); g.drawRect(110,10,110,90); g.drawRoundRect(240,10,170,110,20,30); g.drawOval(10,280,100,100); g.drawOval(130,280,50,80); g.drawArc(200,280,100,100,45,90); g.drawPolygon(x,y,5); g.setColor(Color.BLUE); g.fillRect(110,140,110,90); g.fillRoundRect(240,140,170,110,20,30); } }

/* OUTPUT */

Date: 22 November 2012 Program Number: 29

/* AIM: Write an Applet that displays a counter in the middle of applet. The counter starts from zero and keeps on incrementing after every second.*/
import java.awt.*; import java.applet.*; //<applet code="appletdemo.class" width="100" height="100"></applet> public class appletdemo extends Applet{ intj,i=0; public void paint(Graphics g){ g.drawString(""+i,100,100); i++; try{ Thread.sleep(1000); } catch(Exception e){} repaint(); } }

/* OUTPUT */

Date: 22 November 2012 Program Number: 30

/* AIM: Write an Applet that illustrates how to process mouse click, enter, exit, press and release events. Applet displays your name whenever the mouse is clicked, the background colour changes when the mouse is entered, clicked, pressed, released or exited. */
import java.awt.*; import java.applet.*; import java.awt.event.*; //<applet code="appletdemo.class" width="400" height="400"></applet> public class appletdemo extends Applet implements MouseListener { Label label1 = new Label("Tushar"); public void init(){ add(label1); label1.setFont(new java.awt.Font("Times New Roman", 3, 48)); label1.addMouseListener(this); } public void mouseClicked(MouseEventevt){ label1.setText("JAVA"); } public void mouseEntered(MouseEventevt){ label1.setBackground(Color.ORANGE); } public void mouseExited(MouseEventevt){ label1.setBackground(Color.BLUE); } public void mousePressed(MouseEventevt){ label1.setBackground(Color.YELLOW); } public void mouseReleased(MouseEventevt){ label1.setBackground(Color.GREEN); } }

/* OUTPUT */

Date: 22 November 2012 Program Number: 31

/* AIM: Write an Applet that demonstrates the Applet Window, and the status bar in that window.*/
import java.awt.*; import java.applet.*; //<applet code="appletdemo.class" width="200" height="200"></applet> public class appletdemo extends Applet{ public void init(){ setBackground(Color.CYAN); } public void paint(Graphics g){ g.drawString("This is the Applet Window..",20,20); showStatus("Status Bar"); } }

/* OUTPUT */

Date: 22 November 2012 Program Number: 32

/* AIM: Write a servlet program for interaction with user. Write a program that handle HTTP request. Write a program that handle HTTP response.*/

// .java file
import java.io.*; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; @WebServlet("/servlet") public class servlet extends HttpServlet { @Override public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("text/html"); String name1 = request.getParameter("input1"); String name2 = request.getParameter("input2"); out.println("<H1>Handling HTTP Get Request</H1>"); out.println("You entered: "+name1+" and "+name2); out.close(); } @Override public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("text/html"); String name1 = request.getParameter("input1"); String name2 = request.getParameter("input2"); out.println("<H1>Handling HTTP Post Request</H1>"); out.println("You entered: "+name1+" and "+name2); out.close(); } }

// .html file
<html> <head> <title>Servlets - Java</title> </head> <body> <center> <h1>Java Servlets!</h1> <form method="POST" action="/WebApplication1/servlet"> Parameter 1: <input type="text" name="input1"><br/> Parameter 2: <input type="text" name="input2"><br/> <input type = "submit" value = "Make POST Request"> </form> <hr> <form method="GET" action="/WebApplication1/servlet"> Parameter 1: <input type="text" name="input1"><br/> Parameter 2: <input type="text" name="input2"><br/> <input type = "submit" value = "Make Get Request"> </form> </center> </body> </html>

/* OUTPUT */

Tutorial Sheet 6

Java Programming and Website Design(ETIT-303)

1. What is an applet? Ans: An applet is any small application that performs one specific task that runs within the scope of a larger program, often as a plug-in.[1][2] An applet typically also refers to Java applets, i.e., programs written in the Java programming language that are included in a web page. 2. What is the difference between applications and applets? Ans: An applet runs under the control of a browser, whereas an application runs stand-alone, with the support of a virtual machine. As such, an applet is subjected to more stringent security restrictions in terms of file and network access, whereas an application can have free reign over these resources. 3. How does applet recognize the height and width? Ans: By using getParameters() method. 4. When do you use codebase in applet? Ans: When the applet class file is not in the same directory, codebase is used. 5. What is the lifecycle of an applet? Ans: An applet can react to major events in the following ways: a. It can initialize itself. b. It can start running. c. It can stop running. d. It can perform a final cleanup, in preparation for being unloaded. 6. What is an event and what are the models available for event handling? Ans: Java applications can create user interfaces, allowing users to carry out application tasks. Within these user interfaces, the Java code must be able to respond to user interaction, tailoring processing to whichever actions the user takes. Java events are key to this technique, as they provide programs with the means to detect such user interaction. A very common and very "programmer-friendly" variant is the delegate event model, This model is based on three entities: a control, which is the event source, listeners, that receive the events from the source, interfaces that describe the protocol by which every event is to be communicated. Furthermore, the model requires that every listener must implement the interface for the event it wants to listen to every listener must register with the source to declare its desire to listen to some particular event every time the source generates an event, it communicates it to the registered listeners, following the protocol of the interface. 7. What are the advantages of the model over the event-inheritance model? Ans: in event-inheritance model the event was propagated up the containment hierarchy till it was handled by a component, and wasted time. The delegation event model eliminates this overhead. 8. What is source and listener? Ans: A source is an object that generates an event. This occurs then the internal state of that object changes in some way. An event is an object that describes a state change in a source.

9. What is adapter class? Ans: Adapter class provides an empty implementation of all the methods in EventListener interface. 10. What is meant by controls and what are different types of controls in AWT? Ans: Controls are components that allow a user to interact with your application and the AWT supports the following types of controls: Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are subclasses of Component.

Tutorial Sheet 7

Java Programming and Website Design(ETIT-303)

1. What is the difference between choice and list? Ans: A Choice is displayed in a compact form that requires you to pull it down to see the listof availablechoices. Only one item may be selected from a Choice. A List may be displayed in such away that severalList items are visible. A List supports the selection of one or more List items. 2. What is the difference between scrollbar and scrollpane? Ans: A Scrollbar is a Component, but not a Container whereas Scrollpane is a Container and handles its own events and perform its own scrolling. 3. What is a layout manager and what are different types of layout managers available in java AWT? Ans: A layout manager is an object that is used to organize components in a container.And it is an interface in the java class libraries that describes how a container and a layout manager communicate. There are 5 main Layouts in java: FlowLayout, BorderLayout, CardLayout, GridLayout, GridbagLayout 4. How are the elements of different layouts organized? Ans: FlowLayout: its elements are organized in a top to bottom, left to right fashion. BorderLayout: its elements are organized at the borders (North, South, East and West) and the center of a container. CardLayout: its are stacked, on top of the other, like a deck of cards. GridLayout: its elements are of equal size and are laid out using the square of a grid. GridBagLayout: its elements are organized according to a grid. 5. Which containers use a Border layout as their default layout? Ans: The Window, Frame and Dialog classes use a border layout as their default layout. 6. Which containers use a Flow layout as their default layout? Ans: The Panel and Applet classes use the FlowLayout as their default layout 7. What are wrapper classes? Ans: A primitive wrapper class in the Java programming language is one of eight classes provided in the package to provide object methods for the eight primitive types. 8. What are Vector, Hashtable, LinkedList and Enumeration? Ans: Vector : The Vector class provides the capability to implement a growable array of objects. Hashtable : The Hashtable class implements a Hashtable data structure. A Hashtable indexes and stores objects in a dictionary using hash codes as the objects keys. Hash codes are integer values that identify objects. LinkedList: Removing or inserting elements in the middle of an array can be done using LinkedList. A LinkedList stores each object in a separate link whereas an array stores object references in consecutive locations. Enumeration: An object that implements the Enumeration interface generates a series of elements, one at a time. It has two methods, namely hasMoreElements( ) and nextElement( ). HasMoreElemnts( ) tests if this enumeration has more elements and nextElement method returns successive elements of the series. 9. What is the difference between set and list? Ans: set stores elements in an unordered way but does not contain duplicate elements, where as list stores elements in an ordered way but may contain duplicate elements. 10. What is the difference between Reader/Writer and InputStream/Output Stream? Ans: The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byte-oriented.

Tutorial Sheet 8

Java Programming and Website Design(ETIT-303)

1. What is servlet? Ans: Servlets are Java objects which execute on the server in response to a browser request. They can either generate HTML or XML directly, or call a JSP to produce the output. 2. What are the classes and interfaces for servlets? Ans: The javax.servlet package defines the contract between container and the servlet class. It provides the flexibility to container vendor to implement the API the way they want so long as they follow the specification. To the developers, it provides the library to develop the servlet based applications. 3. What is the difference between an applet and a servlet? Ans: Applets: Applets are applications designed to be transmitted over the network and executed by Java compatible web browsers. An Applet is a client side java program that runs within a Web browser on the client machine. An applet can use the user interface classes like AWT or Swing. Applet Life Cycle Methods: init(), stop(), paint(), start(), destroy() Servlets: Servlets are Java based analog to CGI programs, implemented by means of servlet container associated with an HTTP server. Servlet is a server side component which runs on the web server. The servlet does not have a user interface. Servlet Methods: doGet(), doPost() 4. What is the difference between doPost and doGet methods? Ans: 1.doGet() method is used to get information ,while doPost() method is used for posting information. 2.doGet() requests can't send large amount of information and is limited to 24-255 characters. How ever doPost() requests passes all of it's data ,of unlimited length. 3. A doGet() request is appended to the request URL in a query string and this allows the exchange is visible to the client,where as a doPost() request passes directly over the socket connection as part of its HTTP Request body and the exchange are invisible to the client. 5. What is the life cycle of a servlet? Ans: During initialization stage of the Servlet life cycle, the web container initializes the Servlet instance by calling the init() method. After initialization, the Servlet can service client requests. The web container calls the service() method of the Servlet for every request. The service() method determines the kind of request being made and dispatches it to an appropriate method to handle the request. Finally, the web container calls the destroy() method that takes the Servlet out of service. 6. What are the different servers available for developing and deploying Servlets? Ans: a) Java Web Server b) JRun g) Apache Server h) Netscape Information Server i) Web Logic 7. How many ways can we track client and what are they? Ans: The servlet API provides two ways to track client state and they are: a) Using Session tracking and b) Using Cookies. 8. What is session tracking and how do you track a user session in servlets? Ans: Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are: a) User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password b) Hidden form fields - fields are added to an HTML form that are not displayed in the clients

browser. When the form containing the fields is submitted, the fields are sent back to the server c) URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change. d) Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser. e) HttpSession- places a limit on the number of sessions that can exist in memory. This limit is set in the session.maxresidents property 9. What is Server-Side Includes (SSI)? Ans: SSI (Server Side Includes) are directives that are placed in HTML pages, and evaluated on the server while the pages are being served. They let you add dynamically generated content to an existing HTML page, without having to serve the entire page via a CGI program, or other dynamic technology. 10. What are cookies and how will you use them? Ans: Cookies are a mechanism that a servlet uses to have a client hold a small amount of stateinformation associated with the user. Create a cookie with the cookie constructor: public Cookie(String name,String value) A Servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse: public void HttpServletResponse.addCookie(Cookie cookie) A servlet retrieves cookie by calling the getCookies() method of HttpServletRequest :public Cookie[]HttpServletRequest.getCookie().

Tutorial Sheet 9

Java Programming and Website Design(ETIT-303)

1. Is it possible to communicate from an applet to servlet and how many ways and how? Ans: Yes it is possible to communicate from an applet to servlet. There are several ways for an applet to communicate with a servlet: a. HTTP GET Method - easy to pass simple parameter types like strings to the servlet b. HTTP POST Method - useful for passing a large amount of text or binary data to the servlet c. Object Serialization - PROS: easy to pass complex data to or from a servlet, CONS: only works if the browser running your applet supports JDK 1.1 or later d. The applet can use Java serialization to send and/or receive class objects to/from the servlet. The classes you are passing must implement the java.io.Serializable interface. e. Raw Sockets - PROS: bidirectional communication, CONS: most firewalls do not allow raw socket connections f. RMI - PROS: object-oriented, works with firewalls, CONS: most browsers do not support RMI. 2. What is connection pooling. Why should we go for interservlet communication? Ans: A connection pool is a cache of database connections maintained so that the connections can be reused when future requests to the database are required. Connection pools are used to enhance the performance of executing commands on a database. Opening and maintaining a database connection for each user, especially requests made to a dynamic database-driven website application, is costly and wastes resources. In connection pooling, after a connection is created, it is placed in the pool and it is used over again so that a new connection does not have to be established. If all the connections are being used, a new connection is made and is added to the pool. Connection pooling also cuts down on the amount of time a user must wait to establish a connection to the database. Servlets running together in the same server communicate with each other in several ways. The three major reasons to use interservlet communication are: a. Direct servlet manipulation - allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object) b. Servlet reuse - allows the servlet to reuse the public methods of another servlet. c. Servlet collaboration - requires to communicate with each other by sharing specific information (through method invocation) 3. Is it possible to call servlet with parameters in the URL? Ans: Yes, it is possible to call servlet with parameters in the URL.If HTML form submitted with Get request to servlet URL which is defined in action attribute of HTML form then form values are sent as a name value pairs appended at the end of URL calling servlet 4. What is Servlet chaining? Ans: Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request. In servlet chaining, one servlet output is the input of next servlet. This process continues until the last servlet is reached. Its output is then sent back to the client. We are achieving Servlet Chaining with the help of RequestDispatcher. 5. How do servlets handle multiple simultaneous requests? Ans: The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost( ) and service( ) ) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.

Tutorial Sheet 11

Java Programming and Website Design(ETIT-303)

1. What is the difference between TCP/IP and UDP? Ans: TCP/IP is a two-way communication between the client and the server and it is a reliable and there is a confirmation regarding reaching the message to the destination. UDP is a one-way communication only between the client and the server and it is not a reliable and there is no confirmation regarding reaching the message to the destination. 2. What is Inet address? Ans: An Internet Protocol address is a numerical label assigned to each device participating in a computer network that uses the Internet Protocol for communication. An IP address serves two principal functions: host or network interface identification and location addressing. 3. What is Domain Naming Service(DNS)? Ans: The Domain Name System (DNS) is a hierarchical distributed naming system for computers, services, or any resource connected to the Internet or a private network. A Domain Name Service resolves queries for these names into IP addresses for the purpose of locating computer services and devices worldwide. 4. What is URL? Ans: A uniform resource locator, is a specific character string that constitutes a reference to an Internet resource. 5. What is RMI and steps involved in developing an RMI object?Ans: The Java Remote Method Invocation is a Java API that performs the object-oriented equivalent of remote procedure calls (RPC). The original implementation depends on Java Virtual Machine (JVM) class representation mechanisms and it thus only supports making calls from one JVM to another. Steps involved in developing an RMI object are:i. Enter and compile the source code. ii. Generate Stubs and Skeleton. iii. Install files on the client and server machines. iv. Start the RMI Registry on the Server machine. v. Start the Server. vi. Start the client. 6. What is RMI architecture?

Ans:

Potrebbero piacerti anche