Advance Java | Preboard Solutions | 2019

5th Semester

Asian

Short Answer Questions:

  1. Define Event handling.
    Event handling is a mechanism that controls the event and decides what should happen if an event occurs.
  2. 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.
  3. 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.
  4. What are the two exceptions related with Servlet?
    – ServletException
    – IOException
  5. How do you create constant variable in Java?
    Final keyword
  6. Name the event generated when the button is clicked?
    ActionEvent
  7. 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.
  8. What is XML?
    XML schema is a language which is used for expressing constraint about XML documents.
  9. Define PreparedStatement.
    A prepared statement is a feature used to execute the same (or similar) SQLstatements repeatedly with high efficiency.
  10. 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.

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.

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.

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.

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:

  1. Register the driver with driver manager.
  2. Obtain connection from driver.
  3. Obtain statement from connection.
  4. Run the query using statement.
  5. 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

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

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

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

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:

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:

  1. init()
    The init() methods run once in a servlet that initialize the servlet object and variables.
  2. service()
    The service() methods deals with dynamic request of client and generate the dynamic web pages.
  3. 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

  1. What are two key features of swing?
    • Swing components are lightweight and don’t rely on peers.
    • Swing supports a pluggable look and feel.
  1. 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.

 

  1. 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)
  1. What is SQL exception?

The SQL Exception class provides information on a database access error.

  1. What are the different types of drivers used in JDBC?
    • JDBC-ODBC bridge driver,
    • Native-API driver,
    • Network Protocol driver,
    • Thin driver.
  1. 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.

  1. 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.

  1. 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.

  1. List the different jsp tag.
    • Declarative tag
      <% ! … %>
    • Directive tag
      <%@ page … %
      <%@ include … %>
      <%@ taglib … %>
    • Scriplet tag
      <%  … %>
    • Expression tag
      <%= … %>
  1. Difference between XML and HTML.

Group B

  1. Create a HTML document that contain the header information of page and include this HTML as a header file in JSP.

// index.html

<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” %>

  1. 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
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();
    }
}

 

  1. 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

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("visit");
        out.close();
                }catch(Exception e){System.out.println(e);}
    }
}

//SecondServlet.java

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);}
    }
}

 

  1. Write a servlet program to find the prime number between 20 and 100.
    import 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++;
    		}
    	}
    
  2. Write a swing program to insert data in table using prepared statement. (You can assume your own database, table, and number of field.
    import 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 query
    stmt.setString(2,"Ratan");
    int i=stmt.executeUpdate();
    System.out.println(i+" records inserted");
    con.close();
    }catch(Exception e){ System.out.println(e);}
    }
    }
    

Group C

  1. 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 %>

  1. 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

  1. 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
  1. List any four event classes.

Any four Event classes are as follow:

    • ActionEvent
    • KeyEvent
    • MouseEvent
    • TextEvent
  1. 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.

  1. 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.

  1. 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.

  1. 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.

  1. 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.

  1. 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
  1. 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.

  1. 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.

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.

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:

<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.

<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

<html>
<body>
<form action = Servlet” method = “POST”>
Name:<input type=“text” name “uname”/><br>
<input type =“submit” value=“go”/></form>
</body>
</html>

Cookie.java

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

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.

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:

  1. 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.

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);
}
}
  1. Write a servlet program to compute factorial of a given positive number.

Factorial.html

<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

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

  1. How can you pass parameter in applet?
    • Parametersare passedto applets in NAME=VALUE pairs in <PARAM> tags between the opening and closing APPLET
  1. How can you create a dropdown list and multiple selection list in swing?
    • Dropdown list.
      public dropDown()
      {
      Object obj [] ={“a”,”b”,”c”};
      JComboBox c=new JCombox(obj);
      add(c);
      }
    • Multiple selection
public MultipleSelection()
{
	String color[]={“red”,”blue”,”green”};
	JList list=new JList(color);
                                  list.setSelectionMode
                                (ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}
  1. 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.
  1. What is Exception?
  • Exception are the abnormal conditions that occur in your program during execution which terminates the program.
  1. Which class is used to browse and open file?
  • JFileChooser() and showOpenDialog() class is used to browse and open a file.
  1. Which method are used to add mnemonic and shortcuts in menu?
  • setMnemonic() method and setShortcut() methods are used to add mnemonicand shortcuts in menu.
  1. 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.
  1. 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.
  1. What is inner class?
  • Inner classmeans one classwhich is a member of another class.
  1. 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

  1. Write a program which creates a menu (File->open, save, close) in frame.
    import 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();
    	}
    }
    
  2. 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

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();
	}
}
  1. Create a frame which contains a swing table with some data.
    import 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();
    	}
    }
  2. 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

<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

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);
        }
    }
 }
  1. 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:

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:

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();
	}
}
  1. 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)].
    import 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();
    	}
    }

     

  2. Create a login form (web) and validate the user from database. Assume your own database parameters.
    <%@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>
  1. Create a Jsp simple calculator. The result should be processed by a servlet.

Calculator.jsp

<%@ 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

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

  1. Write a statement to create a JTable.

JTable jt=new JTable(data,column);

  1. 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” …/>

  1. 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.

  1. Which method is used to set the maximum inactive time interval for a session?

setMaxInactiveInterval

  1. List the two key features of swing.
    Swing components are lightweight.
    – Swing supports pluggable look and feel.
  2. How can you create a combo box in AWT?

By using constructor choice()
Choice c1=new Choice();
C1.add(“BIM”);
C1.add(“BBA”);

  1. 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.

  1. Mention any two uses of page directive in JSP.
    It is used to import the classes.
    – It is used to set the content type.
  2. 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.
  3. 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.

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

<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

<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.

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.

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.

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

<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>

————————————

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:

  1. How can you prevent the user from resizing the frame at runtime?
    setResizable(false);
  2. 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” …/>
  3. 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”);
  4. What are the advantages of 2-tier architecture?
    • Easy to maintain and modification is bit easy.
    • Communication is faster.
  5. Mention any four event classes.
    • MouseEvent,
    • KeyEvent
    • ItemEvent
    • WindowEvent
  6. What are the two ways of creating applet?
    • By extending JApplet class.
    • By extending Applet class.
  1. 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.
  1. What are the parameters taken by doGet() or doPost() methods in a servlet?
    • HTTPServletRequest request,HttpServletResponse response
  2. 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.
  1. 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.

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”.

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.

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

<html>
<body>
<%
String str = request.getParameter("str");
int len = str.length();
out.println("Length is: "+len);
%>
</body>
</html>

—————————-
length.html

<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.

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:

  1. 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

<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>

————————————

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

  1. 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.
  1. 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
  1. What is Swing Class?
    • Swing class is used to create a graphical user interface.
  1. 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.
  1. When is ActionPerformed function defined?
    • When event is called to ActionListener interface.
  1. How is database connection object created in java?
    • Connection con= new Driver manager.getconnection( jdbc:mysql\\’localhost’\’root’, ‘ ’);
  1. Which package is used to make swing object?
    • Import javax.swing.*; is used to make swing object.
  1. 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.
  1. What are the parameters taken by dopost ( ) methods of servlet?
    • HttpServletRequest & HttpServletResponse
  1. 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

  1. Make an user interface to take name and address of user?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class First extends JFrame implements ActionListener
    {
    	JLabel name;	JTextField jtf;
    	JLable address; JTextField jtf2
    	JButton 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() ;
    	}
    }
  2. Make a user interface to take name and address of user?
    import 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");
    		}
    	}
    }
    }
  3. Make an applet to display name of your college?
    import 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>*/
    
  4. Write a jsp program to display multiplication table to 2 (from 1 To 10).
    <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

  1. 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
 
 
  1. 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

<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

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

<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

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

<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

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

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

<!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

<%@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

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

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();
        String sql="INSERT INTO Teachers VALUES(5,Shraddha,kathmandu,9851012345,[email protected]);
        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

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

<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

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

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

<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

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

<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

<!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

<%@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

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

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:
    1. Mouse event
    2. Key event
  • Text event
    1. Window event
    2. 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?

  • 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.

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.

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.

<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.

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 &gt; 0) {
     for(int i = 1; i &lt;= num; i++) {
      fact = fact * i;
   }
 }
try {
PrintWriter pw = response.getWriter();
pw.println("&lt;html&gt;&lt;body&gt;");
pw.println("&lt;h1&gt;Factorial of "+num+ " is "+fact+"&lt;/h1&gt;");
pw.println("&lt;/html&gt;&lt;/body&gt;");
}catch(Exception ex) {
  System.out.println(ex);
  }
  }
}

 
 
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset=”ISO-8859-1″&gt;
&lt;title&gt;Insert title here&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;form action = “ques2_2018” method = “get”&gt;
&lt;label&gt;Enter a Number:&lt;/label&gt;
&lt;input type = “text” name = “number”/&gt;
&lt;input type = “submit” value = “Submit”/&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
 
6) Create an applet that contain three text field and two buttons (add and subtract). Perform add and subtract.

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.
    1. Grid bag layout
      The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle.
      Example:

      import java.awt.*;
      import javax.swing.*;z
      public 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();
      }
      }
    2. Border 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:

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:

  1. 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.
  2. 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”.
  3. Synth:the basis for creating your own look and feel with an XML file.
  4. Multiplexing:a way to have the UI methods delegate to a number of different look and feel implementations at the same time.
    For example:

    import 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

  1. Which method is used to create session in java?
    public HttpSession getSession()
    public HttpSession getSession(boolean create)
  1. 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.
  2. 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. 
  3. 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.
  4. What is component?
    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.
  5. 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.
  6. 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.

    Checkbox 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.

    Checkbox 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);
    
  7. 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.
  1. 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.
  2. 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

  1. Write a swing program in which user can select one of the option and display that selected option.
    import 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.

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.

<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.

<applet code ="abc.applet" width="100px" height="100px">
<para name="a" value="10">
<para name="b" value="20">
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.

<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.

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

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&center. 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.

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.

<!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”);
	}
%>
  1. Keyboard event handling by applet
    import 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.

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.

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.

 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();
    }}
  1. <!<!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

<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

<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.

<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.

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.

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.

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:

<%@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:

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();
}
}