Asian
Short Answer Questions:
- Define Event handling.
Event handling is a mechanism that controls the event and decides what should happen if an event occurs. - What is Java Servlet?
Servlet is a small java program that runs within a server.Servlet receive and respond to request from web clients,usually across HTTP,the HyperText Transfer Protocol. - What is JFrame?
JFrame is a class of javax.swing package extended by java.awt.frame, it adds support for JFC/SWING component architecture. It is the top level window, with border and a title bar. JFrame class has many methods which can be used to customize it. - What are the two exceptions related with Servlet?
– ServletException
– IOException - How do you create constant variable in Java?
Final keyword - Name the event generated when the button is clicked?
ActionEvent - What is application server?
An application server is a software framework that provides both facilities to create web applications and a server environment to run them. - What is XML?
XML schema is a language which is used for expressing constraint about XML documents. - Define PreparedStatement.
A prepared statement is a feature used to execute the same (or similar) SQLstatements repeatedly with high efficiency. - What does mean by implicit object in JSP?
JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared.
Short Answer Questions:
2.Write a program passing parameter in applet.Write complete HTML file to include applet.
1 2 3 4 5 6 7 8 |
import java.applet.Applet; import java.awt.Graphics; public class UseParam extends Applet{ public void paint(Graphics g){ String str=getParameter("msg"); g.drawString(str,50, 50); } } |
3.Explain two key swing features.
Swing offers two key features:
Swing components are lightweight and don’t rely on peers. Swing supports a pluggable look and feel. The three PLAFs available to all users are Metal (default), Windows, and Motif.
4.Write a swing program demonstrating GridLayout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package assignment; import java.awt.*; import javax.swing.*; public class GridLayoutDemo{ public GridLayoutDemo(){ JFrame f=new JFrame(); JButton b1=new JButton("1"); JButton b2=new JButton("2"); JButton b3=new JButton("3"); JButton b4=new JButton("4"); JButton b5=new JButton("5"); JButton b6=new JButton("6"); JButton b7=new JButton("7"); JButton b8=new JButton("8"); JButton b9=new JButton("9"); f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5); f.add(b6);f.add(b7);f.add(b8);f.add(b9); f.setLayout(new GridLayout(3,3,10,2)); f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { try { // UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); // UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception e) { System.out.println("Look and Feel not set"); } new GridLayoutDemo(); } } |
5.JSP is slower than Servlet.Explain.
A Servlet is faster than a JSP.
This is because the JSP is first converted into a servlet and then processed. The processing of JSP to convert to a Servlet is extra and hence you can conclude that JSP is slower than a Servlet.
Differentiate between SAX and DOM parser.
1) DOM parser loads whole XML document in memory while SAX only loads a small part of the XML file in memory.
2) DOM parser is faster than SAX because it access whole XML document in memory.
3) SAX parser in Java is better suitable for large XML file than DOM Parser because it doesn’t require much memory.
4) DOM parser works on Document Object Model while SAX is an event based XML parser.
Long Answer Questions:
7.Write a program to insert data using JDBC in MYSql database called contact_db.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package database; import java.sql.*; public class InsertData { public static void main(String args[]) throws Exception { String url = "jdbc:mysql://localhost:3307/contact_db"; String uname = "root"; String pwd = ""; Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(url, uname, pwd); Statement stmt = con.createStatement(); stmt.executeUpdate("insert into user values(15,'Sush',23,'Sundarijal')"); System.out.println("records affected"); con.close(); } } |
8.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
package swing-demo; import javax.swing.*; import java.awt.*; import java.awt.event.*; class Sushmita implements ActionListener { JFrame frame = new JFrame("Registration Form"); Container con = frame.getContentPane(); JLabel headLbl, nameLabel, addressLabel, genderLabel, hobbyLabel; JTextField nameTextFeild, addressTextField; JComboBox cb; JRadioButton r1, r2; ButtonGroup gender = new ButtonGroup(); JComboBox music, sport; JButton submit, reset; JTextArea display; Sushmita() { frame.setBounds(150, 90, 740, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); con.setBackground(Color.YELLOW); con.setLayout(null); Font f = new Font("Times New Roman", Font.BOLD, 30); headLbl = new JLabel("Registration Form"); headLbl.setBounds(250, 5, 400, 35); headLbl.setFont(f); con.add(headLbl); nameLabel = new JLabel("Name"); nameLabel.setBounds(50, 50, 60, 30); con.add(nameLabel); genderLabel = new JLabel("Gender"); genderLabel.setBounds(50, 100, 60, 30); con.add(genderLabel); addressLabel = new JLabel("Address"); addressLabel.setBounds(50, 150, 60, 30); con.add(addressLabel); nameTextFeild = new JTextField(); nameTextFeild.setBounds(130, 53, 180, 20); con.add(nameTextFeild); r1 = new JRadioButton("Male"); r1.setBounds(130, 103, 80, 20); r1.setBackground(Color.YELLOW); con.add(r1); r2 = new JRadioButton("Female"); r2.setBounds(250, 103, 80, 20); r2.setBackground(Color.YELLOW); con.add(r2); gender.add(r1); gender.add(r2); addressTextField = new JTextField(); addressTextField.setBounds(130, 150, 180, 20); con.add(addressTextField); hobbyLabel = new JLabel("Hobby"); hobbyLabel.setBounds(50, 200, 60, 30); con.add(hobbyLabel); String hobbies[] = { "music", "sports" }; cb = new JComboBox<>(hobbies); cb.setBounds(110, 200, 90, 20); con.add(cb); submit = new JButton("SUBMIT"); submit.setBounds(100, 350, 80, 25); con.add(submit); reset = new JButton("RESET"); reset.setBounds(200, 350, 80, 25); con.add(reset); Font ff = new Font("Times New Roman", Font.BOLD, 15); display = new JTextArea(); display.setBounds(400, 50, 300, 350); con.add(display); display.setFont(ff); display.setBackground(Color.GRAY); display.setEditable(false); submit.addActionListener(this); reset.addActionListener(this); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { String ch = e.getActionCommand(); if (ch == "SUBMIT") { String name = nameTextFeild.getText(); String gen = "male"; if (r2.isSelected()) { gen = "female"; } String address = addressTextField.getText(); String hobby = cb.getSelectedItem().toString(); display.setText( "\n\nName: " + name + "\nGender: " + gen + "\nAddress: " + address + "\nHobby: " + hobby); } else { nameTextFeild.setText(null); addressTextField.setText(null); display.setText(null); gender.clearSelection(); } } } public class Registration { public static void main(String[] args) { Sushmita sp = new Sushmita(); } } |
NCC
Group A
Qno.1.
i.
Ans The two types of Applet are :
– JApplet (Applet class of swing)
-Applet (Applet class of AWT).
ii.
Ans Event listener is the interface which is get notified after event occured if an event is registered with the listener.
Key listener, Mouse listener, etc are some of the event listener.
iii.
Ans In AWT, a radio button is created
by grouping checkbox.
For eg: Checkbox Group cb = new Checkbox Group (); Checkbox checkbox 1 = new checkbox (Checkbox 1, cb, true);
checkbox checkbox 2 = new check box (Check box 2, cb, false);
iv.
Ans The two swing key features are
– Swing are lightweight.
– Swing has pluggable look and feel.
(v)
Ans. The difference between Swing and AWT are:
AWT | Swing |
1). It is lightweight. | It is heavy weight. |
2) It is platform independent. | It is platform dependent. |
vi.
Ans 3 tier architecture is the architecture having 3 layers in the network. All the layers are dependent of each other.In this architecture, the presentation logic, business logic and data are logically distributed in three tiers.
vii Ans:
Steps to connect in JDBC are:
- Register the driver with driver manager.
- Obtain connection from driver.
- Obtain statement from connection.
- Run the query using statement.
- Close the connection
Viii. Ans:
XML is the extensible Mark up language which are used to store data in a tree like structure. XML has no pre defined tags like of HTML.XML tags are based on XML document.
For eg.
<name> ……………..root node
<fname>Java</fname>……..child node
<lname > PHP</lname>…….child node
</name>
ix. Ans:
We store data in session using setAttribute() and retrieve the data using getAttribute().
For storing data in session
session.setAttribute(“name”,new String(“JAVA”));
For retrieving session
String=(String)session.getAttribute(“name”);
x. Ans:
A web container is the JEE specific container that include web component. Simply, it is the run-time environment to execute the web component.
Group-B
Qno.2.
Source Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import java.sql.*; public class question_2 { Public static void main(String[] args) { String sql=”select * from student_db”; String url=”jdbc:mysql://localhost:3306/college_db”; String user=”root”; Statement st=null; Connection con=null; try { Class.forName(“com.mysql.jdbc.Driver”); conn=DriverManager.getConnection(url,user,””); if(conn!=null) { st=conn.createStatement(); ResultSet rs=st.executeQuery(sql); While(rs.next()) { System.out.println(“ID:”+rs.getInt(“id”)); System.out.println(“Name:”+rs.getString(“name”)); System.out.println(“Roll:”+rs.getInt(“roll”)); System.out.println(“Marks:”+rs.getInt(“marks”)); } } } catch(SQLException | ClassNotFoundException e) { e.printStackTrace(); } } } |
Qno.3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import javax.swing ; public class Factorial extends JFrame public class Factorical(){ Jlabel l1 = new JLabel ("Enter number”); Jlabel l2= new JLabel (""Result"”); JTextField t1 = new JTextField(); JTextField t2 = new JTextField(); JButton b1 = new JButton ("Find Factorial"); getsize (500, 600); set visible (true); set layout (new Grid Layout (3, 2); bl.add Action listener (new Action listener() { public void action performed (Action Event e) { int num, fact= 1; num Integer.parse Int (t1.getText()); for (i=1;i<=num ; i++) { fact=fact* i; } t2.settext (String.valueof ("fact"); } }); } } |
Qno.4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.ncc.swingdemo.jdbc.basic; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class InsertDemo { public static void main(String[] args) { String sql="INSERT INTO employee_tbl(id,emp_name, emp_salary)VALUES (1,'NCC',20000)"; Connection con = null; Statement st = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/company_db", "root", ""); st = con.createStatement(); st.executeUpdate(sql); System.out.println("Data Inserted"); } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); } } } |
Qno.5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.ncc.ServletDemo.basic; import javax.servlet.*; public class Qno_5 extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String name=req.getParameter("n"); String a=request.getParameter("a"); int age=0; if(a!=null) { age=Integer.parseInt(a); } response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("Name is:"+name); out.println("Age is:"+age); }} |
Group C
Qno.6.
Ans: Delegation model is the modern approach of handling the event that defines standard and consistent mechanism to create the event and control the event.
Source Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
package demo; import java.applet*; import java.awt.*; public class MouseEvents extends Applet implements MouseListener, MouseMotionListener { String msg = ""; // coordinates of mouse int mouseX = 0; int mouseY = 0; public void init() { addMouseListener(this); addMouseMotionListener(this); } public void mouseDragged(MouseEvent e) { mouseX = e.getX(); mouseY = e.getY(); msg = "*"; showStatus("Dragging mouse at " + mouseX + "," + mouseY); repaint(); } public void mouseMoved(MouseEvent e) { showStatus("Moving mouse at: " + e.getX() + "," + e.getY()); } public void mouseClicked(MouseEvent e) { mouseX = 0; mouseY = 10; msg = "mouse clicked"; repaint(); } public void mousePressed(MouseEvent e) { mouseX = e.getX(); mouseY = e.getY(); msg = "Down"; repaint(); } public void mouseReleased(MouseEvent e) { mouseX = e.getX(); mouseY = e.getY(); msg = "Up"; repaint(); } public void mouseEntered(MouseEvent e) { mouseX = 0; mouseY = 10; msg = "mouse entered"; repaint(); } public void mouseExited(MouseEvent e) { mouseX = 0; mouseY = 10; msg = "mouse exited"; repaint(); } // Display msg in applet window at current X,Y location. public void paint(Graphics g) { g.drawString(msg, mouseX, mouseY); } } |
Qno.7.
Ans: Servlet is the java program that generates dynamic web pages and extends the functionality of server.
The lifecycle methods of servlet are:
- init()
The init() methods run once in a servlet that initialize the servlet object and variables. - service()
The service() methods deals with dynamic request of client and generate the dynamic web pages. - destroy()
The destroy method() is used before deleting the servlet from memory.
Deployment Descriptor
Web container uses XML based file to read the information about servlet and name the file as web.xml which is known as deployment descriptor.
//Structure of Deployment Descriptor
<web-app>
<servlet>
<servlet_name>Demo</servlet_name>
<servlet_class>com.ServletDemo</servlet_class>
</servlet>
<servlet_mapping>
<servlet_name> Demo</servlet_name>
<url_pattern>/demo</url_pattern>
</servlet_mapping>
</web_app>
St. Xaviers
Group A
- What are two key features of swing?
-
- Swing components are lightweight and don’t rely on peers.
- Swing supports a pluggable look and feel.
- Difference between listener interface and adapter class.
Listener Interface |
Adapter Class |
All the methods in needs to be overridden. | It is ‘blank’ implementation of listener interface. |
It ensures multiple inheritance for any event. | It does not support multiple inheritance. |
- What are the different places for putting event handling code?
-
- Same class (by implementing listener interface in same class)
- Inner anonymous class
- Outer class ( by implementing listener interface in separate class)
- What is SQL exception?
The SQL Exception class provides information on a database access error.
- What are the different types of drivers used in JDBC?
-
- JDBC-ODBC bridge driver,
- Native-API driver,
- Network Protocol driver,
- Thin driver.
- What is servlet?
Servlets are the Java programs that runs on the Java-enabled web server or application server. They are used to handle the request obtained from the web server, process the request, produce the response, and then send response back to the web server.
- What is request dispatcher?
Request Dispatcher is an interface whose implementation defines an object which can dispatch the request to any resources on the server.
- What is state maintenance in servlet?
Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests to the server.
- List the different jsp tag.
-
- Declarative tag
<% ! … %>
- Declarative tag
-
- Directive tag
<%@ page … %
<%@ include … %>
<%@ taglib … %>
- Directive tag
-
- Scriplet tag
<% … %>
- Scriplet tag
-
- Expression tag
<%= … %>
- Expression tag
- Difference between XML and HTML.
Group B
- Create a HTML document that contain the header information of page and include this HTML as a header file in JSP.
// index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<html> <head> <title>Header Information</title> <style> p{ color: red; } </style> </head> <body> <p>This text is red</p> </body> </html> |
//header.jsp
<% @include file=”index.html” %>
- What is key event? How is it handled in java? Explain with suitable java source code.
On entering the character the Key event is generated. There are three types of key events which are represented by the integer constants. These key events are following
- KEY_PRESSED
- KEY_RELASED
- KEY_TYPED
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.awt.*; import java.awt.event.*; public class KeyListenerExample extends Frame implements KeyListener{ Label l; TextArea area; KeyListenerExample(){ l=new Label(); l.setBounds(20,50,100,20); area=new TextArea(); area.setBounds(20,80,300, 300); area.addKeyListener(this); add(l);add(area); setSize(400,400); setLayout(null); setVisible(true); } public void keyPressed(KeyEvent e) { l.setText("Key Pressed"); } public void keyReleased(KeyEvent e) { l.setText("Key Released"); } public void keyTyped(KeyEvent e) { l.setText("Key Typed"); } public static void main(String[] args) { new KeyListenerExample(); } } |
- How can you maintain session in servlet? Explain with example.
In such case, container creates a session id for each user. The container uses this id to identify the particular user. An object of HttpSession can be used to perform two tasks:
-
- bind objects
- view and manipulate information about a session, such as the session identifier, creation time, and last accessed time.
//index.html
<form action=”servlet1″>
Name:<input type=”text” name=”userName”/><br/>
<input type=”submit” value=”go”/>
</form>
//FirstServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class FirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); HttpSession session=request.getSession(); session.setAttribute("uname",n); out.print("<a href="servlet2">visit</a>"); out.close(); }catch(Exception e){System.out.println(e);} } } |
//SecondServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session=request.getSession(false); String n=(String)session.getAttribute("uname"); out.print("Hello "+n); out.close(); }catch(Exception e){System.out.println(e);} } } |
- Write a servlet program to find the prime number between 20 and 100.
123456789101112131415161718192021import java.io.*;import javax.servlet.*;import javax.servlet.http.*;class test extends HttpServlet{public void doGet (HttpServletResponse res, HttpServletRequest req) throws IOException{printWriter out = res.getWriter();int i, count, num = 20;while (num<= 100){i=2;count=0;while(i<=num/2){if(num%i ==0){count++;break;}i++;if(count == 0){out.println(num);}num++;}} - Write a swing program to insert data in table using prepared statement. (You can assume your own database, table, and number of field.
123456789101112131415import java.sql.*;class InsertPrepared{public static void main(String args[]){try{Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");stmt.setInt(1,101);//1 specifies the first parameter in the querystmt.setString(2,"Ratan");int i=stmt.executeUpdate();System.out.println(i+" records inserted");con.close();}catch(Exception e){ System.out.println(e);}}}
Group C
- How exception can be handled in JSP and forward to the “error.jsp”? Explain with suitable JSP script.
There are two ways of handling exceptions in JSP. They are:
-
- By errorPage and isErrorPage attributes of page directive.
- By <error-page> element in web.xml file.
//A.jsp
<% @page errorPage = “error.jsp” %>
< %
String num1 = request.getParameter(“first”);
String num2 = request.getParameter(“second”);
// extracting numbers from request
int x = Integer.parseInt(num1);
int y = Integer.parseInt(num2);
int z = x / y; // dividing the numbers
out.print(“division of numbers is: ” + z); // result
% >
//error.jsp
<% @page isErrorPage = “true” %>
<h1> Exception caught</ h1>
The exception is : <%= exception %>
- What are the advantages of JSP over servlet? Explain the use of web.xml with example.
There are many advantages of JSP over servlet. They are as follows:
- Extension to Servlet
JSP technology is the extension to servlet technology. We can use all the features of servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression language and Custom tags in JSP that makes JSP development easy.
- Easy to maintain
JSP can be easily managed because we can easily separate our business logic with presentation logic. In servlet technology, we mix our business logic with the presentation logic.
- Fast Development: No need to recompile and redeploy
If JSP page is modified, we don’t need to recompile and redeploy the project. The servlet code needs to be updated and recompiled if we have to change the look and feel of the application.
- Less code than Servlet
In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code. Moreover, we can use EL, implicit objects etc.
web.xml defines mappings between URL paths and the servlets that handle requests with those paths. The web server uses this configuration to identify the servlet to handle a given request and call the class method that corresponds to the request method. For example: the doGet() method for HTTP GET requests.
<servlet-mapping>
<servlet-name>redteam</servlet-name>
<url-pattern>/red/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>blueteam</servlet-name>
<url-pattern>/blue/*</url-pattern>
</servlet-mapping>
Morgan
Short Question
- What is applet? Write down its states.
Applet are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a web document.
States of Applets are as follow:
-
- New born State
- Running State
- Idle State
- End State
- List any four event classes.
Any four Event classes are as follow:
-
- ActionEvent
- KeyEvent
- MouseEvent
- TextEvent
- What is prepared Statement?
The prepared Statement interface extends the Statement interface which gives you added functionality with a couple of advantages over a generic statement object. This statement gives the flexibility of supplying arguments dynamically.
- What is session?
Session is way to identify a user across more than one page request or visit to a web site and to store information about the user.
- What is servlet?
A server side Java program that uses the above API is called as Servlet. In simple terms, a Servlet is a server side Java program that processes HTTP requests and generates HTTP response.
- What do you mean by Adapter class?
Java provides a special feature, called an adapter class,that can simplify the creation of event handlers in certain situations. An adapter class provides an empty implementation of all methods in an event listener interface.
- What is XML Schema?
XML Schema overcame all the limitations of DTD and had now become the standard for validating XML documents. The good thing about XML Schema is that it is closely associated with Object Oriented data models.
- What is web server?
Web server is a computer where the web content is stored. Basically web server is used to host the web sites but there exists other web servers also such as gaming, storage, FTP, email etc. Web server respond to the client request in either of the following two ways:
Sending the file to the client associated with the requested URL.
-
- Generating response by invoking a script and communicating with database
- How is JTable Created?
JTable is a component that displays rows and column of data. At its core, JTable is conceptually simple. It is a component that consists of one or more columns of information. JTable has following constructor.
JTable (Object [][] data, Object[] colHeads)
Here, data is a two- dimensional array of the information to be presented, and colHeads is a one dimensional array with the column size.
- Differentiate between AWT and Swing.
AWT |
Swing |
The components in AWT are heavyweight | The components in Swing are lightweight |
Associated with native components called peers | Same look and feel across platforms |
Same behavior, but platform dependent look | Supports pluggable and feel |
The package is java.awt | The package is javax.swing |
Group B
2. Write a swing program to compute sum, difference and product of two numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
import javax.swing.*; import java.awt.event.*; public class SwingDemo extends JFrame implements ActionListener{ JLabel l1,l2,l3; JTextField t1,t2,t3 ; JButton b1,b2,b3; SwingDemo(){ l1=new JLabel(“first number”); l2=new JLabel(“second number”); l3=new JLabel(“Result”); t1= new JTextField(10); t2 = new JTextField(10); t3=new JTextField(10); b1=new JButton(“Sum ”); b2=new JButton(“Difference”); b3=new JButton(“Product”); setLayout(new FlowLayout(FlowLayout.LEFT)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(200,200); setVisible(true); add(l1); add(t1); add(l2); add(t2); add(b1); add(b2); add(b3); b1.add ActionListener(this); b2.add ActionListener(this); b3.add ActionListener(this); } public void actionPerformed(ActionEvent e){ int a=Integer.ParseInt(t1.getText()); int b=Integer.ParseInt(t2.getText()); if(e.getsource()==b1){ int c=a+b; } if(e.getsource()==b2){ int c=a-b; } if(e.getsource()==b3){ int c=a*b; } t3.setText(string.valueof(c)); } public static void main(String[] args) { new SwingDemo(); } |
3.write an applet to check whether given word by user is of length 5 or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.awt.*; import java.applet.*; public class WordLength extends Applet { String word, temp; int n; public void start () { word = getParameter("input"); n = word.length (); if(n==5) temp = "The word is of length 5"; else temp = "The word is not of length 5"; } public void paint (Graphics g){ g.drawString (temp,20, 20); } } |
The HTML file for above applet is:
1 2 3 4 5 6 |
<html> <body> <applet code ="WordLength.class" width = "400" height = "500"> <param name = "input" value =" This is Applet"> </applet> </html> |
4.write a JSP program to compute sum of two numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<html> <head> <title>Form Processing</title> </head> <body> <font size = 3> <br> <center> Processing HTML Form <hr color = red size = 3> <% out.println(“Hello World”); int x = 10; int y = 20; int z = x+y; out.println(“sum = “+z); %> </center> </font> </body> </html> |
5. Write a program to set cookie in servlet.
Cookie.html file
1 2 3 4 5 6 7 |
<html> <body> <form action = Servlet” method = “POST”> Name:<input type=“text” name “uname”/><br> <input type =“submit” value=“go”/></form> </body> </html> |
Cookie.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Import java.io.*; Import javax.servlet.*; Import javax.servlet.http.*; public class SetServlet extends HttpServlet { Public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Response.setContentType(“text/html”); PrintWriter out = response.getWriter(); String n = request.getParameter(“uname”); Out.print(“Welcome”+n); Cookie ck = new Cookie(“name”,n); ck.setMaxAge(60*60*60*24); response.addCookie(ck); out.print(“form action = ‘ReadServlet’ method = “POST”>”); Out.print(“<input type = submit value = ‘go’>”); </form> out.close(); } } |
ReadServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.io.*; import javax.servlet.http.*;. public class ReadServlet extends HttpServlet { public void doPost(HttpServletRequest request , HttpServletResponse response) throws IOException, ServletException { response.setContentType(“text/html”); PrintWriter out = response.getWriter(); Cookie[] ck = request.getCookies(); If(ck!=null) out.print(“Hello”+ck[0].getValue()); out.close(); } } |
6. Write a program to read the employee(eid,name,address,salary) from file and display.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import java.sql.*; public class ConnectDB { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/Company"; public static void main(String[] args) { Connection conn = null; try{ Class.forName ("com.mysql.jdbc.Driver"); System.out.println ("Connecting to database...."); conn = DriverManager.getConnection(DB_URL,"root","mysql"); System.out.println("Creating statement..."); Statement stmt = conn.createStatement (); String sql = "select * from employee"; ResultSet rs = stmt.executeQuery (sql); while(rs.next()){ int eid = rs.getInt("eid"); float Salary = rs.getfloat("salary"); String name = rs.getString("name"); String address = rs.getString("address"); System.out.println("ID"+id); System.out.println("salary:"+salary); System.out.println("Name:"+name); System.out.println("Address:"+address); rs.close(); stmt.close(); conn.close(); } }catch(Exception e){ System.out.println("Connection failed"+e); } System.out.println("Good bye"); } |
Comprehensive Questions:
- Differentiate between FlowLayout and BorderLayout. Make user form with two textfield and two buttons.
FlowLayout: Flow layout manager is a default layout for applet and panel. A flow layout arranges components in a left to right, much like lines of text in a paragraph. Components are laid out from the upper left corner, left to right and top to down. When no more components fit on a line, the next one appears on next line.
BorderLayout: The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region may contain one component only. It is the default of frame or window. The four sides are referenced to as north, south, east and west. The middle area is called the center. North, south, east and west are narrow fixed width regions whereas center is large region.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import javax.swing.*; import java.awt.*; class SwingDemo { public static void main(String[] args) { JFrame f = new JFrame(); JTextField t1, t2; JLabel l1, l2; JButton b1, b2; l1 = new JLabel("First Name"); l2 = new JLabel("Last Name"); t1 = new JTextField(20); t2 = new JTextField(20); b1 = new JButton("Save"); b2 = new JButton("Close"); f.setLayout(new FlowLayout()); f.add(l1); f.add(t1); f.add(l2); f.add(t2); f.add(b1); f.add(b2); f.setSize(300,400); f.setVisible(true); } } |
- Write a servlet program to compute factorial of a given positive number.
Factorial.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<html> <head> <title> Factorial Example</title> </head> <body> <form method = “get” action = “FactorialServlet”> <table> <tr> <td>Enter value to find its factorial </td> <td><Input type = “text” name =”text1”/> </tr> <tr> <td></td> <td><Input type = “submit” value =”ok”/> </tr> </table> </form> </body> </html> |
FactorialServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.io.*; import java.servlet.*; public class FactorialServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType (“text/html”); PrintWriter out = response.getWriter (); int num = Integer.parseInt(request.getParameter(“text1”)); out.println (this.fact(num)); } long fact(long a) { If(a<=1) retrun 1; else return a*fact(a-1)); } } |
Hetauda
Brief Answers
- How can you pass parameter in applet?
-
- Parametersare passedto applets in NAME=VALUE pairs in <PARAM> tags between the opening and closing APPLET
- How can you create a dropdown list and multiple selection list in swing?
-
- Dropdown list.
123456public dropDown(){Object obj [] ={“a”,”b”,”c”};JComboBox c=new JCombox(obj);add(c);} - Multiple selection
- Dropdown list.
1 2 3 4 5 6 7 |
public MultipleSelection() { String color[]={“red”,”blue”,”green”}; JList list=new JList(color); list.setSelectionMode (ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); } |
- What are adapter classes in event handling?
- An adapter classprovides the default implementation of all methods in an event listener interface. Adapter classesare very useful when you want to process only few of the events that are handled by a particular event listener interface.
- What is Exception?
- Exception are the abnormal conditions that occur in your program during execution which terminates the program.
- Which class is used to browse and open file?
- JFileChooser() and showOpenDialog() class is used to browse and open a file.
- Which method are used to add mnemonic and shortcuts in menu?
- setMnemonic() method and setShortcut() methods are used to add mnemonicand shortcuts in menu.
- Define JDBC and ODBC.
- JDBCstands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the database.
- ODBC is an interface that allows applications to access data in database management systems (DBMS) using SQL as a standard for accessing the data.
- Why swing is called light-weight components?
- Swingcomponents depend less on the target platform and use less of the native GUI resource. Hence the Swingcomponents that don’t rely on native GUI are referred to as lightweight.
- What is inner class?
- Inner classmeans one classwhich is a member of another class.
- Write the steps to add icon in a label in swing.
- Create a Label say JLabel lbl.
- Then add the label to applet or Frame.
- Set lbl.setIcon(new ImageIcon(“images/copy.jpeg”)).
Short Answers
- Write a program which creates a menu (File->open, save, close) in frame.
12345678910111213141516171819202122import java.awt.*;public class MenuDemo extends Frame {MenuBar mnubar=new MenuBar();Menu mnu=new Menu("File");MenuItem mnuopen=new MenuItem("Open");MenuItem mnusave=new MenuItem("Save");MenuItem mnuexit=new MenuItem("Exit");public MenuDemo(){this.setMenuBar(mnubar);mnubar.add(mnu);mnu.add(mnuopen);mnu.add(mnusave);mnu.add(mnuexit);this.setSize(200,200);this.setVisible(true);}public static void main(String argp[]){new MenuDemo();}} - Explain the delegation event model with example.
- Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import java.awt.event.*; import javax.swing.*; public class Demo extends JFrame implements ActionListener{ JButton btnok=new JButton("Ok"); JButton btnclear=new JButton("Clear"); JTextField txt=new JTextField(10); JPanel pnl=new JPanel(); public Qno6() { add(pnl); pnl.add(txt); txt.setEditable(false); pnl.add(btnok); btnok.addActionListener(this); pnl.add(btnclear); btnclear.addActionListener(this); this.setSize(200,200); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("Ok")) { txt.setText("Welcome"); } else txt.setText(null); } public static void main(String arg[]) { new Demo(); } } |
- Create a frame which contains a swing table with some data.
123456789101112131415161718192021222324import java.awt.*;import javax.swing.*;public class SwingTable extends JFrame {Object row[][]= {{"ram",1},{"hari",2},{"shyam",3}};Object col[]= {"Name","roll"};JTable tbl=new JTable(row, col);JPanel pnl=new JPanel();public SwingTable(){add(pnl);pnl.add(tbl);JScrollPane js=new JScrollPane(tbl);this.add(js);this.setSize(200, 200);this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);this.setVisible(true);}public static void main(String arh[]){new SwingTable();}} - What do you understand by Request Dispatching? Explain with example.
- Request Dispatcheris an interface whose implementation defines an object which can dispatch the requestto any resources on the server. javax.servlet.RequestDispatcher interface is used to forward or include the response of a resource in a Servlet.
Example.
Index.html
1 2 3 4 5 |
<form action="servlet1" method="post"> Name:<input type="text" name="userName"/><br/> Password:<input type="password" name="userPass"/><br/> <input type="submit" value="login"/> </form> |
Login.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Login extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); String p=request.getParameter("userPass"); if(p.equals("servlet"){ RequestDispatcher rd=request.getRequestDispatcher("servlet2"); rd.forward(request, response); } else{ out.print("Sorry UserName or Password Error!"); RequestDispatcher rd=request.getRequestDispatcher("/index.html"); rd.include(request, response); } } } |
- Explain component and Container with example program.
- A componentis an object having a graphical representation that can be displayed on the screen and that can interact with the user. Examplesof components are the buttons, checkboxes, and scrollbars of a typical graphical user interface.
Example:
1 2 3 4 5 6 7 8 9 10 11 |
import java.applet.*; import java.awt.*; public class MyApplet extends Applet { Button btn; Label lbl; public void init() { add(lbl); add(btn); } } |
- A containeris a component which can contain other components inside itself
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.awt.*; public class Calculator extends Frame { private Label lblN1=new Label("N1:"); private TextField txt3=new TextField(5); private Panel pnl=new Panel(); private Button btn=new Button("Add"); public Calculator() { this.setTitle("Calculator"); this.add(pnl); pnl.add(lblN1); pnl.add(txt3); pnl.add(btn); this.setSize(200,200); this.setVisible(true); } public static void main(String arg[]) { Calculator cal=new Calculator(); } } |
- Create an Application using swing package which will search the student in the database and display the record in the respective fields. [Database schema is as- Student (Sid, sname, address)].
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475import java.awt.event.*;import java.sql.*;import javax.swing.*;public class StudentDemo extends JFrame implements ActionListener {JLabel lbl=new JLabel("SID");JLabel lblname=new JLabel("Name");JLabel lbladd=new JLabel("Address");JTextField txt=new JTextField(10);JTextField txtname=new JTextField(10);JTextField txtadd=new JTextField(10);JButton btn=new JButton("Search");JPanel pnl=new JPanel();public StudentDemo(){add(pnl);pnl.add(lbl);pnl.add(txt);pnl.add(lblname);pnl.add(txtname);pnl.add(lbladd);pnl.add(txtadd);pnl.add(btn);btn.addActionListener(this);this.setSize(200, 200);this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);this.setVisible(true);}public void actionPerformed(ActionEvent e) {Integer sid=null;try{sid=Integer.parseInt(txt.getText());}catch(NumberFormatException ex){System.out.println(ex.getMessage());}if(txt.getText()!=null){try{Class.forName("com.mysql.jdbc.Driver");Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost/student","root","");Statement stm=con.createStatement();String query="select * from student where sid='"+sid+"'";ResultSet result=stm.executeQuery(query);if(result.next()){txt.setText(result.getString(1));txtname.setText(result.getString(2));txtadd.setText(result.getString(3));}else{JOptionPane.showMessageDialog(this, "No data found");txt.setText(null);txtname.setText(null);txtadd.setText(null);}}catch(ClassNotFoundException ex){System.out,.println(ex.getMessage());}catch(SQLException ex){System.out,.println(ex.getMessage());}}}public static void main(String arg[]){new StudentDemo();}}
- Create a login form (web) and validate the user from database. Assume your own database parameters.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647<%@page import="java.sql.*"%><%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title></head><body><form action="#" method="post">Username:<input type="text" name="user"><input type="submit" value="submit" name="submit"></form><%if(request.getMethod().equals("POST")){if(request.getParameter("user")!=null){String s=request.getParameter("user");try{Class.forName("com.mysql.jdbc.Driver");Connection con=DriverManager.getConnection("jdbc:mysql://localhost/tests", "root", "");Statement stm=con.createStatement();String query="Select username from user where username='"+s+"'";ResultSet result=stm.executeQuery(query);if(result.next()){out.println("Welcome "+s);}else{out.println("Sorry no username found for "+s);}}catch(ClassNotFoundException e){out.println("Class not found:-"+e.getMessage());}catch(SQLException e){out.println("SQL Exception:-"+e.getMessage());}}}%></body></html>
- Create a Jsp simple calculator. The result should be processed by a servlet.
Calculator.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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>Insert title here</title> </head> <body> <form action="CalculatorDemo" method="post"> Number 1:<input type=text name="one"><br> Number 2:<input type=text name="two"><br> <input type="submit" value="Add" name="submit"> <input type="submit" value="Sub" name="submit"> <input type="submit" value="Mul" name="submit"> <input type="submit" value="Div" name="submit"> </form> </body> </html> |
CalculatorDemo.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import java.io.*; import javax.servlet.*; import javax.servlet.annotation.*; import javax.servlet.http.*; @WebServlet("/CalculatorDemo") public class CalculatorDemo extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) { } public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException { RequestDispatcher rd=request.getRequestDispatcher("Calculator.jsp"); rd.include(request, response); if(request.getParameter("submit")!=null) { Integer a=Integer.parseInt(request.getParameter("one")); Integer b=Integer.parseInt(request.getParameter("two")); if(request.getParameter("submit").equals("Add")) { response.getWriter().println(a+b); } else if(request.getParameter("submit").equals("Add")) { response.getWriter().println(a-b); } else if(request.getParameter("submit").equals("Add")) { response.getWriter().println(a*b); } else { response.getWriter().println((float)a/b); } } } } |
Orchid
Short Answer Qustions
- Write a statement to create a JTable.
JTable jt=new JTable(data,column);
- Mention the use of <jsp:getProperty>.
The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output.
<jsp:useBean id=”myName” … />
<jsp:getProperty name=”myName” property=”someProperty” …/>
- How is DTD different from XML schema?
XML schemas are written in XML while DTD are derived from SGML syntax. XML schemas define datatypes for elements and attributes while DTD doesn’t support datatypes. XML schemas allow support for namespaces while DTD does not.
- Which method is used to set the maximum inactive time interval for a session?
setMaxInactiveInterval
- List the two key features of swing.
– Swing components are lightweight.
– Swing supports pluggable look and feel. - How can you create a combo box in AWT?
By using constructor choice()
Choice c1=new Choice();
C1.add(“BIM”);
C1.add(“BBA”);
- How can you pass a parameter to a applet from HTML?
To pass the parameters to the Applet we need to use param attribute of <applet> tag. To retrieve a parameter’s value, we need to use getParameter() method ofApplet class.
- Mention any two uses of page directive in JSP.
– It is used to import the classes.
– It is used to set the content type. - What are the benefits of 3-tier architecture?
– Enhanced scalabilitydue to distributed deployment of application servers. Now,individual connections need not be made between client and server.
– Data Integrityis maintained. Since there is a middle layer between client and server, data corruption can be avoided/removed. - List two importance of XML.
XML stands for EXtensible Markup Language and it serves two purposes. XML is used to structure data so that it can be stored and transported. The tags provides structure to the data.
Short Answer Questions:
2.Write a program to insert 3 records into a table “book” having columns(id,name,author,publishor and price).Assume database name yourself.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.sql.*; public class InsertData{ public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/library"; String uname = "root"; String pwd = ""; try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(url, uname, pwd); String sql = "insert into book (id, name, author, publisher, price) values " + "(1, 'abc', 'bcd', 'efg', 200)," + "(2, 'abc', 'bcd', 'efg', 200)," + "(3, 'abc', 'bcd', 'efg', 200)"; Statement st = con.createStatement(); int rst = st.executeUpdate(sql); if(rst > 0) { System.out.println("Records inserted"); } con.close(); }catch(Exception ex) { System.out.println(ex); } } } |
3.Create a jsp that takes an integer from HTML and display its reverse.
reverse.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<html> <body> <% int num = Integer.parseInt(request.getParameter("number")); int rev = 0, rem; while(num > 0){ rem = num % 10; rev = rem + rev * 10; num = num / 10; } out.println("Reverse is: "+rev); %> </body> </html> |
—————————-
reverse.html
1 2 3 4 5 6 7 8 |
<html> <body> <form action = "reverse.jsp" method = "get"> Enter a number: <input type = "text" name = "number" /> <input type = "submit" /> </form> </body> </html> |
4.Create an applet to draw a circle and a rectangle filled with different colors.
1 2 3 4 5 6 7 8 9 10 |
import java.applet.*; import java.awt.*; public class DrawShape extends Applet { public void paint(Graphics g) { g.setColor(Color.red); g.fillRect(10, 10, 200, 100); g.setColor(Color.blue); g.fillOval(50, 50, 100, 100); } } |
5.Create a swing program with menu bar,menu and a menu item.When menu item is clicked,display “hello” in a message dialog.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MenuBarDemo implements ActionListener { JFrame f1; JMenuBar bar; JMenu m1; JMenuItem mi1; MenuBarDemo(){ f1 = new JFrame(); f1.setSize(300, 300); f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); bar = new JMenuBar(); m1 = new JMenu("File"); bar.add(m1); mi1 = new JMenuItem("OK"); m1.add(mi1); mi1.addActionListener(this); f1.setJMenuBar(bar); f1.setVisible(true); } public static void main(String[] args) { new MenuBarDemo(); } public void actionPerformed(ActionEvent e) { if(e.getSource() == mi1) { JOptionPane.showMessageDialog(null, "Hello"); } } } |
6.Create a servlet to read cookie from client and display the name and value associated with the cookie.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import javax.servlet.http.*; import java.io.*; public class ReadCookie extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html"); Cookie[]cookie = request.getCookies(); try { PrintWriter pw = response.getWriter(); pw.println("<html><body>"); pw.println("<h1>Cookie Info</h1>"); if(cookie != null) { for(int i = 0; i < cookie.length; i++) { pw.println("Cookie name: "+cookie[i].getName()); pw.println("Cookie value: "+cookie[i].getValue()); } } pw.println("</html></body>"); }catch(Exception ex) { System.out.println(ex); } } } |
Long Answer Questions:
8.What is a java bean?Explain.Write a program to use java bean in jsp.
A Java Bean is a java class that should follow following conventions:
-It should have a no-argument constructor.
-It should be Serializable.
-It should provide methods to set and get the values of the properties, known as getter and setter methods.
java_bean.jsp
1 2 3 4 5 6 7 8 9 10 11 |
<html> <body> <% <jsp:useBean id = "abc" class = "web.Person" /> <jsp:setProperty name = "abc" property = "name" value = "Ram" /> <jsp:setProperty name = "abc" property = "salary" value = "20000" /> <p>Name: <jsp:getProperty name = "abc" property = "name" /> </p> <p>Salary: <jsp:getProperty name = "abc" property = "salary" /> </p> %> </body> </html> |
————————————
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package web; import java.io.*; public class Person implements Serializable { private String name; private double salary; public Person() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } } |
SET A
Short Answer Questions:
- How can you prevent the user from resizing the frame at runtime?
setResizable(false);
- Mention the use of <jsp:setProperty> .
The setProperty action sets the properties of a Bean. The Bean must have been previously defined before this action.
<jsp:useBean id=”myName” … />
<jsp:setProperty name=”myName” property=”someProperty” …/>
- How can you store and retrieve the data stored in session?
Saving in Session
String username=request.getParameter(“txtusername”);
HttpSession session = request.getSession(true);
session.setAttribute(“username”, username);
Getting from Session
String username=(String) session.getAttribute(“username”);
- What are the advantages of 2-tier architecture?
- Easy to maintain and modification is bit easy.
- Communication is faster.
- Mention any four event classes.
- MouseEvent,
- KeyEvent
- ItemEvent
- WindowEvent
- What are the two ways of creating applet?
- By extending JApplet class.
- By extending Applet class.
- List two importance of XML.
- XML stands for EXtensible Markup Language and it serves two purposes. XML is used to structure data so that it can be stored and transported. The tags provides structure to the data.
- What are the parameters taken by doGet() or doPost() methods in a servlet?
- HTTPServletRequest request,HttpServletResponse response
- What is the role of adapter class in event handling?
- If a class extends an Adapter Class, we can override some methods which is needed; It can simplify the creation of the Event handlers in certain situations; It provides an empty implementation of all methods in an EventListener Methods.
- What is the use of DriverManager?
- The DriverManager provides a basic service for managing a set of JDBC drivers. As part of its initialization, the DriverManager class will attempt to load the driver classes referenced in the “jdbc.drivers” system property. This allows a user to customize the JDBC Drivers used by their applications.
Short Answer Questions
2.Create a swing program to add two numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class CalculatorDemo implements ActionListener{ JFrame f1; JLabel l1, l2, l3; JTextField t1, t2, t3; JButton b1; CalculatorDemo(){ f1 = new JFrame(); f1.setSize(300,300); f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f1.setLayout(new GridLayout(4, 2)); l1 = new JLabel("Num1"); l2 = new JLabel("Num2"); l3 = new JLabel("Result"); t1 = new JTextField(); t2 = new JTextField(); t3 = new JTextField(); b1 = new JButton("Add"); f1.add(l1); f1.add(t1); f1.add(l2); f1.add(t2); f1.add(l3); f1.add(t3); f1.add(b1); b1.addActionListener(this); f1.setVisible(true); } public static void main(String[] args) { new CalculatorDemo(); } public void actionPerformed(ActionEvent e) { int a = Integer.parseInt(t1.getText()); int b= Integer.parseInt(t2.getText()); int c = 0; if(e.getSource() == b1) { c = a + b; } t3.setText(c+""); } } |
3.Write a program to update price of book to 1200 whose name is “Head First Java” into a table “book”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.sql.*; public class UpdateData { public static void main(String [] args) { String url = "jdbc:mysql://localhost:3306/library"; String uname = "root"; String pwd = ""; try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(url, uname, pwd); String sql = "UPDATE book SET price = 1200 WHERE name = 'Head First Java'"; Statement st = con.createStatement(); int rst = st.executeUpdate(sql); if(rst > 0){ System.out.println("Record Updated"); } con.close(); } catch(Exception ex) { System.out.println(ex); } } } |
4.Create an applet to draw a circle and a rectangle filled with different colors.
1 2 3 4 5 6 7 8 9 10 |
import java.applet.*; import java.awt.*; public class DrawShape extends Applet { public void paint(Graphics g) { g.setColor(Color.red); g.fillRect(10, 10, 200, 100); g.setColor(Color.blue); g.fillOval(50, 50, 100, 100); } } |
5.Create a jsp to find the length of given string provided from HTML.
length.jsp
1 2 3 4 5 6 7 8 9 |
<html> <body> <% String str = request.getParameter("str"); int len = str.length(); out.println("Length is: "+len); %> </body> </html> |
—————————-
length.html
1 2 3 4 5 6 7 8 |
<html> <body> <form action = "length.jsp" method = "get"> Enter a Text: <input type = "text" name = "str" /> <input type = "submit" /> </form> </body> </html> |
6.Create a servlet to write cookie to user computer and store it for 24 hours.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import javax.servlet.http.*; import java.io.*; public class CookieDemo extends HttpServlet{ public void doGet(HttpServletRequest request,HttpServletResponse response){ response.setContentType("text/html"); try{ PrintWriter pw = response.getWriter(); Cookie cookie1 = new Cookie("FirstName", "abc"); cookie1.setMaxAge(24*60*60); response.addCookie(cookie1); pw.println("Hello user, cookie has been set to your computer"); pw.close(); }catch(Exception ex){ System.out.println(ex); } } } |
Long Answer Questions:
- What is a java bean?Explain.Write a program to use java bean in jsp.
A Java Bean is a java class that should follow following conventions:
-It should have a no-argument constructor.
-It should be Serializable.
-It should provide methods to set and get the values of the properties, known as getter and setter methods.
java_bean.jsp
1 2 3 4 5 6 7 8 9 10 11 |
<html> <body> <% <jsp:useBean id = "abc" class = "web.Person" /> <jsp:setProperty name = "abc" property = "name" value = "Ram" /> <jsp:setProperty name = "abc" property = "salary" value = "20000" /> <p>Name: <jsp:getProperty name = "abc" property = "name" /> </p> <p>Salary: <jsp:getProperty name = "abc" property = "salary" /> </p> %> </body> </html> |
————————————
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package web; import java.io.*; public class Person implements Serializable { private String name; private double salary; public Person() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } } |
IMS
Group A
- Define Adapter?
-
- An adaperclass provides the default implementation of all methods in an event listener interface. Adapter classes are very useful when you want to process only few of the events that are handled by a particular event listener interface.
- When will you use Result Set Class?
-
- It is used when it is required to retrieve numbers of rows that satisfies the condition of the query
- What is Swing Class?
-
- Swing class is used to create a graphical user interface.
- Define Applet?
-
- Applet are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a web document.
- When is ActionPerformed function defined?
-
- When event is called to ActionListener interface.
- How is database connection object created in java?
-
- Connection con= new Driver manager.getconnection( jdbc:mysql\\’localhost’\’root’, ‘ ’);
- Which package is used to make swing object?
-
- Import javax.swing.*; is used to make swing object.
- What is JFrame?
-
- Jframe is a container that provide the drag-and-drop features that help us in easily create graphical user-interface. JFrame has the option to hide or close the window with the help of setDefaultCloseOperation(int) method.
- What are the parameters taken by dopost ( ) methods of servlet?
-
- HttpServletRequest & HttpServletResponse
- What is JSP?
-
- Java Server Pages (JSP) is a Java standard technology that enables you to write dynamic, data-driven pages for your Java web applications. JSP is built on top of the Java Servlet specification.
Group B
- Make an user interface to take name and address of user?
1234567891011121314151617181920212223242526272829import java.awt.*;import java.awt.event.*;import javax.swing.*;class First extends JFrame implements ActionListener{JLabel name; JTextField jtf;JLable address; JTextField jtf2JButton btn;public First(){name = new JLable("Enter Name");jtf = new JTextField(10);address = new JLable("Enter Addres");jtf2 = new JTextField(10);btn = new JButton("Submit");add(name);add(jtf);add(address);add(jtf2);add(btn);setsize(400,400);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setLayout(new FlowLayout());setVisible(true);jb.setActionListener(this);}public void actionPerformed(ActionEvent ae){First f = new First() ;}} - Make a user interface to take name and address of user?
123456789101112131415161718192021222324252627282930313233import java.awt.*;import java.awt.event.*;import javax.swing.*;class Prime extends JFrame implements ActionListener{JLabel jLb1;JTextField jtf;JButton jbt;public Prime(){jLb1 = new JLabel("Enter Numner");jtf = new JTextField(10);jbtn = new JButton("Check");add(jLb1);add(jtf);add(jbtn);setsize(200,200);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setLayout(new FlowLayout());setVisible(true);jbtn.setActionListener(this);}public void actionPerformed(ActionEvent ae){int a = Integer.parseInt(jtf.getText());int m = 0;flag = 0;for (int i=1; i<=a; i++) {if (a%i==0) {System.out.println("Prime");}else{System.out.println("Not Prime");}}}} - Make an applet to display name of your college?
12345678import java.applet.Applet;import java.awt.Graphics;public class College extends Applet{public void paint (Graphics g){g.drawString ("IMS College",20,150);}}/*<applet code = "College.class" width="200" height="200"></applet>*/ - Write a jsp program to display multiplication table to 2 (from 1 To 10).
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586<html><head><title>JSP Program</title></head><body><form action="tb_disp.jsp" method="post"><table align="center"><tr><th>Multiplication Table</th></tr><tr><td>Enter no. of rows</td><td><input type="number" name="rows"></td></tr><tr><td>Enter no. of colums </td><td><input type="number" name="cols"></td></tr><tr><td><input type="submit"></td></tr></table></form></body></html><% page import = "java.util.Random"%><%page content Type = "text/html"%><html><head><title>Multiplication Table</title></head><body><%Random r = new Random();int n.row=0, cols=0, inc2;row= Integer.parse.Int(request.getParameter("row"));col= Integer.parse.Int(request.getParameter("cols"));%><table border="2" cellpadding="7" align="center"><thead><center>Multiplication Table</center></thead><tr><%String str;for(inc1=1; inc1<=row; inc1++){n=r.nextInt(0.Xfffff);str=Integer.toHexString(n);%><td align="center"><font size="5"><%Out.print(inc1);%></font></td><%}%></tr><%for(inc1=1; inc1<=col; inc1++)%><tr><%String str;for(inc2=1; inc2<=row; inc2++){n=r.nextInt(0.Xfffff);str=Integer.toHexString(n);%><td><font size="5"><%Out.print(inc1+"*"+inc2+"="+(inc1*inc2));%></font></td><%}%></tr><%}%><tr> </tr></table></body></html>
Group C
- Differentiate between JSP and Servlet?
Servlet |
JSP |
A servlet is a server-side program and written purely on Java. | JSP is an interface on top of Servlets. In another way, we can say that JSPs are extension of servlets to minimize the effort of developers to write User Interfaces using Java programming. |
Servlets run faster than JSP | JSP runs slower because it has the transition phase for converting from JSP page to a Servlet file. Once it is converted to a Servlet then it will start the compilation |
Executes inside a Web server, such as Tomcat | A JSP program is compiled into a Java servlet before execution. Once it is compiled into a servlet, it’s life cycle will be same as of servlet. But, JSP has it’s own API for the lifecycle. |
Receives HTTP requests from users and provides HTTP responses | Easier to write than servlets as it is similar to HTML. |
We can not build any custom tags | One of the key advantage is we can build custom tags using JSP API (there is a separate package available for writing the custom tags) which can be available as the re-usable components with lot of flexibility |
Servlet has the life cycle methods init(), service() and destroy() | JSP has the life cycle methods of jspInit(), _jspService() and jspDestroy() |
Written in Java, with a few additional APIs specific to this kind of processing. Since it is written in Java, it follows all the Object Oriented programming techniques. | JSPs can make use of the Javabeans inside the web pages |
- Explain layout manager?
-
- The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is implemented by all the classes of layout managers. There are following classes that represents the layout managers:
- java.awt.BorderLayout
- java.awt.FlowLayout
- java.awt.GridLayout
- java.awt.CardLayout
- java.awt.GridBagLayout
- javax.swing.BoxLayout
- javax.swing.GroupLayout
- javax.swing.ScrollPaneLayout
- javax.swing.SpringLayout, etc.
BorderLayout
Every content pane is initialized to use a BorderLayout. (As Using Top-Level Containers explains, the content pane is the main container in all frames, applets, and dialogs.) A BorderLayoutplaces components in up to five areas: top, bottom, left, right, and center. All extra space is placed in the center area. Tool bars that are created using JToolBar must be created within a BorderLayout container, if you want to be able to drag and drop the bars away from their starting positions
CardLayout
The CardLayout class lets you implement an area that contains different components at different times. A CardLayout is often controlled by a combo box, with the state of the combo box determining which panel (group of components) the CardLayout displays. An alternative to using CardLayout is using a tabbed pane, which provides similar functionality but with a pre-defined GUI.
FlowLayout
FlowLayout is the default layout manager for every JPanel. It simply lays out components in a single row, starting a new row if its container is not sufficiently wide. Both panels in CardLayoutDemo, shown previously, use FlowLayout.
NCCS
Set B
Q.N. 2
Fact.html
1 2 3 4 5 6 7 8 9 10 11 |
<html> <head> <title>Factorial number</title> </head> <body> <form method="post" action="Fact"> Enter a number:<input type="number" name="num1"><br/> <input type="submit" value="Calculate"> </form> </body> </html> |
Fact.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package ServletLab; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Fact extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); int n1=Integer.parseInt(req.getParameter("num1")); out.println("<html>"); out.println("<head>"); out.println("</head>"); out.println("<body>"); int f=1; for(int i=1;i<=n1;i++){ f*=i; } out.println("Factorial is "+f); out.println("</body>"); out.println("</html>"); } } |
Q.N. 3
Q3.html
1 2 3 4 5 6 7 8 9 10 11 12 |
<html> <head> <title>Q3</title> </head> <body> <form method="post" action="Q3"> Name:: <input type="number" name="name"><br/> Age:: <input type="number" name="age"><br/> <input type="submit" value="submit"> </form> </body> </html> |
Q3.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package ServletLab; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Q5 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); response.setContentType("text/html"); String name = request.getParameter("name"); String age = request.getParameter("age"); session.setAttribute("name", name); session.setAttribute("age", age); PrintWriter out = response.getWriter(); out.println(“Name:: “ + session.getAttribute(name)); out.println(“Age:: “ + session.getAttribute(age)); } } |
Web.xml
1 2 3 4 5 6 7 8 |
<servlet> <servlet-name>Q3</servlet-name> <servlet-class>Servlet25.Q3</servlet-class> </servlet> <servlet-mapping> <servlet-name>Q3</servlet-name> <url-pattern>/Q3</url-pattern> </servlet-mapping> |
Q.N. 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package NCCS_pre; import java.applet.Applet; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; /* <applet code="Q4" width=300 height=300> </applet> */ public class Q4 extends Applet{ TextField t1,t2; Button add,div; Label l1,l2; public void init(){ l1=new Label("Num1"); l2=new Label("Num2"); t1=new TextField(10); t2=new TextField(10); add=new Button("Add"); div=new Button("Divide"); setLayout(new GridLayout(4,2)); add(l1); add(t1); add(l2); add(t2); add(add); add(div); setSize(120,80); setVisible(true); add.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int num1=Integer.parseInt(t1.getText()); int num2=Integer.parseInt(t2.getText()); int sum=num1+num2; showStatus(""+sum); } }); div.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { double num1=Double.parseDouble(t1.getText()); double num2=Double.parseDouble(t2.getText()); double d=num1/num2; showStatus(""+d); } }); } } |
Q.N. 6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package NCCS_pre; import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class KeyEventDemo extends JFrame implements KeyListener{ JTextField t,t2; JPanel p,p1; KeyEventDemo(){ t2=new JTextField(10); t=new JTextField(10); p=new JPanel(); p1=new JPanel(); p.add(t2); p1.add(t); add(p,BorderLayout.SOUTH); add(p1,BorderLayout.NORTH); t.addKeyListener(this); setSize(400,300); setVisible(true); } public void keyPressed(KeyEvent e){ t2.setText(t.getText()); } public void keyTyped(KeyEvent e){ } public void keyReleased(KeyEvent e){ } public static void main(String[] args) { new KeyEventDemo(); } } |
Q.N. 7
Q7.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<!DOCTYPE html> <html> <head> <title>Q7</title></head> <body> <form method="post" action="Q7.jsp"> FirstName : <input type="text" name="fname"/><br/> LastName: <input type="text" name="lname"/><br/> Age : <input type="text" name="age"/><br/> Address : <input type="text" name="add"/><br/> <input type="submit" value="Submit" name="submit"/> </form> </body> </html> <%@page session="true" %> <% if (request.getParameter("submit") != null) { String firstName = request.getParameter("fname"); String lastName = request.getParameter("lname"); String age = request.getParameter("age"); String add = request.getParameter("add"); %> <jsp:useBean id="bean" class="bean.Customer" scope="session"/> <jsp:setProperty name="bean" property="firstname" value="<%= firstName %>"/> <jsp:setProperty name="bean" property="lastname" value="<%= lastName %>"/> <jsp:setProperty name="bean" property="age" value="<%=age%>"/> <jsp:setProperty name="bean" property="address" value="<%=add%>"/> <% response.sendRedirect("Q7disp.jsp"); } %> |
Q7disp.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<%@page session="true" %> <jsp:useBean id="bean" class="bean.Customer" scope="session"/> <!DOCTYPE html> <html> <head> <title>JSP Page</title> </head> <body> FirstName : <jsp:getProperty name="bean" property="fname"/><br/> LastName : <jsp:getProperty name="bean" property="lname"/><br/> Age : <jsp:getProperty name="bean" property="age"/><br/> Address : <jsp:getProperty name="bean" property="add"/><br/> </body> </html> |
Q7.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package bean; public class Q7 { String firstname,lastname,address,age; public String getfirstname(){ return firstname; } public String getlastname(){ return lastname; } public String getage(){ return age; } public String getAddress(){ return address; } public void setfirstname (String firstname){ this.firstname = firstname; } public void setlastname (String lastname){ this.lastname = lastname; } public void setaget(String age){ this.age = age; } public void setAddress(String address){ this.address = address; } } |
Q.N. 8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package LabSheet; import java.sql.*; public class Q8 { public static void main(String [] args) throws Exception{ Connect(); } public static Connect() throws Exception{ Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/college "; Connection con=DriverManager.getConnection(url,"root",""); Statement stmt=con.createStatement(); int res=stmt.executeUpdate(sql); if(res!=-1){ String sql=”UPDATE Teacher SET address=’Dharan’ WHERE t_id=5”; int res=stmt.executeUpdate(sql); System.out.println("Update succesfully"); }else{ System.out.println("couldn't inserted. Please check ur SQL Syntax"); } } } } |
Set A
Q.N. 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
package NCCS_pre; import java.awt.*; import java.awt.event.*; public class MouseEventDemo extends Frame implements MouseListener { int x = 0, y = 0; String strEvent = ""; MouseEventDemo(String title) { super(title); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); addMouseListener(this); setSize(300, 300); setVisible(true); } public void mouseClicked(MouseEvent e) { strEvent = "MouseClicked"; x = e.getX(); y = e.getY(); repaint(); } public void mousePressed(MouseEvent e) { strEvent = "MousePressed"; x = e.getX(); y = e.getY(); repaint(); } public void mouseReleased(MouseEvent e) { strEvent = "MouseReleased"; x = e.getX(); y = e.getY(); repaint(); } public void mouseEntered(MouseEvent e) { strEvent = "MouseEntered"; x = e.getX(); y = e.getY(); repaint(); } public void mouseExited(MouseEvent e) { strEvent = "MouseExited"; x = e.getX(); y = e.getY(); repaint(); } public void paint(Graphics g) { g.drawString(strEvent + " at " + x + "," + y, 50, 50); } public static void main(String[] args) { new MouseEventDemo("Window With Mouse Events Example"); } } |
Q.N. 3
1 2 3 4 5 6 7 8 9 10 11 |
<html> <head> <title>Prime number</title> </head> <body> <form method="post" action="Prime"> Enter a number:<input type="number" name="num1"><br/> <input type="submit" value="check"> </form> </body> </html> |
Prime.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package ServletLab; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Fact extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); int n1=Integer.parseInt(req.getParameter("num1")); int f=1; for(int i=2;i<n1/2;i++){ if(n1%==0){ f=0; break; } } if(f==1) out.println(n1+” is prime”); else out.println(n1+” is not prime”); } } |
Q.N. 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
package NCCS_pre; import java.applet.Applet; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; /* <applet code="Q4" width=300 height=300> </applet> */ public class Q4 extends Applet{ TextField t1,t2; Button check; Label l1,l2; public void init(){ l1=new Label("Num1"); l2=new Label("Num2"); t1=new TextField(10); t2=new TextField(10); check=new Button("Check"); setLayout(new GridLayout(3,2)); add(l1); add(t1); add(l2); add(t2); add(check); setSize(120,80); setVisible(true); check.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int small; int num1=Integer.parseInt(t1.getText()); int num2=Integer.parseInt(t2.getText()); if(num1<num2) small=num1; else small=num2; showStatus(""+small); } }); } } |
Q.N. 6
Q6.html
1 2 3 4 5 6 7 8 9 10 11 12 |
<html> <head> <title>Q6</title> </head> <body> <form method="post" action="Q6"> Num1:: <input type="number" name="n1"><br/> Num2:: <input type="number" name="n2"><br/> <input type="submit" value="submit"> </form> </body> </html> |
Q6.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package ServletLab; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Q5 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); int num1,num2,add,sub,mul; num1=Integer.parseInt(req.getParameter(“n1”)); num2=Integer.parseInt(req.getParameter(“n2”)); add=num1+num2; sub=num1-num2; mul=num1*num2; out.println(“Sum is “+add); out.println(“Sum is “+sub); out.println(“Sum is “+mul); } } |
Web.xml
1 2 3 4 5 6 7 8 |
<servlet> <servlet-name>Q6</servlet-name> <servlet-class>Servlet25.Q6</servlet-class> </servlet> <servlet-mapping> <servlet-name>Q6</servlet-name> <url-pattern>/Q6</url-pattern> </servlet-mapping> |
Q.N. 7
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<!DOCTYPE html> <html> <head> <title>Q7</title> </head> <body> <form method="post" action="Q7.jsp"> Name : <input type="text" name="name"/><br/> Address : <input type="text" name="add"/><br/> Age : <input type="text" name="age"/><br/> Program : <input type="text" name="pro"/><br/> <input type="submit" value="Submit" name="submit"/> </form> </body> </html> <%@page session="true" %> <% if (request.getParameter("submit") != null) { String name = request.getParameter("name"); String add = request.getParameter("add"); String age = request.getParameter("age"); String program = request.getParameter("pro"); %> <jsp:useBean id="bean" class="bean.Customer" scope="session"/> <jsp:setProperty name="bean" property="name" value="<%= name %>"/> <jsp:setProperty name="bean" property="address" value="<%=add%>"/> <jsp:setProperty name="bean" property="age" value="<%=age%>"/> <jsp:setProperty name="bean" property="program" value="<%= pro %>"/> <% response.sendRedirect("Q7disp.jsp"); } %> |
Q7disp.jsp
1 2 3 4 5 6 7 8 9 10 11 12 |
<%@page session="true" %> <jsp:useBean id="bean" class="bean.Customer" scope="session"/> <!DOCTYPE html> <html> <head> <title>JSP Page</title> </head> <body> Name : <jsp:getProperty name="bean" property="name"/><br/> Address : <jsp:getProperty name="bean" property="add"/><br/> Age : <jsp:getProperty name="bean" property="age"/><br/> Program : <jsp:getProperty name="bean" property="program"/><br/> </body> </html> |
Q7.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package bean; public class Q7 { String name,address,age,program; public String getname(){ return name; } public String getAddress(){ return address; } public String getage(){ return age; } public String getprogram(){ return program; } public void setname (String name){ this.name = name; } public void setAddress(String address){ this.address = address; } public void setaget(String age){ this.age = age; } public void setprogram (String program){ this.program= program; } } |
Q.N. 8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package LabSheet; import java.sql.*; public class Q8 { public static void main(String [] args) throws Exception{ Connect(); } public static Connect() throws Exception{ Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/hospital "; Connection con=DriverManager.getConnection(url,"root",""); String sql="INSERT INTO patient VALUES(1,’Ram’,’kathmandu’,’Male’); if(con!=null){ Statement stmt=con.createStatement(); int res=stmt.executeUpdate(sql); String sql=”UPDATE patitent SET address=’Pokhara’ WHERE id=1”; int res=stmt.executeUpdate(sql); System.out.println("Update succesfully"); Stmt.close(); }else{ System.out.println("couldn't inserted. Please check ur SQL Syntax"); } } } } |
KIST
Set B
Group A
1) How a session can be enable and disable in jsp page?
- Session can be enable as <% @page session=”true” %> and disable as <% @page session=”false” %>
2) What do you mean by delegation model?
- The Delegation Event model is one of the many techniques used to handle events in GUI (Graphical User Interface) programming languages. GUI represents a system where a user visually/graphically interacts with the system.
3) List any 5 event class.
- Five event classes are as following:
-
- Mouse event
- Key event
- Text event
-
- Window event
- Item event
4) How can you store and retrieve the data in a session?
- Set() and get() method help in data store and retrieve in a session.
5) What is the use of <jsp:getproperty> ?
- The< jsp:setProperty> action tag returns the value of the property.
7) What do you mean by deployment descriptor file?
- A deployment descriptor (DD) refers to a configuration file for an artifact that is deployed to some container/engine .In the Java Platform, Enterprise Edition, a deployment descriptor describes how a component, module or application (such as a web application or enterprise application) should be deployed.
8) How can you create a jDialog in java?
- JDialog can create as showMessageDialog (frame, “Eggs are not supposed to be green.”);
9) What is adapter class?
- An adapter class provides the default implementation of all methods in an event listener interface. Adapter classes are very useful when you want to process only few of the events that are handled by a particular event listener interface.
10) What is xml schema?
- XML Schema is commonly known as XML Schema Definition (XSD). It is used to describe and validate the structure and the content of XML data.
Group B
2) Write a swing program to add two numbers given by user as input.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.awt.*; import javax.swing.*; import javax.swing.event.*; import java.awt.event.*; public class T2016_2 extends JFrame implements ActionListener{ JTextField t1,t2; JLabel sum; JButton b; public T2016_2(){ t1=new JTextField(); t2=new JTextField(); sum=new JLabel(""); b=new JButton("Add"); setLayout(new GridLayout(4,1)); add(t1); add(t2); add(b); add(sum); setSize(200,400); setVisible(true); b.addActionListener (this); } public void actionPerformed(ActionEvent e){ int n1=Integer.parseInt(t1.getText()); int n2=Integer.parseInt(t2.getText()); int s=n1+n2; sum.setText("Sum is: "+s); } public static void main(String[] args) { new T2016_2(); } } |
3) Write a program to display record from user_table that contains (id, username, password and role) inside a database kist_db.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.sql.*; public class Db{ public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/ kist_db "; String uname = "root"; String pwd = ""; try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(url, uname, pwd); String sql = "select * from employee"; Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql); while(rs.next()) { System.out.println(rs.getString("id")); System.out.println(rs.getString("username")); System.out.println(rs.getString("password")); System.out.println(rs.getString("role")); } }catch(Exception ex) { System.out.println(ex); } } } |
4) Write a jsp to display “Hello from jsp” 10 times.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<html> <head> <title> </title> </head> <body> <% String i=" Hello from jsp"; For( i=1; i<=10; i++){ %> <%i = %> <% } %> </body> </html> |
5) Write a servlet to find the factorial of a positive values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import javax.servlet.http.*; import java.io.*; public class Ques3_2018 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html"); int num = Integer.parseInt(request.getParameter("number")); int fact = 1; while(num > 0) { for(int i = 1; i <= num; i++) { fact = fact * i; } } try { PrintWriter pw = response.getWriter(); pw.println("<html><body>"); pw.println("<h1>Factorial of "+num+ " is "+fact+"</h1>"); pw.println("</html></body>"); }catch(Exception ex) { System.out.println(ex); } } } |
<!DOCTYPE html>
<html>
<head>
<meta charset=”ISO-8859-1″>
<title>Insert title here</title>
</head>
<body>
<form action = “ques2_2018” method = “get”>
<label>Enter a Number:</label>
<input type = “text” name = “number”/>
<input type = “submit” value = “Submit”/>
</form>
</body>
</html>
6) Create an applet that contain three text field and two buttons (add and subtract). Perform add and subtract.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class Ap extends Applet{ int a, b; public void start () { string b= getparameter("b"); string a= getparameter("a"); try{ if(a!= null && b!=null){ a= Integer.parseInt("a"); b= Integer.parseInt("b"); int sub=a-b; int sum=a+b; }catch(Exception e){ System.out.println(e); System.out.println("sum" +sum); System.out.println("sub" +sub); } } <applet code="add.Applet"> <para name="a" value="50"> <para name="b" value="60"> </applet> |
Group ‘c’
7)What layout manager? Explain border layout and grid bag layout.
- The Layout Managers are used to arrange components in a particular manner. Layout Manager is an interface that is implemented by all the classes of layout managers.
- Grid bag layout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle.
Example:
12345678910111213141516171819202122232425import java.awt.*;import javax.swing.*;zpublic class MyGridLayout{Jframe f;MyGridLayout(){f=new JFrame();Jbutton b1=new JButton("1");Jbutton b2=new Jbutton("2");Jbutton b3=new JButton("3");Jbutton b4=new JButton("4");Jbutton b5=new JButton("5");Jbutton b6=new JButton("6");Jbutton b7=new JButton("7");Jbutton b8=new JButton("8");Jbutton b9=new JButton("9");f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);f.add(b6);f.add(b7);f.add(b8);f.add(b9);f.setLayout(new GridLayout(3,3));f.setSize(300,300);f.setVisible(true);}public static void main(String[] args) {new MyGridLayout();}} - Border layout
- Grid bag layout
The Border Layout is used to arrange the components in five regions: north, south, east, west and center. Each region (area) may contain one component only.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.awt.*; import javax.swing.*; public class Border { JFrame f; Border(){ f=new JFrame(); JButton b1=new JButton("NORTH");; JButton b2=new JButton("SOUTH");; JButton b3=new JButton("EAST");; JButton b4=new JButton("WEST");; JButton b5=new JButton("CENTER"); f.add(b1,BorderLayout.NORTH); f.add(b2,BorderLayout.SOUTH); f.add(b3,BorderLayout.EAST); f.add(b4,BorderLayout.WEST); f.add(b5,BorderLayout.CENTER); f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new Border(); } } |
8) What do you understand by event delegation model? How swing support look and feel ?
- Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.
The Delegation Event Model has the following key participants namely:
- Source– The source is an object on which event occurs. Source is responsible for providing information of the occurred event to it’s handler. Java provide as with classes for source object.
- Listener– It is also known as event handler. Listener is responsible for generating response to an event. From java implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is received, the listener process the event an then returns.
“Look” refers to the appearance of GUI widgets and “feel” refers to the way the widgets behave.
Sun’s JRE provides the following L&Fs:
- CrossPlatformLookAndFeel:this is the “Java L&F” also known as “Metal” that looks the same on all platforms. It is part of the Java API (javax.swing.plaf.metal) and is the default.
- SystemLookAndFeel:here, the application uses the L&F that is default to the system it is running on. The System L&F is determined at runtime, where the application asks the system to return the name of the appropriate L&F.
For Linux and Solaris, the System L&Fs are “GTK+” if GTK+ 2.2 or later is installed, “Motif” otherwise. For Windows, the System L&F is “Windows”. - Synth:the basis for creating your own look and feel with an XML file.
- Multiplexing:a way to have the UI methods delegate to a number of different look and feel implementations at the same time.
For example:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.UIManager;import javax.swing.JFrame;class Awt implements ActionListener {JFrame f;JButton addbut, subbut, mulbut, divbut, b5;JTextField t1, t2, t3;JLabel l, l1;Awt(){f = new JFrame("Cross Platform Look and Feel");t1 = new JTextField(" ");t2 = new JTextField(" ");t3 = new JTextField(" ");addbut = new JButton("Add");subbut = new JButton("Sub");mulbut = new JButton("Mul");divbut = new JButton("Div");l = new JLabel();l1 = new JLabel();}public void awt1(){f.setLayout(new GridLayout(3, 2));f.setVisible(true);f.add(t1);f.add(t2);f.add(t3);f.add(addbut);f.add(subbut);f.add(mulbut);f.add(divbut);f.add(l);f.add(l1);addbut.addActionListener(this);subbut.addActionListener(this);mulbut.addActionListener(this);divbut.addActionListener(this);f.pack();}public void actionPerformed(ActionEvent e){String s = new String(e.getActionCommand());l.setText(s);if ((s).equals("Add")) {int a = Integer.parseInt(t1.getText());int b = Integer.parseInt(t2.getText());Integer c = a + b;t3.setText(c.toString());}else if ((s).equals("Sub")) {int a = Integer.parseInt(t1.getText());int b = Integer.parseInt(t2.getText());Integer c = a - b;t3.setText(c.toString());}else if ((s).equals("Mul")) {int a = Integer.parseInt(t1.getText());int b = Integer.parseInt(t2.getText());Integer c = a * b;t3.setText(c.toString());}}public static void main(String args[]){try {UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());}catch (Exception e) {System.out.println("Look and Feel not set");}Awt a = new Awt();a.awt1();}}
SET-A
- Which method is used to create session in java?
public HttpSession getSession()
public HttpSession getSession(boolean create)
- What is prepared Statement?
A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency. Also it is a sub interface of Statement. It is used to execute parameterized query. - What is the use of ResultSet?
java.sql.ResultSet also an interface and is used to retrieve SQL select query results. A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set. - List any 3 disadvantages of 3-tier architecture.
– To implement even small part of application it will consume lots of time.
– Need good expertise in object oriented concept (classes and objects).
– It is more complex to build. - What is component?
A component is an object having a graphical representation that can be displayed on the screen and that can interact with the user. Examples of components are the buttons, checkboxes, and scrollbars of a typical graphical user interface. - What is cookie?
A cookie is a small piece of information that is persisted between the multiple client requests. 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. - How is radio button created in AWT?
In java.awt we are not having a special class for radio buttons but we can create radio button from Checkbox class. java.awt we have a predefined class called CheckboxGroup through which we can add all the checkboxes to the object of CheckboxGroup class.
1234567Checkbox cb1, cb2, cb3, cb4;CheckboxGroup cbg1=new CheckboxGroup();CheckboxGroup cbg2=new CheckboxGroup();cb1=new Checkbox ("C", cbg1, false);cb2=new Checkbox ("Cpp", cbg1, false);cb3=new Checkbox ("Java", cbg2, false);cb4=new Checkbox ("Oracle9i", cbg2, false);
In java.awt we are not having a special class for radio buttons but we can create radio button from Checkbox class. java.awt we have a predefined class called CheckboxGroup through which we can add all the checkboxes to the object of CheckboxGroup class.
1234567Checkbox cb1, cb2, cb3, cb4;CheckboxGroup cbg1=new CheckboxGroup();CheckboxGroup cbg2=new CheckboxGroup();cb1=new Checkbox ("C", cbg1, false);cb2=new Checkbox ("Cpp", cbg1, false);cb3=new Checkbox ("Java", cbg2, false);cb4=new Checkbox ("Oracle9i", cbg2, false); - What is Document Type Definition(DTD)?
The XML Document Type Declaration, commonly known as DTD, is a way to describe XML language precisely. DTDs check vocabulary and validity of the structure of XML documents against grammatical rules of appropriate XML language.
- What is web server?
It is a computer where the web content can be stored. In general web server can be used to host the web sites but there also used some other web servers also such as FTP, email, storage, gaming etc. - What is the use of MouseListener interface?
The MouseListener interface is used to track the preceding events of the mouse on the area occupied by the graphical component. The Java MouseListener is notified whenever you change the state of mouse. It is notified against MouseEvent.
5 Methods of MouseListener interface are:
- publicabstract void mouseClicked(MouseEvent e);
- publicabstract void mouseEntered(MouseEvent e);
- publicabstract void mouseExited(MouseEvent e);
- publicabstract void mousePressed(MouseEvent e);
- publicabstract void mouseReleased(MouseEvent e);
Group B
- Write a swing program in which user can select one of the option and display that selected option.
12345678910111213141516171819202122232425262728import java.awt.*;import java.awt.event.*;import javax.swing.*;/*<applet code="JAppletDemo.class" width=200 height=200></applet>*/public class JAppletDemo extends JApplet{public void init(){setLayout(new FlowLayout());JButton b1=new JButton("Alpha");JButton b2=new JButton("Beta");JLabel label=new JLabel("Press a button");b1.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {label.setText("You have pressed Alpha");}});b2.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {label.setText("You have pressed Beta");}});add(b1);add(b2);add(label);}}
3) Write a program to set cookie.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import javax.servlet.http.*; import java.io.*; public class Ques extends HttpServlet{ public void doGet(HttpServletRequest request,HttpServletResponse response){ response.setContentType("text/html"); try{ PrintWriter pw = response.getWriter(); Cookie cookie1 = new Cookie("FirstName", "abc"); Cookie cookie2 = new Cookie("LastName", "bcd"); cookie1.setMaxAge(24*60*60); cookie2.setMaxAge(24*60*60); response.addCookie(cookie1); response.addCookie(cookie2); pw.println("Hello user cookie has been set to your computer"); pw.close(); }catch(Exception e){ System.out.println(ex); } } } |
4) Create jsp page to display all the odd numbers between 10 and 50.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<html> <head> <title></title> </head> <body> <% for(int i=10; i<=50; i++){ %> if(i%2!=0){ (%i = %) } <% } %> </body> </html> |
5) Create applet having <para> tag.
1 2 3 |
<applet code ="abc.applet" width="100px" height="100px"> <para name="a" value="10"> <para name="b" value="20"> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Ap extends Applet{ int a, b; public void start () { string b= getparameter("b"); string a= getparameter("a"); try{ if(a!= null && b!=null){ a= Integer.parseInt("a"); b= Integer.parseInt("b"); int sub=a-b; int sum=a+b; }catch(Exception e){ System.out.println(e); System.out.println("sum" +sum); System.out.println("sub" +sub); } } |
Group C
7) Describe any two layout.
1) Flow layout: The Flow Layout is used to arrange the components in a line, one after another (in a -flow). Flow Layout is used to arrange the components in a line, one after another (in a flow). It is the default layout of applet or panel.
2) Box layout:The Box Layout is used to arrange the components either vertically or horizontally. For this purpose, Box Layout provides four constants.
8) Difference between JSP and servlet. Explain the use of web.xml with an example.
SERVLET | JSP |
A servlet is a server-side program and written purely on Java. | JSP is an interface on top of Servlets. In another way, we can say that JSPs are extension of servlets to minimize the effort of developers to write User Interfaces using Java programming. |
Servlets run faster than JSP | JSP runs slower because it has the transition phase for converting from JSP page to a Servlet file. Once it is converted to a Servlet then it will start the compilation |
Executes inside a Web server, such as Tomcat | A JSP program is compiled into a Java servlet before execution. Once it is compiled into a servlet, it’s life cycle will be same as of servlet. But, JSP has it’s own API for the lifecycle. |
Receives HTTP requests from users and provides HTTP responses | Easier to write than servlets as it is similar to HTML. |
We can not build any custom tags | One of the key advantage is we can build custom tags using JSP API (there is a separate package available for writing the custom tags) which can be available as the re-usable components with lot of flexibility |
Servlet has the life cycle methods init(), service() and destroy() | JSP has the life cycle methods of jspInit(), _jspService() and jspDestroy() |
Written in Java, with a few additional APIs specific to this kind of processing. Since it is written in Java, it follows all the Object Oriented programming techniques. | JSPs can make use of the Javabeans inside the web pages |
Thames
Qn.1) Write a program to illustrate how to use session state in servlet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<web-app> <servlet> <servlet-name>Servlet1</servlet-name> <servlet-class>MyServlet1</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet1</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> <servlet> <servlet-name>Servlet2</servlet-name> <servlet-class>MyServlet2</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet2</servlet-name> <url-pattern>/welcome</url-pattern> </servlet-mapping> </web-app> |
Qn2) Write a program where user can seleclt one of the option and display the selected option.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
package mynotepad1; import java.awt.Color; import java.awt.*; import java.awt.Menu; import java.awt.MenuBar; import java.awt.TextArea; public class Mynotepad1 extends Frame { TextArea ta; Mynotepad1(){ MenuBar mBar= new MenuBar(); setMenuBar(mBar); Menu files= new Menu("Files"); Menu date= new Menu ("Dates"); Menu exit= new Menu("Exit"); MenuItem mNew= new MenuItem("New"); files.add(mNew); MenuItem mOpen= new MenuItem("Open"); files.add(mOpen); MenuItem mSave= new MenuItem("Save"); files.add(mSave); files.addSeparator(); CheckboxMenuItem chMenuToolbox= new CheckboxMenuItem("Toolbox"); files.add(chMenuToolbox); ta= new TextArea(10,40); ta.setBackground(Color.gray); add(ta); mBar.add(files); mBar.add(date); mBar.add(exit); setSize(500,600); setVisible(true); } public static void main(String[] args) { new Mynotepad1(); } } |
Qn3) Repeated from past qn of 2016
Qn. 4) What is adapter class? Explain the advantages and disadvantages of adapter class over listener interfaces with suitable examples.
Adapter class is a simple java class that implements an interface with only EMPTY implementation Instead of implementing interface if we extends Adapter class ,we provide implementation only for require method. An adapter class provides the default implementation of all methods in an event listener interface. 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. You can define a new class by extending one of the adapter classes and implement only those events relevant to you.
Advantages:
• Assists unrelated classes to work together.
• Provides a way to use classes in multiple ways.
• Increases the transparency of classes.
• Its provides a way to include related patterns in a class.
Disadvantages:
• All requests are forwarded, so there is a slight increase in the overhead.
• Sometimes many adaptations are required along an adapter chain to reach the type which is required.
• No new functionality can be added in adapter class.
Examples
The following examples contain the following Adapter classes:
• ContainerAdapter class.
• KeyAdapter class.
• FocusAdapter class.
• WindowAdapter class.
• MouseAdapter class.
• ComponentAdapter class.
• MouseMotionAdapter class.
Java MouseAdapter Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.awt.*; import java.awt.event.*; public class MouseAdapterExample extends MouseAdapter{ Frame f; MouseAdapterExample(){ f=new Frame("Mouse Adapter"); f.addMouseListener(this); f.setSize(300,300); f.setLayout(null); f.setVisible(true); } public void mouseClicked(MouseEvent e) { Graphics g=f.getGraphics(); g.setColor(Color.BLUE); g.fillOval(e.getX(),e.getY(),30,30); } public static void main(String[] args) { new MouseAdapterExample(); } } |
Group C
1) Differentiate between jsp and servlet.explain the use of web.xml file with an example.
- Writing code for servlet is harder than JSP as it is html in java. 1)JSP is easy to code as it is java in html.
- Servlet plays a controller role in MVC approach. 2)JSP is the view in MVC approach for showing output.
- Servlet is faster than JSP. 3) JSP is slower than Servlet because the first step in JSP lifecycle is the translation of JSP to java code and then compile.
- Servlet can accept all protocol requests. 4) JSP only accept http requests.
- In Servlet, we can override the service() method. 5) In JSP, we cannot override its service() method.
- In Servlet by default session management is not enabled, user have to enable it explicitly. 6)In JSP session management is automatically enabled
- Servlet is a java code.
- JSP is a html based code.
Web.xml file is the configuration file of web applications in java.
It instructs the servlet container which classes to load, what parameters to set in the context,
and how to intercept requests coming from browsers.
2) Differentiate between applet and swing. explain the border layout manager.
- Swing is light weight component while applet is not.
- Applet have no main method, but swing have.
- Swing have have look and feel while Applet Does not provide this facility.
- Swing uses for stand lone Applications while Applet need HTML code for Run the Applet.
- Swing have its own Layout while Applet uses Awt Layout.
The border layout is used to arrange the component in five regions:
north,south,east,west¢er. eacch region may contain one component only.border layout creates a border layout but no gap between components. It is the default layout of frame or window.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.awt.*; import javax.swing.*; public class Border { JFrame f; Border(){ f=new JFrame(); JButton b1=new JButton("NORTH");; JButton b2=new JButton("SOUTH");; JButton b3=new JButton("EAST");; JButton b4=new JButton("WEST");; JButton b5=new JButton("CENTER");; f.add(b1,BorderLayout.NORTH); f.add(b2,BorderLayout.SOUTH); f.add(b3,BorderLayout.EAST); f.add(b4,BorderLayout.WEST); f.add(b5,BorderLayout.CENTER); f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new Border(); } } |
NCIT
SET A
3.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<!DOCTYPE html> <html> <head> <meta charset=”ISO-8859-1”> <title>Odd and Even</title> </head> <body> <form method=”post” action=”Ques3.jsp”> <h1>Enter the number:</h1><input type=”number” name=”num”> <input type=”submit” value=”calculate”> </form> </body> </html> <%@page language=”java” contentType=”text/html; charset=ISO-8859-1”%> <!DOCTYPE html> <% int n=Integer.parseInt(request.getParameter(“num”); if(n%2==0){ out.println(“The number is even”); } else { out.println(“The number is odd”); } %> |
- Keyboard event handling by applet
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182import java.awt.*;import java.awt.event.*;import java.applet.*;/*<applet code="Key" width=300 height=400></applet>*/public class Key extends Applet implements KeyListener{int X=20,Y=30;String msg="KeyEvents--->";public void init(){addKeyListener(this);requestFocus();setBackground(Color.green);setForeground(Color.blue);}public void keyPressed(KeyEvent k){showStatus("KeyDown");int key=k.getKeyCode();switch(key){case KeyEvent.VK_UP:showStatus("Move to Up");break;case KeyEvent.VK_DOWN:showStatus("Move to Down");break;case KeyEvent.VK_LEFT:showStatus("Move to Left");break;case KeyEvent.VK_RIGHT:showStatus("Move to Right");break;}repaint();}public void keyReleased(KeyEvent k){showStatus("Key Up");}public void keyTyped(KeyEvent k){msg+=k.getKeyChar();repaint();}public void paint(Graphics g){g.drawString(msg,X,Y);}}import java.awt.*;import java.awt.event.*;public class KeyListenerExample extends Frame implements KeyListener{Label l;TextArea area;KeyListenerExample(){l=new Label();l.setBounds(20,50,100,20);area=new TextArea();area.setBounds(20,80,300, 300);area.addKeyListener(this);add(l);add(area);setSize(400,400);setLayout(null);setVisible(true);}public void keyPressed(KeyEvent e) {l.setText("Key Pressed");}public void keyReleased(KeyEvent e) {l.setText("Key Released");}public void keyTyped(KeyEvent e) {l.setText("Key Typed");}public static void main(String[] args) {new KeyListenerExample();}}
5.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.sql.*; import java.sql.DriverManager; public class Five{ Connection con; Statement stmt; String sql, url; Five( ){ Class.forName(“com.mysql.jdbc.Driver”); url=”jdbc:mysql://localhost:3306/contact”; con=DriverManager.getConnection(“url”,”root”,””); stmt=con.createStatement( ); sql=”INSERT INTO Student(id, name, address, gender, program) VALUES (1,’Dikchya’, ’Sorakhutee’,’ Female’,’BIM’); int result=stmt.executeUpdate(sql); if(result!=-1){ System.out.println(“Successfully inserted”); } else { System.out.println(“Failed to insert”); } } public static void main(String[] args){ new Five( ); } } |
6.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import java.awt.*; import java.awt.event.*; public class MenuDemo { public MenuDemo() { Frame f = new Frame("DashBoard"); f.setSize(400, 400); MenuBar menubar = new MenuBar(); Menu fileMenu = new Menu("File",true); Menu editMenu = new Menu("Edit"); Menu helpMenu = new Menu("Help"); menubar.add(fileMenu); menubar.add(editMenu); menubar.add(helpMenu); f.setMenuBar(menubar); MenuItem newfile = new MenuItem("New"); MenuItem openfile = new MenuItem("Open"); MenuItem newsave = new MenuItem("Save"); MenuItem newsaveas = new MenuItem("SaveAs"); MenuItem newexit = new MenuItem("Exit"); CheckboxMenuItem c1 = new CheckboxMenuItem("Check 1", true); CheckboxMenuItem c2 = new CheckboxMenuItem("Check 2"); fileMenu.add(newfile); fileMenu.add(openfile); fileMenu.add(newsave); fileMenu.add(newsaveas); fileMenu.add(newexit); fileMenu.add(c1); fileMenu.add(c2); newsaveas.setEnabled(false); f.setLocationRelativeTo(null); f.setVisible(true); } public static void main(String[] args) { new MenuDemo(); } } |
7.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import javax.swing.*; public class ListExample { ListExample(){ JFrame f= new JFrame(); DefaultListModel<String> l1 = new DefaultListModel<>(); l1.addElement("Item1"); l1.addElement("Item2"); l1.addElement("Item3"); l1.addElement("Item4"); JList<String> list = new JList<>(l1); list.setBounds(100,100, 75,75); f.add(list); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } public static void main(String args[]) { new ListExample(); }} |
-
1234567891011121314151617181920212223242526272829<!<!DOCTYPE html><html><head><title>Form </title></head><body><form action=”Form” method=”Get”>UserName:<input type=”text” name=”user”/>Password:<input type=”password” name=”pass”/><input type=”submit” name=”submit”/></form></body></html>import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class Form extends HttpServlet{public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception{HttpSession session=request.getSession( );session.setAttribute(“user”,request.getParameter(“user”);session.setAttribute(“pass”,request.getParameter(“pass”);PrintWriter out=response.getWriter( );out.println(“<! DOCTYPE html ><html><head><title>Form</title></head><body><h1>Username:”+session.getAttribute(“user”)+”<br/>Password:”+session.getAttribute(“pass”)+”</h1></body></html>”);session.invalidate( );}}
Set B
2.
Table.jsp
1 2 3 4 5 6 7 8 9 10 |
<html> <body> <h2>Enter Any 2 Numbers !!</h2> <form action="Table2.jsp" method="post"> First No: <input type="text" name="fno"><br> Second No: <input type="text" name="sno"><br> <input type="submit" value="Show Tables"> </form> </body> </html> |
Table2.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<html> <body> <% int num1=Integer.parseInt(request.getParameter("fno")); int num2=Integer.parseInt(request.getParameter("sno")); int range=0;%> <table cellpadding=0 cellspacing=0 align='center' bgcolor='yellow' width=70% > <% try { for (int j = 1; j <= 10; j++) { %><tr><th>|</th><% for (range = num1; range <= num2; range++) { %><td align='center'><% out.println(range); %></td><td align='center'><%out.println("*"); %></td><td align='center'><%out.println(j); %></td><td align='center'><%out.println(" = "); %></td><td align='center'><%out.println(range * j); %><th>|</th><% } %></tr><% } } catch(Exception e) { out.println("Error"); } %> </table> </body> </html> |
3.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<html> <body> <% int num1=Integer.parseInt(request.getParameter("fno")); int num2=Integer.parseInt(request.getParameter("sno")); int range=0;%> <table cellpadding=0 cellspacing=0 align='center' bgcolor='yellow' width=70% > <% try { for (int j = 1; j <= 10; j++) { %><tr><th>|</th><% for (range = num1; range <= num2; range++) { %><td align='center'><% out.println(range); %></td><td align='center'><%out.println("*"); %></td><td align='center'><%out.println(j); %></td><td align='center'><%out.println(" = "); %></td><td align='center'><%out.println(range * j); %><th>|</th><% } %></tr><% } } catch(Exception e) { out.println("Error"); } %> </table> </body> </html> |
4.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.sql.*; import java.sql.DriverManager; public class Four{ Connection con; Statement stmt; String sql, url; Four( ){ try{ Class.forName(“com.mysql.jdbc.Driver”); url=”jdbc:mysql://localhost:3306/contact”; con=DriverManager.getConnection(“url”,”root”,””); stmt=con.createStatement( ); sql=”DELETE FROM Student WHERE Student_name=’Dikchya’); int result=stmt.executeUpdate(sql); if(result!=-1){ System.out.println(“Database has been deleted”); } else { System.out.println(“Failed to delete the database”); } } catch(Exception e){ e.printStackTrace( ); } } public static void main(String[] args){ new Four( ); } } |
5.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
import java.awt.*; import java.awt.event.*; import javax.swing.*; // class extends JFrame class BorderLayoutDemo extends JFrame { BoderLayoutDemo() { JPanel pa = new JPanel(); pa.setLayout(new BorderLayout()); pa.add(new JButton("WelCome"), BorderLayout.NORTH); pa.add(new JButton("Geeks"), BorderLayout.SOUTH); pa.add(new JButton("Layout"), BorderLayout.EAST); pa.add(new JButton("Border"), BorderLayout.WEST); pa.add(new JButton("GeeksforGeeks"), BorderLayout.CENTER); add(pa); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(300, 300); setVisible(true); } } public static void main(String[] args) { new BoderLayoutDemo(); } } import javax.swing.*; import java.awt.*; public class GridLayoutDemo extends JFrame { GridLayoutDemo() { JPanel p1 = new JPanel(); p1.setLayout(new GridLayout(4, 2)); FlowLayout layout = new FlowLayout(); JPanel p2 = new JPanel(); p2.setLayout(layout); JLabel one, two, three, four; JTextField tname, tsalary, tcode, tdesig; JButton buttonSave, buttonExit; one = new JLabel("NAME"); tname = new JTextField(20); two = new JLabel("CODE"); tcode = new JTextField(20); three = new JLabel("DESIGNATION"); tdesig = new JTextField(20); four = new JLabel("SALARY"); tsalary = new JTextField(20); buttonSave = new JButton("SAVE"); buttonExit = new JButton("EXIT"); p1.add(one); p1.add(tname); p1.add(two); p1.add(tcode); p1.add(three); p1.add(tdesig); p1.add(four); p1.add(tsalary); p2.add(buttonSave); p2.add(buttonExit); add(p1, "North"); add(p2, "South"); setVisible(true); this.setSize(400, 180); } public static void main(String args[]) { new GridLayoutDemo(); } } |
6.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; public class JTableExamples { // frame JFrame f; // Table JTable j; // Constructor JTableExamples() { // Frame initiallization f = new JFrame(); // Frame Title f.setTitle("JTable Example"); // Data to be displayed in the JTable String[][] data = { { "Kundan Kumar Jha", "4031", "CSE" }, { "Anand Jha", "6014", "IT" } }; // Column Names String[] columnNames = { "Name", "Roll Number", "Department" }; // Initializing the JTable j = new JTable(data, columnNames); j.setBounds(30, 40, 200, 300); // adding it to JScrollPane JScrollPane sp = new JScrollPane(j); f.add(sp); // Frame Size f.setSize(500, 200); f.setVisible(true); } public static void main(String[] args) { new JTableExamples(); } } |
7.
INDEX.JSP:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <form method=”post” action=”servlet”> Name:<input type="text" name="name" value="" /> Num1:<input type="text" name="num1" value="" /> Num2:<input type="text" name="num2" value="" /> <br> <input type="submit" value="button" /> </form> </body> </html> |
Servlet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
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(name = "HelloServelet", urlPatterns = {"/HelloServelet"}) public class HelloServelet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String name = request.getParameter("name"); int a = request.getParameter("num1"); int b = request.getParameter("num2"); int pro = 0; int x,y; x = Integer.parseInt(a); y = Integer.parseInt(b); pro = x * y; out.println("Hi!" + name + "The product is" + pro); out.close(); } } |