0% found this document useful (0 votes)
9 views7 pages

Java 22

A report

Uploaded by

bibek547khadka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views7 pages

Java 22

A report

Uploaded by

bibek547khadka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Write a swing program to add two WAP to set cookies. WAP to make connection with database.

numbers given as input by the user. import javax.servlet.http.*; Make your own assumption about the database.
import java.awt.*; import java.io.*; import java.sql.*;
import javax.swing.*; public class Ques5_2016 extends HttpServlet{ public class T2016_6 {
import javax.swing.event.*; public void doGet(HttpServletRequest static Connection con;
import java.awt.event.*; request,HttpServletResponse response) public static void main(String[] args) throws
public class T2016_2 extends JFrame implements { response.setContentType("text/html"); Exception{
ActionListener{ try{ connect();
JTextField t1,t2; PrintWriter pw = response.getWriter(); }
JLabel sum; Cookie cookie1 = new Cookie("FirstName", "abc"); public static void connect() throws Exception{
JButton b; Cookie cookie2 = new Cookie("LastName", "bcd"); Class.forName("com.mysql.jdbc.Driver");
public T2016_2(){ cookie1.setMaxAge(24*60*60); String url="jdbc:mysql://localhost:3306/fomdb";
t1=new JTextField(); cookie2.setMaxAge(24*60*60); con=DriverManager.getConnection(url,"root","");
t2=new JTextField(); response.addCookie(cookie1); if(con!=null){
sum=new JLabel(""); response.addCookie(cookie2); System.out.println("Successfully connected to
b=new JButton("Add"); pw.println("Hello user cookie has been set to your database");
setLayout(new GridLayout(4,1)); computer"); }
add(t1); add(t2); add(b); add(sum); pw.close(); else{
setSize(200,400); }catch(Exception ex){ System.out.println("Error connecting to
setVisible(true); System.out.println(ex); } } } database!");
b.addActionListener(this); }}}
}
public void actionPerformed(ActionEvent e){ Write a servlet to display “Hello Tomcat”
int n1=Integer.parseInt(t1.getText()); import java.io.*;
import javax.servlet.*; Make a user form with three radio buttons.
int n2=Integer.parseInt(t2.getText());
import javax.servlet.http.*; import java.awt.*;
int s=n1+n2;
public class HelloWorld extends HttpServlet { public class T2016_7 extends Frame{
sum.setText("Sum is: "+s);
private String message; Label l1,l2;
}
public void init() throws ServletException Panel p1,p2;
public static void main(String[] args) {
{ TextField t1;
new T2016_2();
message = "Hello Tomcat"; CheckboxGroup cb;
}}
} Checkbox a,b,c;
public void doGet(HttpServletRequest request, public T2016_7() {
Write an applet to check whether given
HttpServletResponse response) l2=new Label("Gender: ");
word by user is of length 5 or not.
throws ServletException, IOException cb=new CheckboxGroup();
import java.awt.*;
{ a=new Checkbox("Male",true,cb);
import java.applet.*;
response.setContentType("text/html"); b=new Checkbox("Female",false,cb);
public class WordLength extends Applet {
PrintWriter out = response.getWriter(); c=new Checkbox("Other",false,cb);
String word, temp;
out.println("<h1>" + message + "</h1>"); add(l2); add(a); add(b); add(c);
int n;
} setLayout(new FlowLayout());
public void start () {
public void destroy() setSize(400,200);
word = getParameter("input");
{}} setVisible(true);
n = word.length ();
}
if(n==5)
public static void main(String[] args) {
temp = "The word is of length 5";
new T2016_7();
else
Create a HTML documents that contains }}
temp = "The word is not of length 5";
header information of a page
}
and include this HTML as a header file in JSP.
public void paint (Graphics g){ Create JSP page to display all odd numbers from
Step:1 Create an HTML header file (e.g.,
g.drawString (temp,20, 20); 10 to 50.
header .html)
}} <html>
<!-- header.html -->
The HTML file for above applet is: <head>
<header>
<html> <title></title>
<h1>Welcome to My Website</h1>
<body> </head>
<nav> <body>
<applet code ="WordLength.class"
<ul> <%
width = "400" height = "500">
<li><a href="home.jsp">Home</a></li> for(int i=10; i<=50; i++){
<param name = "input" value =" This is Applet">
<li><a href="about.jsp">About</a></li> %>
</applet> if(i%2!=0){
<li><a href="contact.jsp">Contact</a></li>
</html> (%i = %)
</ul>
}
</nav>
Write a JSP program to display <%
</header> }
“Apache Tomcat” eight times.
<html> Step:2 Include this header in your jsp (eg.,index.jsp) %>
<head> <!-- index.jsp --> </body>
<%@ include file="header.html" %> </html>
</head>
<body> <p>This is the main content of the page.</p>
<%
for(int i = 1; i <= 8; i++) {
out.println("Apache Tomcat <br />");
}
%>
Make an applet to display the name of your college.
</body>
import java.applet.Applet;
</html>
import java.awt.Graphics;
public class College extends Applet{
public void paint (Graphics g){
g.drawString ("IMS College",20,150);
}
}
/*<applet code = "College.class" width="200"
height="200"></applet>*/
Write a servlet to find the reverse of a string Create a servlet to find out factorial of a positive Write a program to demonstrate the key event
import java.io.*; integer value for moving an image left, right, up and down.
import javax.servlet.*; import java.io.IOException; import java.awt.*;
import javax.servlet.http.*; import java.io.PrintWriter;
import java.awt.event.*;
import javax.swing.*;
import javax.servlet.ServletException;
public class ReverseStringServlet extends HttpServlet { import javax.servlet.http.HttpServlet; public class KeyEventDemo extends JFrame implements
protected void doGet(HttpServletRequest request, import javax.servlet.http.HttpServletRequest; KeyListener {
HttpServletResponse response) import javax.servlet.http.HttpServletResponse; JLabel l;
throws ServletException, IOException { int x = 0, y = 0;
String inputString = request.getParameter("input"); public class FactorialServlet extends HttpServlet { public KeyEventDemo() {
String reversedString = new StringBuilder(inputString) protected void doGet(HttpServletRequest request,
setTitle("KeyEventDemo");
.reverse().toString( setSize(300, 300);
HttpServletResponse response) throws setLayout(new FlowLayout());
response.setContentType("text/html"); ServletException, IOException { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PrintWriter out = response.getWriter(); String numStr = l = new JLabel("Press any key on the keyboard");
out.println("Reversed String: " + reversedString); request.getParameter("number"); add(l);
}} int number = Integer.parseInt(numStr); addKeyListener(this);
int factorial = 1; setVisible(true);
Create an applet that contains 3 text fill and for (int i = 1; i <= number; i++) {
}
two buttons (Add and subtract). public void keyPressed(KeyEvent ke) {
factorial *= i; l.setText("You pressed: " + ke.getKeyChar());
Perform addition and subtraction } if (ke.getKeyCode() == KeyEvent.VK_RIGHT) {
when add and subtract buttons are clicked. response.setContentType("text/html"); x += 10;
public class Ap extends Applet{ PrintWriter out = response.getWriter(); l.setLocation(x, y);
int a, b; out.println("<html><body>"); } else if (ke.getKeyCode() == KeyEvent.VK_LEFT) {
public void start () { out.println("<h1>Factorial of " + number + " is: x -= 10;
string b= getparameter("b"); " + factorial + "</h1>");
l.setLocation(x, y);
string a= getparameter("a"); } else if (ke.getKeyCode() == KeyEvent.VK_UP) {
out.println("</body></html>"); y -= 10;
try{ }} l.setLocation(x, y);
if(a!= null && b!=null){ } else if (ke.getKeyCode() == KeyEvent.VK_DOWN) {
a= Integer.parseInt("a"); y += 10;
b= Integer.parseInt("b"); Create an applet that reads the l.setLocation(x, y);
int sub=a-b; parameter supplied from the <param> tag } }
int sum=a+b; and display the parameter value.
public void keyReleased(KeyEvent ke) {
}catch(Exception e){ l.setText("You released: " + ke.getKeyChar());
Also create a suitable HTML file. }
System.out.println(e); import java.applet.*; public void keyTyped(KeyEvent ke) {
System.out.println("sum" +sum); import java.awt.*; l.setText("You typed: " + ke.getKeyChar());
System.out.println("sub" +sub); import java.applet.*; }
} /* public static void main(String[] args) {
} &lt;applet code="T2018_5.class" new KeyEventDemo();
<applet code="add.Applet"> height="300" width="500"&gt;
}}
<para name="a" value="50"> &lt;param name="name" value="Laxmi"
<para name="b" value="60"> /&gt; Assume a database named "college_db", which contains
</applet> &lt;param name="age" value="20" /&gt; a table named "employees" with attributes
&lt;/applet&gt; (employee_id, employee_name, contact_number, salary).
*/ Write a JDBC program to update the salary of employee
public class T2018_5 extends Applet to 20,000 whose employee_id = 6
{ import java.sql.*;
String n; class Update
String a; {
public void init(){ public static void main(String args[])
n=getParameter("name"); {
a=getParameter("age"); try
} {
public void paint(Graphics g){ Class.forName("com.mysql.jdbc.Driver");
g.drawString("Name is: " + n, 20, 20); Connection
g.drawString("Age is: " + a, 20, 40); con=DriverManager.getConnection("jdbc:mysql://localhost:
} 3306/College_db","root","");
Create a Swing GUI that contains a combo box } Statement stmt=con.createStatement();
and a text field. When the users select any item String query="update employees set salary=20000 where
in employee_id=6";
the combo box, it will be displayed in the text field. int i=stmt.executeUpdate(query);
import javax.swing.*; System.out.println(i+" records updated");
import java.awt.event.*; con.close();
public class ComboBoxExample { }
public static void main(String[] args) { catch(Exception e)
JFrame frame = new JFrame("ComboBox Example"); {
frame.setSize(300, 150); System.out.println(e);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}}
frame.setLayout(null);
String[] items = {"Item 1", "Item 2", "Item 3"};
Write a JSP to display”Hello form
JComboBox<String> comboBox = new JComboBox<>(items);
jsp” 10 times.
comboBox.setBounds(50, 30, 100, 20); <html>
JTextField textField = new JTextField(); <head>
textField.setBounds(50, 60, 100, 20); <title> </title>
comboBox.addActionListener(new ActionListener() { </head>
public void actionPerformed(ActionEvent e) <body>
String selectedItem = (String) comboBox.getSelectedItem(); <%
String i=" Hello from jsp";
textField.setText(selectedItem);
For( i=1; i<=10; i++){
} }); %>
frame.add(comboBox); <%i = %>
frame.add(textField); <% }
frame.setVisible(true); %>
}} </body>
</html>
Write a servlet to read the values of principal, time and rate
from a HTML form and display the simple interest.
Also write the contents of HTML page and web.xml file
*/
import java.io.*;
import javax.servlet.*;
WAP to insert 5 records into the table “Book”
that contains (id, title, author, price) WAP of Adapter class.
inside the database “Library”. import java.awt.*;
import java.sql.*; import java.awt.event.*;
public class T2018_4 {
private static Connection con; public class AdapterClassExample extends
private static Statement s; Frame {
public static void main(String[] args) throws Exception{ public AdapterClassExample() {
insertRecords(); addMouseListener(new
} MouseAdapter() {
public static void insertRecords() throws Exception{ public void
Class.forName("com.mysql.jdbc.Driver"); mouseClicked(MouseEvent e) {
String url="jdbc:mysql://localhost:3306/Library"; System.out.println("Mouse
con=DriverManager.getConnection(url,"root",""); Clicked");
if(con!=null){ }
s=con.createStatement(); });
String sql="INSERT INTO book (id,title,author.price) VALUES " setSize(300, 200);
+ "(25,'AbcBook','AbcAuthor',2500)," setVisible(true);
+ "(47,'MnoBook','MnoAuthor',800)," }
+ "(33,'PqrBook','PqrAuthor',625)," public static void main(String[] args) {
+ "(49,'XyzBook','XyzAuthor',1200)," new AdapterClassExample();
+ "(11,'StuBook','StuAuthor',1200) "; }}
int res=s.executeUpdate(sql);
if(res!=-1){
System.out.println("Successfully inserted in table BOOK");
}
else{
System.out.println("Could not insert into table");
}}
else{
System.out.println("Error in connectiong to database!");
} }}

Create a swing GUI that contains odd text field and


two buttons (ok and clear). When ok button is clicked, "welcome" Write a servlet to receive a natural number
should be displayed in the text field from an HTML form and display whether
and clear buttons should be clear the text field contents the number is odd or even.
import javax.swing.*; import java.io.*;
import java.awt.event.*; import javax.servlet.*;
public class SimpleSwing extends JFrame implements ActionListener { import javax.servlet.http.*;
JTextField textField; public class OddEven extends HttpServlet {
JButton okButton, clearButton; public void doGet(HttpServletRequest request,
public SimpleSwing() { HttpServletResponse response)
textField = new JTextField(20); throws ServletException, IOException {
okButton = new JButton("OK"); response.setContentType("text/html");
clearButton = new JButton("Clear"); PrintWriter out = response.getWriter();
okButton.addActionListener(this); String n = request.getParameter("userName");
clearButton.addActionListener(this); int num = Integer.parseInt(n);
add(textField); if (num % 2 == 0) {
add(okButton); out.print("Even Number");
add(clearButton); } else {
setLayout(new java.awt.FlowLayout()); out.print("Odd Number");
setSize(300, 150); }
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); out.close();
setVisible(true); }
} }
public void actionPerformed(ActionEvent e) {
if (e.getSource() == okButton) {
textField.setText("Welcome");
} else if (e.getSource() == clearButton) {
textField.setText(""); How to create Jtable
}} import javax.swing.*;
public static void main(String[] args) { import javax.swing.table.DefaultTableModel;
new SimpleSwing(); // Run the GUI
}} public class SimpleTableExample {
public static void main(String[] args) {
String[] columnNames = {"ID", "Name", "Age"};
Object[][] data = {
WAP of Border layout. {1, "John", 25},
import java.awt.*; {2, "Jane", 30},
import javax.swing.*; {3, "Doe", 35}
};
public class BorderLayoutExample { DefaultTableModel model = new DefaultTableModel(data, columnNames);
public static void main(String[] args) { JTable table = new JTable(model);
JFrame frame = new JFrame("Border Layout Example"); JFrame frame = new JFrame("JTable Example");
frame.setLayout(new BorderLayout()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add buttons to different regions frame.add(new JScrollPane(table)); // Add table to scroll pane
frame.add(new JButton("North"), BorderLayout.NORTH); frame.setSize(300, 200);
frame.add(new JButton("South"), BorderLayout.SOUTH); frame.setVisible(true);
frame.add(new JButton("East"), BorderLayout.EAST); }}
frame.add(new JButton("West"), BorderLayout.WEST);
frame.add(new JButton("Center"), BorderLayout.CENTER);

frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}}

Create a JSP to illustrate


How event delegation model works.
the use of <jsp: useBean> import javax.swing.*;
import java.awt.event.*;

public class SimpleEventExample {


public static void main(String[] args) {
<jsp: setb property> and <jsp: getproperty.
Write the contents of Bean class too

Step:1 Java Bean class: User.java


public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}}
Step:2 JSP File: User.jsp
<%@ page language="java" contentType="text/html;
charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>JSP Bean Example</title>
</head>
<body>
<h2>Use of jsp:useBean, jsp:setProperty, and jsp:getProperty</h2>
<!-- Using the User Bean --> WAP of Flow Layout.
<jsp:useBean id="user" class="User" scope="session"/>
import java.awt.*;
<!-- Set the property of the bean -->
import javax.swing.*;
<jsp:setProperty name="user" property="name" value="John Doe" />
<!-- Display the property of the bean -->
public class FlowLayoutExample {
<p>Name: <jsp:getProperty name="user" property="name" /></p>
public static void main(String[] args) {
</body>
JFrame frame = new JFrame("Flow Layout Example");
</html>
frame.setLayout(new FlowLayout());
Design a GUI for normal calculators using appropriate layout.
import javax.swing.*; // Add buttons to the frame
import java.awt.*; frame.add(new JButton("Button 1"));
import java.awt.event.*; frame.add(new JButton("Button 2"));
public class SimpleCalculator extends JFrame implements ActionListener { frame.add(new JButton("Button 3"));
JTextField display; frame.add(new JButton("Button 4"));
JButton[] buttons; frame.add(new JButton("Button 5"));
String[] labels = { "7", "8", "9", "/",
"4", "5", "6", "*", frame.setSize(300, 200);
"1", "2", "3", "-", frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
"0", "C", "=", "+" }; frame.setVisible(true);
String currentInput = ""; }}
int firstNum = 0;
String operator = "";
public SimpleCalculator() {
display = new JTextField(10);
display.setEditable(false); WAP of Windows listener.
buttons = new JButton[16]; import java.awt.*;
JPanel panel = new JPanel(); import java.awt.event.*;
panel.setLayout(new GridLayout(4, 4));
for (int i = 0; i < 16; i++) { public class WindowListenerExample extends Frame {
buttons[i] = new JButton(labels[i]); public WindowListenerExample() {
buttons[i].addActionListener(this); addWindowListener(new WindowAdapter() {
panel.add(buttons[i]); public void windowClosing(WindowEvent e) {
} System.out.println("Window is closing");
add(display, BorderLayout.NORTH); dispose(); // Close the window
add(panel); }
setTitle("Simple Calculator"); });
setSize(300, 300); setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true);
setVisible(true); }
} public static void main(String[] args) {
public void actionPerformed(ActionEvent e) { new WindowListenerExample();
String command = e.getActionCommand(); }}
if (command.charAt(0) >= '0' && command.charAt(0) <= '9') {
currentInput += command;
display.setText(currentInput);
}
else if (command.equals("+") || command.equals("-") WAP to insert data using JDBC
|| command.equals("*") || command.equals("/")) { in MYSql database called contact_db.
firstNum = Integer.parseInt(currentInput); package database;
operator = command; import java.sql.*;
currentInput = ""; public class InsertData {
} public static void main(String args[]) throws Exception {
else if (command.equals("=")) { String url = "jdbc:mysql://localhost:3307/contact_db";
int secondNum = Integer.parseInt(currentInput); String uname = "root";
int result = 0; String pwd = "";
switch (operator) { Class.forName("com.mysql.jdbc.Driver");
case "+": result = firstNum + secondNum; break; Connection con = DriverManager.getConnection(url, uname, pwd);
case "-": result = firstNum - secondNum; break; Statement stmt = con.createStatement();
case "*": result = firstNum * secondNum; break; stmt.executeUpdate("insert into user
case "/": result = firstNum / secondNum; break; values(15,'Sush',23,'Sundarijal')");
} System.out.println("records affected");
display.setText(String.valueOf(result)); con.close();
currentInput = ""; }}
}
else if (command.equals("C")) {
display.setText("");
currentInput = "";
firstNum = 0;
} }

public static void main(String[] args) {


new SimpleCalculator(); // Run the calculator }}

Create a GUI using swing that contains two text fields,


two buttons (SMALL and LARGE) and a label.
When SMALL button is clicked, smaller of two numbers Explain about any three JSP implict objects with
entered from text fields should be displayed in the label and example.
when LARGE button is clicked, larger of two numbers
entered from text fields should be displayed in the label. 1. Out (Jspwriter)
import java.awt.*; = Represents the output stream to write content to the
import java.awt.event.*; response.
import javax.swing.*; =Example: Displaying a message on the web page.
public class SmallLarge extends JFrame implements ActionListener
{ <html>
JLabel l1,l2,l3; <body>
JTextField t1,t2; <% out.print("Hello, JSP!"); %>
JButton b1,b2; </body>
public SmallLarge() </html>
{
setLayout(new FlowLayout()); 2. Request (HttpServletRequest)
l1=new JLabel("Enter First Number");
l2=new JLabel("Enter Second Number"); =Represents the client’s request to the server.
l3=new JLabel("Result"); =Example: Retrieving a parameter from the URL.
t1=new JTextField(10); <html>
t2=new JTextField(10); <body>
b1=new JButton("Small"); <% String username =
b2=new JButton("Large"); request.getParameter("username"); %>
add(l1); Welcome, <%= username %>!
add(t1);
add(l2); </body>
add(t2); </html>
add(b1);
add(b2); 3. session (HttpSession):
add(l3); =Represents a user session, allowing data to persist
b1.addActionListener(this); across multiple requests.
b2.addActionListener(this); =Example: Storing and retrieving user-specific data.
} <html>
public void actionPerformed(ActionEvent ae) <body>
{ <% session.setAttribute("user", "John"); %>
int a=Integer.parseInt(t1.getText()); User: <%= session.getAttribute("user") %>
int b=Integer.parseInt(t2.getText()); </body>
if(ae.getSource()==b1) </html>
{
if(a&lt;b)
{
l3.setText("Smaller Number is "+a); WAP of Grid Layout. Create a servlet to read cookie from client
} import java.awt.*; And display the name and value associated
else import javax.swing.*; with the cookie.
{
import javax.servlet.http.*;
l3.setText("Smaller Number is "+b);
}} public class GridLayoutExample { import java.io.*;
public static void main(String[] args) { public class ReadCookie extends HttpServlet {
else
JFrame frame = new JFrame("Grid Layout Example"); public void doGet(HttpServletRequest request,
{
HttpServletResponse response) {
if(a&gt;b) frame.setLayout(new GridLayout(2, 3)); // 2 rows and 3 response.setContentType("text/html");
{ columns Cookie[]cookie = request.getCookies();
l3.setText("Larger Number is "+a);
try {
}
// Add components to the frame PrintWriter pw = response.getWriter();
else
{ frame.add(new JButton("Button 1")); pw.println("<html><body>");
frame.add(new JButton("Button 2")); pw.println("<h1>Cookie Info</h1>");
l3.setText("Larger Number is "+b);
frame.add(new JButton("Button 3")); if(cookie != null) {
}}}
for(int i = 0; i < cookie.length; i++) {
public static void main(String args[]) frame.add(new JButton("Button 4")); pw.println("Cookie name: "+cookie[i].getName());
{ frame.add(new JButton("Button 5")); pw.println("Cookie value: "+cookie[i].getValue());
SmallLarge sl=new SmallLarge(); frame.add(new JButton("Button 6")); }}
sl.setSize(300,300);
pw.println("</html></body>");
sl.setVisible(true);
sl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); }catch(Exception ex) {
System.out.println(ex);
}}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CL }}}
OSE);
frame.setVisible(true);
WAP of Card Layout. }}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class CardLayoutExample {


public static void main(String[] args) { Write a JSP program to compute sum of two numbers.
JFrame frame = new JFrame("Card Layout Example"); <html>
CardLayout cardLayout = new CardLayout(); <head>
JPanel cardPanel = new JPanel(cardLayout); <title>Form Processing</title>
JPanel card1 = new JPanel(); </head>
card1.add(new JLabel("This is Card 1"));
<body> <font size = 3> <br>
JPanel card2 = new JPanel(); <center>
card2.add(new JLabel("This is Card 2")); Processing HTML Form <hr color = red size = 3>
cardPanel.add(card1, "Card1"); <% out.println(“Hello World”);
cardPanel.add(card2, "Card2"); int x = 10; int y = 20; int z = x+y;
JButton switchButton = new JButton("Switch Card"); out.println(“sum = “+z);
switchButton.addActionListener(e -> cardLayout.next(cardPanel)); %>
frame.add(cardPanel, BorderLayout.CENTER); </center>
frame.add(switchButton, BorderLayout.SOUTH); </font>
</body>
frame.setSize(300, 200); </html>
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); }}
Write a program to read the
employee (id, name, address, salary)
from the field and display.
import java.sql.*;
public class ConnectDB {
WAP of key event.
=On entering the character the key event is generated.
Three types of Key event:
1. Key Pressed.
2. Key Released.
3. 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();
}}

Write a servlet program to


find the prime number between 20 and 100.
import java.io.*;
import javax.servlet.*;
Write a swing program in which
import javax.servlet.http.*;
user can select one of the
class test extends HttpServlet{
Option and display that selected option.
public void doGet (HttpServletResponse res,
import java.awt.*;
HttpServletRequest req) throws IOException{
import java.awt.event.*;
printWriter out = res.getWriter();
import javax.swing.*;
int i, count, num = 20;
/*
while (num&lt;= 100){
<applet code="JAppletDemo.class" width=200 height=200>
i=2;
</applet>
count=0;
*/
while(i&lt;=num/2){
public class JAppletDemo extends JApplet{
if(num%i ==0){
public void init(){
count++;
setLayout(new FlowLayout());
break;
JButton b1=new JButton("Alpha");
}i++;
JButton b2=new JButton("Beta");
if(count == 0){
JLabel label=new JLabel("Press a button");
out.println(num);
b1.addActionListener(new ActionListener() {
}
public void actionPerformed(ActionEvent e) {
num++;
label.setText("You have pressed Alpha");
}}
}
});
Write a swing program to insert data in table using prepared statement.
b2.addActionListener(new ActionListener() {
import java.sql.*;
public void actionPerformed(ActionEvent e) {
class InsertPrepared{
label.setText("You have pressed Beta");
public static void main(String args[]){
} });
try{
add(b1);
Class.forName("oracle.jdbc.driver.OracleDriver");
add(b2);
Connection con=DriverManager.getConnection
add(label);
("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);}
}}

Write a swing program to compute WAP to display record from user_table


that contains (id, username, password and role)
inside database_db.
import java.sql.*;
public class Db{
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); Make an user interface to take name and address of user.
add(b2); import java.awt.*;
add(b3); import java.awt.event.*;
b1.add ActionListener(this); import javax.swing.*;
b2.add ActionListener(this); class First extends JFrame implements ActionListener
b3.add ActionListener(this); {
} JLabel name; JTextField jtf;
public void actionPerformed(ActionEvent e){ JLable address; JTextField jtf2
int a=Integer.ParseInt(t1.getText()); JButton btn;
int b=Integer.ParseInt(t2.getText()); public First(){
if(e.getsource()==b1){ name = new JLable("Enter Name");
int c=a+b; jtf = new JTextField(10);
} address = new JLable("Enter Addres");
if(e.getsource()==b2){ jtf2 = new JTextField(10);
int c=a-b; btn = new JButton("Submit");
} add(name);
if(e.getsource()==b3){ add(jtf);
int c=a*b; add(address);
} add(jtf2);
t3.setText(string.valueof(c)); add(btn);
} setsize(400,400);
public static void main(String[] args) { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new SwingDemo(); setLayout(new FlowLayout());
} setVisible(true);
jb.setActionListener(this);
WAP to illustrate how to use session state in servlet. }
<web-app> public void actionPerformed(ActionEvent ae){
<servlet> First f = new First() ;
<servlet-name>Servlet1</servlet-name> }}
<servlet-class>MyServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
WAP to use java bean in jsp.
<url-pattern>/login</url-pattern>
</servlet-mapping>
Step:1 Create a javaBean (user.java)
<servlet>
public class User {
<servlet-name>Servlet2</servlet-name>
private String name;
<servlet-class>MyServlet2</servlet-class>
public String getName() {
</servlet>
return name;
<servlet-mapping>
}
<servlet-name>Servlet2</servlet-name>
public void setName(String name) {
<url-pattern>/welcome</url-pattern>
this.name = name;
</servlet-mapping>
}}
</web-app>
Step:2 Use the JavaBean in JSP (index .jsp)
<jsp:useBean id="user" class="User" />
Create an applet to draw circle and rectangle
<jsp:setProperty name="user" property="name"
filled with different colour
value="John" />
import java.applet.*;
import java.awt.*; <p>Hello, <jsp:getProperty name="user"
public class DrawShape extends Applet { property="name" />!</p>
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);
}}

You might also like