Nội dung text Last minutes exam preparation.pdf
Explain any two components of swing with examples. The basic AWT library deals with user interface elements by delegating their creation and behavior to the native GUI toolkit on each target platform (Windows, Solaris, Macintosh, and so on). This peer-based approach worked well for simple applications. User interface elements such as menus, scrollbars, and text fields can have subtle differences in behavior on different platforms. Moreover, some graphical environments do not have as rich a collection of user interface components as does Windows or the Macintosh Unlike AWT, Java Swing provides platform-independent and lightweight components. The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc. Difference between AWT and Swing There are many differences between java awt and swing that are given below. No. Java AWT Java Swing 1) AWT components are platform- dependent. Java swing components are platform- independent. 2) AWT components are heavyweight. Swing components are lightweight. 3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel. 4) AWT provides less components than Swing. Swing provides more powerful components such as tables, lists, scrollpanes, colorchooser, tabbedpane etc. 5) AWT doesn't follows MVC(Model View Controller) where model represents data, view represents presentation and controller acts as an interface between model and view. Swing follows MVC. Java Swing Example 1 : Using java button: 1. import javax.swing.*; 2. public class FirstSwingExample { 3. public static void main(String[] args) { 4. JFrame f=new JFrame();//creating instance of JFrame 5. JButton b=new JButton("click");//creating instance of JButton 6. b.setBounds(130,100,100, 40);//x axis, y axis, width, height 7. f.add(b);//adding button in JFrame 8. f.setSize(400,500);//400 width and 500 height 9. f.setLayout(null);//using no layout managers 10. f.setVisible(true);//making the frame visible 11. } 12. } Example 2: Java JLabel Example 1. import javax.swing.*; 2. class LabelExample 3. { 4. public static void main(String args[]) 5. { 6. JFrame f= new JFrame("Label Example"); 7. JLabel l1,l2; 8. l1=new JLabel("First Label."); 9. l1.setBounds(50,50, 100,30); 10. l2=new JLabel("Second Label."); 11. l2.setBounds(50,100, 100,30); 12. f.add(l1); f.add(l2); 13. f.setSize(300,300); 14. f.setLayout(null); 15. f.setVisible(true); 16. } 17. } ========================================================= What is the MVC design pattern in swing? Explain Event handling in swing with suitable examples. Swing actually makes use of a simplified variant of the MVC design called the model-delegate . This design combines the view and the controller object into a single element that draws the component to the screen and handles GUI events known as the UI delegate . Bundling graphics capabilities and event handling is somewhat easy in Java, since much of the event handling is taken care of in AWT. As you might expect, the communication between the model and the UI delegate then becomes a two-way street, as shown in Figure below: With Swing, the view and the controller are combined into a UI-delegate object Figure 1-7. With Swing, the view and the controller are combined into a UI-delegate object Each Swing component contains a model and a UI delegate. The model is responsible for maintaining information about the component’s state. The UI delegate is responsible for maintaining information about how to draw the component on the screen. In addition, the UI delegate (in conjunction with AWT) reacts to various events that propagate through the component. Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has a code which is known as an event handler, that is executed when an event occurs. Create the following Java program using any editor of your choice in say D:/ > SWING > com > example> gui > SwingControlDemo.java 1) package com.tutorialspoint.gui; 2) import java.awt.*; 3) import java.awt.event.*; 4) import javax.swing.*; 5) public class SwingControlDemo { 6) private JFrame mainFrame; 7) private JLabel headerLabel; 8) private JLabel statusLabel; 9) private JPanel controlPanel; 10) public SwingControlDemo(){ 11) prepareGUI(); 12) } 13) public static void main(String[] args){ 14) SwingControlDemo swingControlDemo = new SwingControlDemo(); 15) swingControlDemo.showEventDemo(); 16) } 17) private void prepareGUI(){ 18) mainFrame = new JFrame("Java SWING Examples"); 19) mainFrame.setSize(400,400); 20) mainFrame.setLayout(new GridLayout(3, 1)); 21) headerLabel = new JLabel("",JLabel.CENTER ); 22) statusLabel = new JLabel("",JLabel.CENTER); 23) statusLabel.setSize(350,100); 24) mainFrame.addWindowListener(new WindowAdapter() { 25) public void windowClosing(WindowEvent windowEvent){ 26) System.exit(0); 27) } 28) }); 29) controlPanel = new JPanel(); 30) controlPanel.setLayout(new FlowLayout()); 31) mainFrame.add(headerLabel); 32) mainFrame.add(controlPanel); 33) mainFrame.add(statusLabel); 34) mainFrame.setVisible(true); 35) } 36) private void showEventDemo(){ 37) headerLabel.setText("Control in action: Button"); 38) JButton okButton = new JButton("OK"); 39) JButton submitButton = new JButton("Submit"); 40) JButton cancelButton = new JButton("Cancel"); 41) okButton.setActionCommand("OK"); 42) submitButton.setActionCommand("Submit"); 43) cancelButton.setActionCommand("Cancel"); 44) okButton.addActionListener(new ButtonClickListener()); 45) submitButton.addActionListener(new ButtonClickListener()); 46) cancelButton.addActionListener(new ButtonClickListener()); 47) controlPanel.add(okButton); 48) controlPanel.add(submitButton); 49) controlPanel.add(cancelButton); 50) mainFrame.setVisible(true); 51) } 52) private class ButtonClickListener implements ActionListener{ 53) public void actionPerformed(ActionEvent e) { 54) String command = e.getActionCommand(); 55) if( command.equals( "OK" )) { 56) statusLabel.setText("Ok Button clicked."); 57) } else if( command.equals( "Submit" ) ) { 58) statusLabel.setText("Submit Button clicked."); 59) } else { 60) statusLabel.setText("Cancel Button clicked.");}}}} Cookies in Servlet A cookie is a small piece of information that is persisted between the multiple client requests. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. How Cookie works? By default, each request is considered as a new request. In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user. Simple example of Servlet Cookies In this example, we are storing the name of the user in the cookie object and accessing it in another servlet. As we know well that session corresponds to the particular user. So if you access it from too many browsers with different values, you will get the different value. index.html 1) FirstServlet.java 1) import java.io.*; 2) import javax.servlet.*; 3) import javax.servlet.http.*; 4) public class FirstServlet extends HttpServlet { 5) public void doPost(HttpServletRequest request, HttpServletResponse response){ 6) try{ 7) response.setContentType("text/html"); 8) PrintWriter out = response.getWriter(); 9) String n=request.getParameter("userName"); 10) out.print("Welcome "+n); 11) Cookie ck=new Cookie("uname",n);//creating cookie object 12) response.addCookie(ck);//adding cookie in the response 13) //creating submit button 14) out.print(""); 17) out.close(); 18) }catch(Exception e){System.out.println(e);} 19) } 20) } SecondServlet.java 1) import java.io.*; 2) import javax.servlet.*; 3) import javax.servlet.http.*; 4) public class SecondServlet extends HttpServlet { 5) public void doPost(HttpServletRequest request, HttpServletResponse response){ 6) try{ 7) response.setContentType("text/html"); 8) PrintWriter out = response.getWriter(); 9) Cookie ck[]=request.getCookies(); 10) out.print("Hello "+ck[0].getValue()); 11) out.close(); 12) }catch(Exception e){System.out.println(e);} 13) } 14) } web.xml 1) 2) 3) s1 4) FirstServlet 5) 6) 7) s1 8) /servlet1 9) 10) 11) s2 12) SecondServlet 13) 14) 15) s2 16) /servlet2 17) 18)
Explain different types of tags in JSP with examples. JSP Scripting elements The scripting elements provides the ability to insert java code inside the jsp. There are three types of scripting elements: 1) scriptlet tag 2) expression tag 3) declaration tag 1. JSP scriptlet tag A scriptlet tag is used to execute java source code in JSP. Syntax is as follows: <% java source code %> Example of JSP scriptlet tag that prints the user name In this example, we have created two files index.html and welcome.jsp. The index.html file gets the username from the user and the welcome.jsp file prints the username with the welcome message. File: index.html File: welcome.jsp <% String name=request.getParameter("uname"); out.print("welcome "+name); %> 2. JSP expression tag The code placed within JSP expression tag is written to the output stream of the response. So you need not write out.print() to write data. It is mainly used to print the values of variable or method. Example of JSP expression tag that prints the user name In this example, we are printing the username using the expression tag. The index.html file gets the username and sends the request to the welcome.jsp file, which displays the username. File: index.jsp File: welcome.jsp <%= "Welcome "+request.getParameter("uname") %> 3. JSP declaration tag The JSP declaration tag is used to declare fields and methods. The code written inside the jsp declaration tag is placed outside the service() method of auto generated servlet. So it doesn't get memory at each request. Example of JSP declaration tag that declares method In this example of JSP declaration tag, we are defining the method which returns the cube of given number and calling this method from the jsp expression tag. But we can also use jsp scriptlet tag to call the declared method. index.jsp <%! int cube(int n){ return n*n*n*; } %> <%= "Cube of 3 is:"+cube(3) %> ========================================================== Why are adapter classes important? Compare it with the listener interface with suitable examples. Java adapter classes provide the default implementation of listener interfaces. If you inherit the adapter class, you will not be forced to provide the implementation of all the methods of listener interfaces. So it saves code. Pros of using Adapter classes: • It assists the unrelated classes to work combinedly. • It provides ways to use classes in different ways. • It increases the transparency of classes. • It provides a way to include related patterns in the class. • It provides a pluggable kit for developing an application. • It increases the reusability of the class. Listeners are used when the programmer intends to utilize most of the methods listed under the interface. If a listener interface is implemented directly by a class, all the methods within that interface need to be implemented, making the code unreasonably large. This complexity can be resolved by calling upon an adapter class. An adapter class proves essential in instances where an event calls for only specific methods. The programmer has only to create a subclass of it and override the interest methods to use an adapter class. Adapter classes are, therefore, beneficial for listener interfaces in JAVA having more than one method. To better understand this, let us consider the example of the MouseListener interface. This interface is notified whenever there is a change in the state of the mouse. It has five methods, mouse clicked, mouseExited, mouseEntered, mousePressed, and mouseReleased. Java WindowAdapter Example In the following example, we are implementing the WindowAdapter class of AWT and one its methods windowClosing() to close the frame window. AdapterExample.java 1) import java.awt.*; 2) import java.awt.event.*; 3) public class AdapterExample { 4) // object of Frame 5) Frame f; 6) // class constructor 7) AdapterExample() { 8) // creating a frame with the title 9) f = new Frame ("Window Adapter"); 10) // adding the WindowListener to the frame 11) // overriding the windowClosing() method 12) f.addWindowListener (new WindowAdapter() { 13) public void windowClosing (WindowEvent e) { 14) f.dispose(); 15) } 16) }); 17) // setting the size, layout and 18) f.setSize (400, 400); 19) f.setLayout (null); 20) f.setVisible (true); 21) } 22) // main method 23) public static void main(String[] args) { 24) new AdapterExample(); 25) } 26) } ========================================================== What is Java bean? Explain Properties, Events and Methods design patterns. A JavaBean is a Java class that should follow the following conventions: • It should have a no-arg constructor. • It should be Serializable. • It should provide methods to set and get the values of the properties, known as getter and setter methods. A JavaBean property may be read, write, read-only, or write-only. JavaBean features are accessed through two methods in the JavaBean's implementation class: 1. getPropertyName () For example, if the property name is firstName, the method name would be getFirstName() to read that property. This method is called the accessor. 2. setPropertyName () For example, if the property name is firstName, the method name would be setFirstName() to write that property. This method is called the mutator. Property design patterns are used to identify the properties of a Bean. Not surprisingly, property design patterns are closely related to accessor methods. In fact, accessor methods are the means by which the JavaBean's automatic introspection facility determines the properties of a Bean. Basically, any time the JavaBeans introspector encounters a public getter or setter method, it assumes the member variable being get or set is a property, and then exposes the property to the outside world. ========================================================== Explain RMI Architecture in detail. Remote Method Invocation (RMI) is an API that allows an object to invoke a method on an object that exists in another address space, which could be on the same machine or on a remote machine. Through RMI, an object running in a JVM present on a computer (Client-side) can invoke methods on an object present in another JVM (Server-side). RMI creates a public remote server object that enables client and server-side communications through simple method calls on the server object. Transport Layer : This layer connects the client and the server. It manages the existing connection and also sets up new connections. Stub : A stub is a representation (proxy) of the remote object at client. It resides in the client system; it acts as a gateway for the client program. Skeleton: This is the object which resides on the server side. stub communicates with this skeleton to pass request to the remote object. RRL(Remote Reference Layer): It is the layer which manages the references made by the client to the remote object. Working of an RMI Application The following points summarize how an RMI application works − • When the client makes a call to the remote object, it is received by the stub which eventually passes this request to the RRL. • When the client-side RRL receives the request, it invokes a method called invoke() of the object remoteRef. It passes the request to the RRL on the server side. • The RRL on the server side passes the request to the Skeleton (proxy on the server) which finally invokes the required object on the server. • The result is passed all the way back to the client. Goals of RMI Following are the goals of RMI − • To minimize the complexity of the application. • To preserve type safety. • Distributed garbage collection. • Minimize the difference between working with local and remote objects. ========================================================== Explain about different types of ResultSet used in JDBC. There are two types of result sets namely, forward only and, bidirectional. 1. Forward only ResultSet: The ResultSet object whose cursor moves only in one direction is known as forward only ResultSet. By default, JDBC result sets are forward-only result sets. You can move the cursor of the forward only ResultSets using the next() method of the ResultSet interface. It moves the pointer to the next row from the current position. This method returns a boolean value. If there are no rows next to its current position it returns false, else it returns true. Therefore, using this method in the while loop you can iterate the contents of the ResultSet object. while(rs.next()){ } 2. Bidirectional ResultSet: A bi-directional ResultSet object is the one whose cursor moves in both forward and backward directions. The createStatement() method of the Connection interface has a variant which accepts two integer values representing the result set type and the concurrency type. Statement createStatement(int resultSetType, int resultSetConcurrency) To create a bi-directional result set you need to pass the type as ResultSet.TYPE_SCROLL_SENSITIVE or ResultSet.TYPE_SCROLL_INSENSITIVE, along with the concurrency, to this method as: //Creating a Statement object Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ========================================================== =
Difference between RMI and CORBA RMI CORBA RMI is a Java-specific technology. CORBA has implementation for many languages. It uses Java interface for implementation. It uses Interface Definition Language (IDL) to separate interface from implementation. RMI objects are garbage collected automatically. CORBA objects are not garbage collected because it is language independent and some languages like C++ does not support garbage collection. RMI programs can download new classes from remote JVM’s. CORBA does not support this code sharing mechanism. RMI passes objects by remote reference or by value. CORBA passes objects by reference. The responsibility of locating an object implementation falls on JVM. The responsibility of locating an object implementation falls on Object Adapter either Basic Object Adapter or Portable Object Adapter. RMI uses the Java Remote Method Protocol as its underlying remoting protocol. CORBA use Internet Inter- ORB Protocol as its underlying remoting protocol. ========================================================= ========================================================= why do we use panels while creating GUI program in java? By using Panels it's easier to group components and arrange them in a Frame. Every Panel can have it's own layout. So you could give your outer Frame a BorderLayout and put a Panel into the center. The Panel then can have let's say a GridBagLayout for it's components. A panel is a container. • It allows you to group components together • It allows you to devise complex interfaces, as each panel can have a different layout, allowing you to leverage the power of different layout managers. • It allows you to build reusable components and isolate responsibility • But most of all, it gives you the bases for deciding how the panel should be deployed. With a panel you can add it to a frame or applet or another component as needed... • A panel also makes a good surface onto which to perform custom painting. For all the benefits mentioned above - its isolated and reusable... ========================================================== Cookies and using handling cookies in Java Cookies are the textual information that is stored in key-value pair format to the client’s browser during multiple requests. It is one of the state management techniques in session tracking. Basically, the server treats every client request as a new one so to avoid this situation cookies are used. When the client generates a request, the server gives the response with cookies having an id which are then stored in the client’s browser. Thus if the client generates a second request, a cookie with the matched id is also sent to the server. The server will fetch the cookie id, if found it will treat it as an old request otherwise the request is considered new. Methods in Cookies 1) clone(): Overrides the standard java.lang.Object.clone method to return a copy of this Cookie. 2) getComment(): Returns the comment describing the purpose of this cookie, or null if the cookie has no comment. 3) getDomain(): Gets the domain name of this Cookie. 4) getMaxAge(): Gets the maximum age in seconds of this Cookie. 5) getName(): Returns the name of the cookie. 6) getPath(): Returns the path on the server to which the browser returns this cookie. 7) getSecure(): Returns true if the browser is sending cookies only over a secure protocol, or false if the browser can send cookies using any protocol. 8) getValue(): Gets the current value of this Cookie. 9) getVersion(): Returns the version of the protocol this cookie complies with. 10) setValue(String newValue): Assigns a new value to this Cookie. 11) setVersion(int v): Sets the version of the cookie protocol that this Cookie complies with. What is an Event Handling and describe the components in Event Handling in Java? Explain with example ? The GUI in Java processes the interactions with users via mouse, keyboard and various user controls such as button, checkbox, text field, etc. as the events. These events are to be handled properly to implement Java as an Event-Driven Programming. Components in Event Handling • Events • Event Sources • Event Listeners/Handlers 1. Events • The events are defined as an object that describes a change in the state of a source object. • The Java defines a number of such Event Classes inside java.awt.event package • Some of the events are ActionEvent, MouseEvent, KeyEvent, FocusEvent, ItemEvent and etc. 2. Event Sources • A source is an object that generates an event. • An event generation occurs when an internal state of that object changes in some way. • A source must register listeners in order for the listeners to receive the notifications about a specific type of event. • Some of the event sources are Button, CheckBox, List, Choice, Window and etc. 3. Event Listeners • A listener is an object that is notified when an event occurs. • A Listener has two major requirements, it should be registered to one more source object to receiving event notification and it must implement methods to receive and process those notifications. • Java has defined a set of interfaces for receiving and processing the events under the java.awt.event package. • Some of the listeners are ActionListener, MouseListener, ItemListener, KeyListener, WindowListener and etc. Example 1. import java.awt.*; 2. import java.awt.event.*; 3. import javax.swing.*; 4. public class EventListenerTest extends JFrame implements ActionListener { 5. JButton button; 6. public static void main(String args[]) { 7. EventListenerTest object = new EventListenerTest(); 8. object.createGUI(); 9. } 10. void createGUI() { 11. button = new JButton(" Click Me !"); 12. setSize(300,200); 13. setLocationRelativeTo(null); 14. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 15. setVisible(true); 16. add(button); 17. button.addActionListener(this); 18. } 19. public void actionPerformed(ActionEvent ae) { 20. if(ae.getSource() == button) { 21. JOptionPane.showMessageDialog(null, "Generates an Action Event"); 22. } 23. } 24. } ========================================================== Marshalling and Unmarshalling Whenever a client invokes a method that accepts parameters on a remote object, the parameters are bundled into a message before being sent over the network. These parameters may be of primitive type or objects. In case of primitive type, the parameters are put together and a header is attached to it. In case the parameters are objects, then they are serialized. This process is known as marshalling. At the server side, the packed parameters are unbundled and then the required method is invoked. This process is known as unmarshalling. ======================================================== SimplePropertyBeanMain.java(java bean Example) public class SimplePropertyBeanMain { public static void main(String args[]) { SimplePropertyBean ob=new SimplePropertyBean(); ob.setLength(5); ob.setBreadth(3); ob.setHeight(2); System.out.println("Volume :"+ob.getLength()*ob.getBreadth()*ob.getHeight()); } } ========================================================= JavaBean and its properties with example. A JavaBean is a Java class that should follow the following conventions: o It should have a no-arg constructor. o It should be Serializable. o It should provide methods to set and get the values of the properties, known as getter and setter methods. Why use JavaBean? According to Java white paper, it is a reusable software component. A bean encapsulates many objects into one object so that we can access this object from multiple places. Moreover, it provides easy maintenance. Simple example of JavaBean class 1. //Employee.java 2. 3. package mypack; 4. public class Employee implements java.io.Serializable{ 5. private int id; 6. private String name; 7. public Employee(){} 8. public void setId(int id){this.id=id;} 9. public int getId(){return id;} 10. public void setName(String name){this.name=name;} 11. public String getName(){return name;} 12. } How to access the JavaBean class? To access the JavaBean class, we should use getter and setter methods. 1. package mypack; 2. public class Test{ 3. public static void main(String args[]){ 4. Employee e=new Employee();//object is created 5. e.setName("Arjun");//setting value to the object 6. System.out.println(e.getName()); 7. }} Note: There are two ways to provide values to the object. One way is by constructor and second is by setter method. JavaBean Properties A JavaBean property is a named feature that can be accessed by the user of the object. The feature can be of any Java data type, containing the classes that you define. A JavaBean property may be read, write, read-only, or write-only. JavaBean features are accessed through two methods in the JavaBean's implementation class: 1. getPropertyName () For example, if the property name is firstName, the method name would be getFirstName() to read that property. This method is called the accessor. 2. setPropertyName () For example, if the property name is firstName, the method name would be setFirstName() to write that property. This method is called the mutator. Advantages of JavaBean The following are the advantages of JavaBean:/p> o The JavaBean properties and methods can be exposed to another application. o It provides an easiness to reuse the software components. Disadvantages of JavaBean The following are the disadvantages of JavaBean: o JavaBeans are mutable. So, it can't take advantages of immutable objects. o Creating the setter and getter method for each property separately may lead to the boilerplate code. ========================================================== Working with 2D Shapes Starting with Java 1.0, the Graphics class from java.awt package has methods to draw strings, lines, rectangles, ellipses, and so on. For example to draw line, we use drawLine(x1, y1, x2, y2) method as show below, class SimplePanel extends JPanel { public void paintComponent(Graphics g) { g.drawLine(10,10,100,100); } } To draw rectangles, we use drawRect(x1, y1, w, h) method and to draw string we use drawString(▫String▫, x1, y1) and so on. The drawings using Graphics class methods are very limited. For example, you cannot vary the line thickness and cannot rotate the shapes. program : class SimplePanel extends JPanel { public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D)g; Rectangle2D floatRect = new Rectangle2D.Float (10, 15.5F, 52.5F, 60.0F); g2d.draw(floatRect); } } =========================================================
Life Cycle of a Servlet (Servlet Life Cycle) The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet: • Servlet class is loaded. • Servlet instance is created. • init method is invoked. • service method is invoked. • destroy method is invoked. As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet is in new state if servlet instance is created. After invoking the init() method, Servlet comes in the ready state. In the ready state, servlet performs all the tasks. When the web container invokes the destroy() method, it shifts to the end state. 1) Servlet class is loaded The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is received by the web container. 2) Servlet instance is created The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle. 3) init method is invoked The web container calls the init method only once after creating the servlet instance. The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below: public void init(ServletConfig config) throws ServletException 4) service method is invoked The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given below: public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException 5) destroy method is invoked The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy method of the Servlet interface is given below: public void destroy() ========================================================== Servlet vs JSP Servlet JSP Servlets are faster as compared to JSP, as they have a short response time. JSP is slower than Servlets, as the first step in the JSP lifecycle is the conversion of JSP to Java code and then the compilation of the code. Servlets are Java-based codes. JSP are HTML-based codes. Servlets are harder to code, as here, the HTML codes are written in Java. JSPs are easier to code, as here Java is coded in HTML. In an MVC architecture, Servlets act as the controllers. In MVC architectures, the JSPs act as a view to present the output to the users. The service() function can be overridden in Servlets. The service() function cannot be overridden in JSPs. The Servlets are capable of accepting all types of protocol requests. The JSPs are confined to accept only the HTTP requests. Modification in Servlets is a time-consuming and challenging task, as here, one will have to reload, recompile, and then restart the servers. Modification is easy and faster in JSPs as we just need to refresh the pages. What is a LayoutManager and types of LayoutManager in Java? The Layout managers enable us to control the way in which visual components are arranged in the GUI forms by determining the size and position of components within the containers. Types of LayoutManager There are 6 layout managers in Java • FlowLayout: It arranges the components in a container like the words on a page. It fills the top line from left to right and top to bottom. The components are arranged in the order as they are added i.e. first components appears at top left, if the container is not wide enough to display all the components, it is wrapped around the line. Vertical and horizontal gap between components can be controlled. The components can be left, center or right aligned. • BorderLayout: It arranges all the components along the edges or the middle of the container i.e. top, bottom, right and left edges of the area. The components added to the top or bottom gets its preferred height, but its width will be the width of the container and also the components added to the left or right gets its preferred width, but its height will be the remaining height of the container. The components added to the center gets neither its preferred height or width. It covers the remaining area of the container. • GridLayout: It arranges all the components in a grid of equally sized cells, adding them from the left to right and top to bottom. Only one component can be placed in a cell and each region of the grid will have the same size. When the container is resized, all cells are automatically resized. The order of placing the components in a cell is determined as they were added. • GridBagLayout: It is a powerful layout which arranges all the components in a grid of cells and maintains the aspect ration of the object whenever the container is resized. In this layout, cells may be different in size. It assigns a consistent horizontal and vertical gap among components. It allows us to specify a default alignment for components within the columns or rows. • BoxLayout: It arranges multiple components in either vertically or horizontally, but not both. The components are arranged from left to right or top to bottom. If the components are aligned horizontally, the height of all components will be the same and equal to the largest sized components. If the components are aligned vertically, the width of all components will be the same and equal to the largest width components. • CardLayout: It arranges two or more components having the same size. The components are arranged in a deck, where all the cards of the same size and the only top card are visible at any time. The first component added in the container will be kept at the top of the deck. The default gap at the left, right, top and bottom edges are zero and the card components are displayed either horizontally or vertically. Example 1) import java.awt.*; 2) import javax.swing.*; 3) public class LayoutManagerTest extends JFrame { 4) JPanel flowLayoutPanel1, flowLayoutPanel2, gridLayoutPanel1, gridLayoutPanel2, gridLayoutPanel3; 5) JButton one, two, three, four, five, six; 6) JLabel bottom, lbl1, lbl2, lbl3; 7) public LayoutManagerTest() { 8) setTitle("LayoutManager Test"); 9) setLayout(new BorderLayout()); 10) // Set BorderLayout for JFrame 11) flowLayoutPanel1 = new JPanel(); 12) one = new JButton("One"); 13) two = new JButton("Two"); 14) three = new JButton("Three"); 15) flowLayoutPanel1.setLayout(new FlowLayout(FlowLayout.CENTER)); 16) // Set FlowLayout Manager 17) flowLayoutPanel1.add(one); 18) flowLayoutPanel1.add(two); 19) flowLayoutPanel1.add(three); 20) flowLayoutPanel2 = new JPanel(); 21) bottom = new JLabel("This is South"); 22) flowLayoutPanel2.setLayout (new FlowLayout(FlowLayout.CENTER)) ; // Set FlowLayout Manager 23) flowLayoutPanel2.add(bottom); 24) gridLayoutPanel1 = new JPanel(); 25) gridLayoutPanel2 = new JPanel(); 26) gridLayoutPanel3 = new JPanel(); 27) lbl1 = new JLabel("One"); 28) lbl2 = new JLabel("Two"); 29) lbl3 = new JLabel("Three"); 30) four = new JButton("Four"); 31) five = new JButton("Five"); 32) six = new JButton("Six"); 33) gridLayoutPanel2.setLayout(new GridLayout(1, 3, 5, 5)); // Set GridLayout Manager 34) gridLayoutPanel2.add(lbl1); 35) gridLayoutPanel2.add(lbl2) 36) gridLayoutPanel2.add(lbl3); 37) gridLayoutPanel3.setLayout(new GridLayout(3, 1, 5, 5)); // Set GridLayout Manager 38) gridLayoutPanel3.add(four); 39) gridLayoutPanel3.add(five); 40) gridLayoutPanel3.add(six); 41) gridLayoutPanel1.setLayout(new GridLayout(2, 1)); // Set GridLayout Manager 42) gridLayoutPanel1.add(gridLayoutPanel2); 43) gridLayoutPanel1.add(gridLayoutPanel3); 44) add(flowLayoutPanel1, BorderLayout.NORTH); 45) add(flowLayoutPanel2, BorderLayout.SOUTH); 46) add(gridLayoutPanel1, BorderLayout.CENTER); 47) setSize(400, 325); 48) setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 49) setLocationRelativeTo(null); 50) setVisible(true); 51) } 52) public static void main(String args[]) { 53) new LayoutManagerTest(); 54) } 55) } Output: ========================================================== Session Tracking in Servlets Session simply means a particular interval of time. Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet. Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user. HTTP is stateless that means each request is considered as the new request. It is shown in the figure given below: We use session tracking To recognize the user It is used to recognize the particular user. Session Tracking Techniques There are four techniques used in Session tracking: • Cookies • Hidden Form Field • URL Rewriting • HttpSession ================================================== Difference between scrollable and updateable resultSet with example. Scrollable result set Updateable result set you can move forward and backward through a result set and even jump to any position. you can programmatically update entries so that the database is automatically updated. Statement stmt = conn.createStatem ent(type, concurrency); Statement stmt =conn.createStatement(ResultSet.TYPE_S CROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); =========================================================