Advance Java Final
Advance Java Final
Hibernate
Hibernate is ORM (Object-Relation Mapping) framework that allows us
establish communication between Java programming language and the
RDBMS.
Grails
It is a dynamic framework created by using the Groovy programming
language. It is an OOPs language. Its purpose is to enhance the
productivity. The syntax of Grails is matched with Java and the code is
We can use JDBC API to handle database using Java program and can
compiled to JVM. It also works with Java, JEE, Spring and Hibernate.
perform the following activities:
========================================================
• Connect to the database
Difference between Library and framework
• Execute queries and update statements to the database
Library Framework
• Retrieve the result received from the database.
Library is the collection of Framework is the collection of
1) JDBC-ODBC bridge driver frequently used, pre- libraries.
The JDBC-ODBC bridge driver uses ODBC driver to connect to the compiled classes.
database. The JDBC-ODBC bridge driver converts JDBC method calls It is a set of reusable It is a piece of code that dictates
into the ODBC function calls. This is now discouraged because of thin functions used by computer the architecture of your project
driver. programs. and aids in programs.
You are in full control when The code never calls into a
you call a method from a framework, instead the
library and the control is then framework calls you.
returned.
It is in corporate seamlessly It cannot be seamlessly
into existing projects to add incorporated into an existing
functionality that you can project. Instead it can be used
access using an API. when a new project is started.
They are important in They provide a standard way to
program for linking and build and deploy applications. =========================================================
binding process. Differentiate between rowset and resultset
Libraries do no employ an Framework employs an inverted ResultSet RowSet
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The inverted flow of control flow of control between itself
A ResultSet always A RowSet can be connected, disconnected
driver converts JDBC method calls into native calls of the database API. between itself and its clients. and its clients.
maintains connection with from the database.
It is not written entirely in java. Example: jQuery is a Example: Angular JS is a
the database.
JavaScript library that JavaScript-based framework for
It cannot be serialized. A RowSet object can be serialized.
simplifies DOM dynamic web applications.
manipulation. ResultSet object cannot be You can pass a RowSet object over the
========================================================== passed other over network. network.
Write a program object to read personal details from HTML file or ResultSet object is not a ResultSet Object is a JavaBean object.You
another JSP file. JavaBean objectYou can can get a RowSet using
create/get a result set using the RowSetProvider.newFactory().createJdb
the executeQuery() method. cRowSet() method.
By default, ResultSet object By default, RowSet object is scrollable and
is not scrollable or, updatable.
updatable.
==========================================================
3) Network Protocol driver 1. Statement :
The Network Protocol driver uses middleware (application server) that It is used for accessing your database. Statement interface cannot
converts JDBC calls directly or indirectly into the vendor-specific accept parameters and useful when you are using static SQL
database protocol. It is fully written in java. statements at runtime. If you want to run SQL query only once then
this interface is preferred over PreparedStatement.
Example –
//Creating The Statement Object
Statement GFG = con.createStatement();
//Executing The Statement
GFG.executeUpdate("CREATE TABLE STUDENT(ID NUMBER NOT NULL,
NAME VARCHAR)");
2. PreparedStatement :
It is used when you want to use SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific Example –
database protocol. That is why it is known as thin driver. It is fully //Creating the PreparedStatement object
written in Java language. PreparedStatement GFG = con.prepareStatement("update STUDENT
set NAME = ? where ID = ?");
//Setting values to place holders
//Assigns "RAM" to first place holder
GFG.setString(1, "RAM");
//Assigns "512" to second place holder
GFG.setInt(2, 512);
//Executing PreparedStatement
GFG.executeUpdate();
==========================================================
==
-------------------------------------------------à
JDBC Configuration to execute sql Write a program to calculate simple interest using swing? The following JSP program calculates factorial values for an integer
In this example we are using MySql as the database. So we need to know number, while the input is taken from an HTML form.
following information’s for the mysql database: 1) import javax.swing.*;
2) import java.awt.*;
1. Load a JDBC Driver class 3) import java.awt.event.*; input.html
To load a class at runtime into JVM, we need to call a static method 4) public class SimpleIntrest extends JFrame implements
called forName() of java.lang.Class. By calling the forName() method we ActionListener 1) <html>
can load the JDBC Driver class into the JVM. 5) { 2) <body>
3) <form action="Factorial.jsp">
2. Establish a Connection 6) JLabel lblPrinciple = new JLabel("Principle"); 4) Enter a value for n: <input type="text" name="val">
By using the DriverManager class, we can establish the connection to 7) JLabel lblRate = new JLabel("Rate"); 5) <input type="submit" value="Submit">
the database. By calling the getConnection(String url, String user,String 8) JLabel lblTime = new JLabel("Time"); 6) </form>
password) static factory method in DriverManager class, we can obtain 9) JLabel lblResult = new JLabel("Result"); 7) </body>
a Connection object. To get the connection object we need to proved 8) </html>
the connection url as a first parameter and database username and 10) JTextField txtPrinciple = new JTextField();
password as second and third parameters. 11) JTextField txtTime = new JTextField();
12) JTextField txtRate = new JTextField(); Factorial.jsp
3. Create a Statement 13) JTextField txtResult = new JTextField();
Create a Statement : In order to send the SQL commands to database 1) <html>
from our java program, we need Statement object. We can get the 14) SimpleIntrest() 2) <body>
Statement object by calling the createStatement() method on 15) { 3) <%!
connection. 16) setSize(400,500); 4) long n, result;
17) setTitle("Simple Intrest"); 5) String str;
4. Execute Sql queries 18) setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Inorder to execute the SQL commands on database, Statement interface 6) long fact(long n) {
provides provides three different methods: executeUpdate(), 19) setLayout(null); 7) if(n==0)
executeQuery() ,execute(). 8) return 1;
20) JButton btn = new JButton("Compute"); 9) else
5. Process the ResultSet 21) btn.addActionListener(this); 10) return n*fact(n-1);
For the select operations, we use executeQuery() method. The executed 11) }
query returns the data in the form of ResultSet object. To process the 22) lblPrinciple.setBounds(50,20,60,20); 12) %>
data we need to go through the ResultSet. 23) lblTime.setBounds(50,50,60,20); 13) <%
24) lblRate.setBounds(50,80,60,20); 14) str = request.getParameter("val");
6. Close Connection 25) lblResult.setBounds(50,110,60,20); 15) n = Long.parseLong(str);
Last but not least, finally we need to close the connection object. It is 16) result = fact(n);
very important step to close the connection. Else we may get 26) txtPrinciple.setBounds(150,20,100,20); 17) %>
JDBCConnectionException exception. 27) txtTime.setBounds(150,50,100,20); 18) <b>Factorial value: </b> <%= result %>
Conn.close(); 28) txtRate.setBounds(150,80,100,20); 19) </body>
29) txtResult.setBounds(150,110,100,20); 20) </html>
To connect java application with the mysql database, ==========================================================
mysqlconnector.jar file is 30) btn.setBounds(150,140,100,20); Creating Frames using Swings in Java with examples:
required to be loaded. Swing is a part of JFC (Java Foundation Classes). Building Graphical User
download the jar file mysql-connector.jar 31) add(lblPrinciple); Interface in Java requires the use of Swings. Swing Framework contains
32) add(lblTime); a large set of components that allow a high level of customization and
Example 33) add(lblRate); provide rich functionalities and is used to create window-based
import java.sql.*; 34) add(lblResult); applications.
import javax.swing.*; Java swing components are lightweight, platform-independent, provide
public class JDBCProgram { 35) add(txtPrinciple); powerful components like tables, scroll panels, buttons, lists, color
public static void main(String args[]) { 36) add(txtTime); chooser, etc. In this article, we’ll see how to make frames using Swings
try 37) add(txtRate); in Java. Ways to create a frame:
{ 38) add(txtResult); Methods:
//step-1 Load a JDBC Driver class • By creating the object of Frame class (association)
Class.forName("com.mysql.cj.jdbc.Driver"); 39) add(btn); • By extending Frame class (inheritance)
//step-2 Establish a Connection • Create a frame using Swing inside main()
Connection 40) setVisible(true);
conn=DriverManager.getConnection("jdbc:mysql://localhost:3307/tes 41) } JFrame Example
t"); 1) import java.awt.FlowLayout;
//step-3 Create a Statement 42) public void actionPerformed(ActionEvent ae) 2) import javax.swing.JButton;
Statement stmt=conn.createStatement(); 43) { 3) import javax.swing.JFrame;
String sql="select * from student"; 44) int p,t,r; 4) import javax.swing.JLabel;
//step-4 Execute Sql queries 45) float res; 5) import javax.swing.JPanel;
ResultSet rs=stmt.executeQuery(sql); 46) p = Integer.parseInt(txtPrinciple.getText()); 6) public class JFrameExample {
//step-5 Process the ResultSet 47) t = Integer.parseInt(txtTime.getText()); 7) public static void main(String s[]) {
while(rs.next()) 48) r = Integer.parseInt(txtRate.getText()); 8) JFrame frame = new JFrame("JFrame Example");
{ 49) res=(p*t*r)/100; 9) JPanel panel = new JPanel();
System.out.println(rs.getInt(2)+" "+rs.getString(3)+" 50) txtResult.setText(String.valueOf(res)); 10) panel.setLayout(new FlowLayout());
"+rs.getString(4)); 51) } 11) JLabel label = new JLabel("JFrame By Example");
} 12) JButton button = new JButton();
//step-6 Close Connection 52) public static void main(String args[]) 13) button.setText("Button");
conn.close(); 53) { 14) panel.add(label);
} 54) new SimpleIntrest(); 15) panel.add(button);
catch(Exception e) 55) } 16) frame.add(panel);
{ 56) } 17) frame.setSize(200, 300);
JOptionPane.showMessageDialog(null,e); ========================================================== 18) frame.setLocationRelativeTo(null);
} Differentiate between statement and prepared Statement, 19) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS
} Statement PreparedStatement E);
} It is used when SQL query is to It is used when SQL query is to be 20) frame.setVisible(true);
be executed only once. executed multiple times. 21) }
You can not pass parameters at 22) }
runtime. You can pass parameters at runtime.
Used for CREATE, ALTER, DROP Used for the queries which are to be Output:
statements. executed multiple times.
Performance is better than
Performance is very low. Statement.
=============================================== It is base interface. It extends statement interface.
Used to execute normal SQL Used to execute dynamic SQL
queries. queries.
We can not use statement for We can use Preparedstatement for
reading binary data. reading binary data.
It is used for DDL statements. It is used for any SQL Query.
We can not use statement for We can use Preparedstatement for
writing binary data. writing binary data.
No binary protocol is used for Binary protocol is used for
communication. communication.
Explain JCheckBOX and JRadio Button component of Java swing Write a JSP script for enabling and disabling session? 43) Vector v = new Vector();
library? <%@ page language="java" session="false"%> 44) while (rs.next()) {
Java JCheckBox <html> 45) ids = rs.getString(1);
The JCheckBox class is used to create a checkbox. It is used to turn an <head> 46) v.add(ids);
option on (true) or off (false). Clicking on a CheckBox changes its state <title>Session Disabled</title> 47) }
from "on" to "off" or from "off" to "on ".It inherits JToggleButton class. </head> 48) c1 = new JComboBox(v);
<body> 49) c1.setBounds(150, 110, 150, 20);
Java JCheckBox Example <p>Session is Disabled in this page 50) add(c1);
1) import javax.swing.*; </body> 51) st.close();
2) public class CheckBoxExample </html> 52) rs.close();
3) { 53) } catch (Exception e) {
4) CheckBoxExample(){ <%@ page language="java" session="true"%> 54) }
5) JFrame f= new JFrame("CheckBox Example"); <html> 55) }
6) JCheckBox checkBox1 = new JCheckBox("C++"); <head> 56) public void actionPerformed(ActionEvent ae) {
7) checkBox1.setBounds(100,100, 50,50); <title>Session Enabled</title> 57) if (ae.getSource() == b1) {
8) JCheckBox checkBox2 = new JCheckBox("Java", true); </head> 58) showTableData();
9) checkBox2.setBounds(100,150, 50,50); <body> 59) }
10) f.add(checkBox1); <p>Session is Enabled in this page 60) }
11) f.add(checkBox2); </body> 61) public void showTableData() {
12) f.setSize(400,400); </html> 62) frame1 = new JFrame("Database Search Result");
13) f.setLayout(null); ======================================================== 63) frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLO
14) f.setVisible(true); jsp form program to add two numbers . SE);
15) } index.html 64) frame1.setLayout(new BorderLayout());
16) public static void main(String args[]) <html> 65) //TableModel tm = new TableModel();
17) { <head> 66) DefaultTableModel model = new DefaultTableModel();
18) new CheckBoxExample(); <title>calculator </title> 67) model.setColumnIdentifiers(columnNames);
<meta charset=”UTF-8”>
19) }} 68) //DefaultTableModel model = new
<meta name=”viewportal” content = “width=device-width,initial-scale=1.0”>
DefaultTableModel(tm.getData1(),
</head>
Java JRadioButton <body> tm.getColumnNames());
The JRadioButton class is used to create a radio button. It is used to <form action =”add.jsp”> 69) //table = new JTable(model);
choose one option from multiple options. It is widely used in exam Enter first number : <input type=”text” name=”num1”><br><br> 70) table = new JTable();
systems or quiz. Enter second number:<input type=”text” name=”num2”><br><br> 71) table.setModel(model);
It should be added in ButtonGroup to select one radio button only. <input type=”submit” value=”sum”> 72) table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_CO
</body> LUMNS);
Java JRadioButton Example </html> 73) table.setFillsViewportHeight(true);
1) import javax.swing.*; 74) JScrollPane scroll = new JScrollPane(table);
2) public class RadioButtonExample { JSP for adding two number : add.jsp 75) scroll.setHorizontalScrollBarPolicy(
3) JFrame f; 76) JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
<html>
4) RadioButtonExample(){ 77) scroll.setVerticalScrollBarPolicy(
<head>
5) f=new JFrame(); <meta http-equiv="Content-type" content="text/html; charset=UTF-8"> 78) JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
6) JRadioButton r1=new JRadioButton("A) Male"); <title>JSP page for result sum </title> 79) from = (String) c1.getSelectedItem();
7) JRadioButton r2=new JRadioButton("B) Female"); </head> 80) //String textvalue = textbox.getText();
8) r1.setBounds(75,50,100,30); <body> 81) String uname = "";
9) r2.setBounds(75,100,100,30); <h1>sum</h1> 82) String email = "";
10) ButtonGroup bg=new ButtonGroup(); <%=”<h4>sum is “ + (Integer.parseInt(request.getParameter(“num1”))+ 83) String pass = "";
11) bg.add(r1);bg.add(r2); Integer.parseInt(request.getParameter(“num2”)))+”</h4>”%> 84) String cou = "";
12) f.add(r1);f.add(r2); </body> 85) try {
13) f.setSize(300,300); </html> 86) pst = con.prepareStatement("select * from emp where
14) f.setLayout(null); ========================================================== UNAME='" + from + "'");
15) f.setVisible(true); write a swing program to connect database and display 87) ResultSet rs = pst.executeQuery();
16) } student/employee details in Jtable. 88) int i = 0;
17) public static void main(String[] args) { 1) import java.awt.*; 89) if (rs.next()) {
18) new RadioButtonExample(); 2) import java.awt.event.*; 90) uname = rs.getString("uname");
19) } 3) import java.sql.*; 91) email = rs.getString("umail");
20) } 4) import java.util.Vector; 92) pass = rs.getString("upass");
========================================================== 5) import javax.swing.*; 93) cou = rs.getString("ucountry");
What is javabean ?how it is different from java class? 6) import javax.swing.table.DefaultTableModel; 94) model.addRow(new Object[]{uname, email, pass, cou});
A JavaBean is a Java class that follows a certain standard: 7) public class DisplayEmpData extends JFrame 95) i++;
• JavaBean class properties should be set to private – implements ActionListener { 96) }
accessing /mutating these properties is done using 8) JFrame frame1; 97) if (i < 1) {
getters/setters methods. 9) JLabel l0, l1, l2; 98) JOptionPane.showMessageDialog(null, "No Record
10) JComboBox c1; Found", "Error", JOptionPane.ERROR_MESSAGE);
• A JavaBean class should have a public no-argument
11) JButton b1; 99) }
constructor.
12) Connection con; 100) if (i == 1) {
• A JavaBean class should implement the
13) ResultSet rs, rs1; 101) System.out.println(i + " Record Found");
java.io.Serializable interface. The Serializable interface
14) Statement st, st1; 102) } else {
allows the saving, storing, and restoring of a JavaBean’s
15) PreparedStatement pst; 103) System.out.println(i + " Records Found");
state while in use.
16) String ids; 104) }
The only difference between both the classes is Java make java beans
17) static JTable table; 105) } catch (Exception ex) {
objects serialized so that the state of a bean class could be preserved in
18) String[] columnNames = {"User name", "Email", 106) JOptionPane.showMessageDialog(null, ex.getMessage(),
case required.So due to this a Java Bean class must either implements
"Password", "Country"}; "Error", JOptionPane.ERROR_MESSAGE);
Serializable or Externalizable interface.
19) String from; 107) }
20) DisplayEmpData() { 108) frame1.add(scroll);
Example of javabeans
21) l0 = new JLabel("Fatching Employee Information"); 109) frame1.setVisible(true);
public class Employee implements java.io.Serializable {
22) l0.setForeground(Color.red); 110) frame1.setSize(400, 300);
private int id;
23) l0.setFont(new Font("Serif", Font.BOLD, 20)); 111) }
private String name;
24) l1 = new JLabel("Select name"); 112) public static void main(String args[]) {
public Employee(){}
25) b1 = new JButton("submit"); 113) new Displaystudent Data();
public void setId(int id){this.id=id;}
26) l0.setBounds(100, 50, 350, 40); 114) }
public int getId(){return id;}
27) l1.setBounds(75, 110, 75, 20); 115) }
public void setName(String name){this.name=name;}
28) b1.setBounds(150, 150, 150, 20);
}
public String getName(){return name;}
29) b1.addActionListener(this); =========================
30) setTitle("Fetching Student Info From DataBase");
31) setLayout(null);
32) setVisible(true);
33) setSize(500, 500);
34) setDefaultCloseOperation(WindowConstants.EXIT_ON_
CLOSE);
35) add(l0);
36) add(l1);;
37) add(b1);
38) try {
39) Class.forName("oracle.jdbc.driver.OracleDriver");
40) con =
DriverManager.getConnection("jdbc:oracle:thin:@mcnd
esktop07:1521:xe", "sandeep", "welcome");
41) st = con.createStatement();
42) rs = st.executeQuery("select uname from emp");-------à
Write a swing program to get two number input using two text field 24) out.println("<td>"+rs.getString(2)+"</td>"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3307/tes
and multiply it by clicking button and display it in third text field. 25) out.println("<td>"+rs.getString(3)+"</td>"); t","root","");
1) import java.awt.FlowLayout; 26) out.println("<td>"); String sql="delete from tblstd where RollNo=?";
2) import java.awt.event.*; 27) out.println("</td>"); PreparedStatement ptst=conn.prepareStatement(sql);
3) import javax.swing.*; 28) out.println("</tr>"); ptst.setInt(1,
4) public class MultiplyUsingSwing extends JFrame 29) } Integer.parseInt(txtRollno.getText()));
implements ActionListener { 30) out.println("</table> ptst.executeUpdate();
5) JLabel l1 = new JLabel("First No:"); 31) </body> if(ptst.getUpdateCount()>0)
6) JTextField t1 = new JTextField(10); 32) </html>") JOptionPane.showMessageDialog(null,"Data deleted
7) JLabel l2 = new JLabel("Second No:"); Successfully");
8) JTextField t2 = new JTextField(10); ========================================================== Found");
9) JTextField t3 = new JTextField(10); }}
10) JButton b = new JButton("Multiply"); );
11) String fno = ""; else
12) String sno = ""; JOptionPane.showMessageDialog(null,"Data not
13) public MultiplyUsingSwing() { conn.close();
14) setLayout(new FlowLayout()); }
15) setSize(250, 250); catch(Exception e)
16) setVisible(true); {
17) setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JOptionPane.showMessageDialog(null, ae);
18) add(l1); }
19) add(t1); btnUpdate.addActionListener(new ActionListener()
20) add(l2); {
import java.awt.event.*;
21) add(t2); public void actionPerformed(ActionEvent ae)
import javax.swing.*;
22) t3.setEditable(false); {
import javax.swing.event.*;
23) add(t3); try
import java.sql.*;
24) add(b); {
public class AllOp
25) b.addActionListener(this); Class.forName("com.mysql.cj.jdbc.Driver");
{
26) } Connection
AllOp() {
27) @Override conn=DriverManager.getConnection("jdbc:mysql://localhost:3307/tes
JFrame f=new JFrame();
28) public void actionPerformed(ActionEvent e) { t","root","");
JLabel lblRollno=new JLabel("Roll Number");
29) int f = Integer.parseInt(t1.getText()); String sql="update tblstd set
lblRollno.setBounds(10, 10, 150, 20);
30) int s = Integer.parseInt(t2.getText()); RollNo=?,Name=?,Address=? where RollNo=?";
f.add(lblRollno);
31) int r = f * s; PreparedStatement ptst=conn.prepareStatement(sql);
JTextField txtRollno=new JTextField();
32) t3.setText("" + r); ptst.setInt(1,
txtRollno.setBounds(100, 10, 150, 20);
33) } Integer.parseInt(txtRollno.getText()));
f.add(txtRollno);
34) public static void main(String[] args) { ptst.setString(2, txtName.getText());
JLabel lblName=new JLabel("Name");
35) new MultiplyUsingSwing(); ptst.setString(3, txtAddress.getText());
lblName.setBounds(10, 40, 150, 20);
36) } ptst.setInt(4,
f.add(lblName);
37) } Integer.parseInt(txtRollno.getText()));
JTextField txtName=new JTextField();
========================================================== ptst.executeUpdate();
txtName.setBounds(100, 40, 150, 20);
Write a swing program to read two input user using input dialog and if(ptst.getUpdateCount()>0)
f.add(txtName);
sum those values and display it using message dialog. JOptionPane.showMessageDialog(null,"Data Updated
JLabel lblAddress=new JLabel("Address");
1) /* Successfully");
lblAddress.setBounds(10, 70, 150, 20);
2) To change this license header, choose License Headers found");
f.add(lblAddress);
in Project Properties. else
JTextField txtAddress=new JTextField();
3) To change this template file, choose Tools | Templates JOptionPane.showMessageDialog(null,"Data not
txtAddress.setBounds(100, 70, 150, 20);
4) and open the template in the editor. conn.close();
f.add(txtAddress);
5) */ }
JButton btnInsert=new JButton("Insert");
6) package inputdialogexample; catch(Exception e)
btnInsert.setBounds(20, 110, 80, 20);
7) import javax.swing.*; {
f.add(btnInsert);
8) /** JOptionPane.showMessageDialog(null, ae);
JButton btnDelete=new JButton("Delete");
9) * }
btnDelete.setBounds(110, 110, 80, 20);
10) @author DELL }}
f.add(btnDelete);
11) */ );
JButton btnUpdate=new JButton("Update");
12) public class InputDialogExample { btnSearch.addActionListener(new ActionListener()
btnUpdate.setBounds(200, 110, 80, 20);
{
f.add(btnUpdate);
13) /** public void actionPerformed(ActionEvent ae)
JButton btnSearch=new JButton("Search");
14) @param args the command line arguments {
btnSearch.setBounds(290, 110, 80, 20);
15) */ try
f.add(btnSearch);
16) public static void main(String[] args) { {
btnInsert.addActionListener(new ActionListener()
17) int num,num1; Class.forName("com.mysql.cj.jdbc.Driver");
{
18) num=Integer.parseInt(JOptionPane.showInputDialog(" Connection
public void actionPerformed(ActionEvent ae)
Enter first values")); conn=DriverManager.getConnection("jdbc:mysql://localhost:3307/tes
{
19) num1=Integer.parseInt(JOptionPane.showInputDialog(" t","root","");
try
Enter second values")); String sql="select * from tblstd where RollNo=?";
{
20) JOptionPane.showMessageDialog(null,(num+num1)); PreparedStatement ptst=conn.prepareStatement(sql);
Class.forName("com.mysql.cj.jdbc.Driver");
21) } ptst.setInt(1,
Connection
Integer.parseInt(txtRollno.getText()));
conn=DriverManager.getConnection("jdbc:mysql://localhost:3307/tes
22) } ResultSet rs=ptst.executeQuery();
t","root","");
========================================================== if(rs.next())
String sql="insert into tblStd
Write a servlet program to select students id name age from student {
(ID,RollNo,Name,Address) values(NULL,?,?,?)";
table and display in html table. txtName.setText(rs.getString("Name"));
PreparedStatement ptst=conn.prepareStatement(sql);
txtAddress.setText(rs.getString("Address"));
ptst.setInt(1,
1) public void doGet(HttpServletRequest req, }
Integer.parseInt(txtRollno.getText()));
HttpServletResponse res) else
ptst.setString(2, txtName.getText());
2) throws ServletException,IOException{ {
ptst.setString(3, txtAddress.getText());
3) res.setContentType("text/html"); Found");
ptst.executeUpdate();
4) PrintWriter out=res.getWriter(); }
if(ptst.getUpdateCount()>0)
5) //selecting data }}
JOptionPane.showMessageDialog(null,"Data inserted
6) try { );
Successfully");
7) Connection conn=DbConnection.getConn(); JOptionPane.showMessageDialog(null,"Data not
conn.close();
8) String sql="SELECT * FROM employees"; conn.close();
}}
9) PreparedStatement pst=conn.prepareStatement(sql); }
);
10) ResultSet rs=pst.executeQuery(); catch(Exception e)
}
11) out.println("<html><body>"); {
catch(Exception e)
12) out.println("<a href='index.html'> JOptionPane.showMessageDialog(null, ae);
{
13) Goto Index </a> <br><br>"); }
JOptionPane.showMessageDialog(null, ae);
14) //displaying data f.setSize(400,500);
}
15) out.println("<table>"); f.setLayout(null);
btnDelete.addActionListener(new ActionListener()
16) out.println("<tr>"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
{
17) out.println("<th> Eid </th>"); f.setVisible(true);
public void actionPerformed(ActionEvent ae)
18) out.println("<th> Name </th>"); }
{
19) out.println("<th> Address </th>"); public static void main(String args[])
try
20) out.println("</tr>"); {
{
21) while(rs.next()) { new AllOp();
Class.forName("com.mysql.cj.jdbc.Driver");
22) out.println("<tr>"); }}
Connection
23) out.println("<td>"+rs.getInt(1)+"</td>"); ==========================================================
How JSP is differing from servlet? Write JSP program to display " 13) JInternalFrame frame1 = new JInternalFrame("Frame 1", Difference between session and cookie. WAP ti implement session.
Tribhuvan University" 10 times. true, true, true,
Session Cookie
Servlets are faster as compared to JSP, as they have a short response 14) true);
time. JSP is slower than Servlets, as the first step in the JSP lifecycle is 15) JInternalFrame frame2 = new JInternalFrame("Frame 2",
the conversion of JSP to Java code and then the compilation of the code. true, true, true, Server side files that contain Client side files on a local
Servlets are Java-based codes. JSP are HTML-based codes. In Servlet we 16) true); user data computer that hold user
have to implement everything like business logic and presentation logic 17) frame1.getContentPane().add(new JLabel("Frame 1 information
in just one servlet file.In JSP business logic is separated from contents..."));
presentation logic by using JavaBeansclient-side. 18) frame1.pack(); It can hold an indefinite It can only store a certain
19) frame1.setVisible(true); quantity of data amount of info.
Program: 20) frame2.getContentPane().add(new JLabel("Frame 2
<!DOCTYPE html> contents..."));
They are more secured. They are not secured.
<html> 21) frame2.pack();
<head> 22) frame2.setVisible(true);
<meta http-equiv=“Content-Type” content=“text/htm; charset=UTF- 23) int x2 = frame1.getX() + frame1.getWidth() + 10; Store data in text file. Save data in encrypted form.
8”> 24) int y2 = frame1.getY();
<title> JSP program to display “Tribhuvan University” 10 25) frame2.setLocation(x2, y2); They have maximum They have maximun memory of
times</title> 26) desktopPane.add(frame1); capacity of 4KB 128KB
</head> 27) desktopPane.add(frame2);
<body> 28) this.add(desktopPane, BorderLayout.CENTER); 1) import java.io.*;
<h1> Displaying “Tribhuvan University” 10 times!!</h1> 29) this.setMinimumSize(new Dimension(300, 300)); 2) import java.util.*;
<table> 30) } 3) import javax.servlet.*;
<% 31) public static void main(String[] args) { 4) import javax.servlet.http.*;
for(int i=1; i<=10; i++){ 32) try { 5) @WebServlet("/test_session")
%> 33) UIManager.setLookAndFeel(UIManager.getSystemLook 6) public class TestSessionServlet extends HttpServlet {
<tr><td> Tribhuvan University</td></tr> AndFeelClassName()); 7) private static final long serialVersionUID = 1L;
<% } %> 34) } catch (Exception e) { 8) public TestSessionServlet() {
</table> 35) e.printStackTrace(); 9) super();
</body> 36) } 10) }
</html> 37) SwingUtilities.invokeLater(() -> { 11) protected void doGet(HttpServletRequest request,
========================================================== 38) Main frame = new Main(); HttpServletResponse response)
How to develop MDI application on java explain? 39) frame.pack(); 12) throws ServletException, IOException {
MDI stands for Multiple Document Interface. In an MDI application, one 40) frame.setVisible(true); 13) HttpSession session = request.getSession();
main window is opened, and multiple child windows are open within the 41) frame.setExtendedState(frame.MAXIMIZED_BOTH); 14) PrintWriter writer = response.getWriter();
main window. 42) }); 15) writer.println("Session ID: " + session.getId());
In an MDI application, we can open multiple frames that will be 43) } 16) writer.println("Creation Time: " + new
instances of the JInternalFrame class. 44) } Date(session.getCreationTime()));
We can organize multiple internal frames in many ways. For example, ========================================================== 17) writer. println("Last Accessed Time: " + new
we can maximize and minimize them; we can view them side by side in What are JTextField and JTextArea in Java? Date(session.getLastAccessedTime()));
a tiled fashion, or we can view them in a cascaded form. JTextField 18) }
The following are four classes we will be working with in an MDI A JTextFeld is one of the most important components that allow the user 19) }
application: to an input text value in a single line format. A JTextField will generate ==========================================================
• JInternalFrame an ActionListener interface when we trying to enter some input inside WAP to calculate sum of any two number using rmi.
• JDesktopPane it. The important methods in the JTextField class are setText(), getText(), 1) Adder.interface
setEnabled(), etc. 2) import java.rmi.Remote;
• DesktopManager
3) import java.rmi.RemoteException;
• JFrame 4) public interface Adder extends Remote{
An instance of the JInternalFrame class acts as a child window that is Example 5) void Add(Integer a,Integer b) throws RemoteException;
displayed inside the area of its parent window. 1) import javax.swing.*; 6) }
We can add Swing components to JInternalFrame content pane, pack 2) import java.awt.*; 7) ImplExample.java
3) public class JTextFieldTest {
them using the pack() method, and make it visible using the 8) public class ImplExample implements Adder{
4) public static void main(String[] args) { 9) ImplExample()
setVisible(true) method.
5) final JFrame frame = new JFrame("JTextField Demo"); 10) {
To listen to window events such as activated, deactivated, etc., we need 6) JLabel lblFirstName = new JLabel("First Name:");
to add an InternalFrameListener to the JInternalFrame instead of a 11) super();
7) JTextField tfFirstName = new JTextField(20); 12) }
WindowListener, which is used for a JFrame. 8) lblFirstName.setLabelFor(tfFirstName); 13) public void Add(Integer x,Integer y) {
The following code shows how to use an instance of the JInternalFrame 9) JLabel lblLastName = new JLabel("Last Name:"); 14) System.out.println("sum = "+(x+y));
class: 10) JTextField tfLastName = new JTextField(20); 15) }
String title = "A Child Window"; 11) lblLastName.setLabelFor(tfLastName); 16) }
Boolean resizable = true; 12) JPanel panel = new JPanel(); 17) ServerRMI.java
Boolean closable = true; 13) panel.setLayout(new FlowLayout()); 18) import java.rmi.registry.Registry;
Boolean maximizable = true; 14) panel.add(lblFirstName); 19) import java.rmi.registry.LocateRegistry;
15) panel.add(tfFirstName); 20) import java.rmi.RemoteException;
Boolean iconifiable = true;
16) panel.add(lblLastName); 21) import java.rmi.server.UnicastRemoteObject;
JInternalFrame iFrame = new JInternalFrame(title, resizable, closable,
17) panel.add(tfLastName); 22) public class ServerRMI extends ImplExample{
maximizable, iconifiable); 18) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Add components to the iFrame using public ServerRMI() {}
19) frame.setSize(300, 100); public static void main(String args[]) {
iFrame.add(...) 20) frame.getContentPane().add(panel, BorderLayout.CENTER); try {
Pack eth frame and make it visible 21) frame.setVisible(true); 23) ImplExample obj = new ImplExample();
iFrame.pack(); 22) } 24) Hello skeleton =(Hello)
iFrame.setVisible(true); 23) } UnicastRemoteObject.exportObject(obj, 0);
JDesktopPane is used as a container for all JInternalFrame. It uses a null 25) Registry registry = LocateRegistry.getRegistry();
layout manager. JTextArea 26) registry.bind("RMITest",skeleton);
JDesktopPane desktopPane = new JDesktopPane(); A JTextArea is a multi-line text component to display text or allow the user to 27) System.err.println("server Ready");
enter text. A JTextArea will generate a CaretListener interface. 28) }
// Add all JInternalFrames to the desktopPane
The important methods in the JTextArea class are setText(), append(), 29) catch(Exception e) {
desktopPane.add(iFrame);
setLineWrap(), setWrapStyleWord(), setCaretPosition(), etc. 30) System.err.println("Server Exception:"+ e.toString());
We can get all JInternalFrames that are added to a JDesktopPane using Example
its getAllFrames() method. 31) e.printStackTrace();
1) import java.awt.*; 32) }
JInternalFrame[] frames = desktopPane.getAllFrames(); 2) import javax.swing.*; 33) }
A JDesktopPane uses an instance of the DesktopManager interface to 3) import javax.swing.event.*; 34) }
manage all internal frames. 4) public class JTextAreaTest { 35) ClientRMI.java
The DefaultDesktopManager implements DesktopManager interface. 5) public static void main(String args[]) { 36) import java.rmi.registry.LocateRegistry;
The desktop manager has many useful methods. For example, to close 6) JFrame frame = new JFrame("JTextArea Example"); 37) import java.rmi.registry.Registry;
an internal frame programmatically, use its closeFrame() method. 7) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 38) public class ClientRMI{
desktopPane.getDesktopManager().closeFrame(frame1); 8) JTextArea textArea = new JTextArea(); 39) private ClientRMI() {}
9) JScrollPane scrollPane = new JScrollPane(textArea); 40) public static void main(String[] args) {
10) frame.add(scrollPane, BorderLayout.CENTER); 41) try {
The following code demonstrates how to develop an MDI application.
11) CaretListener listener = new CaretListener() { 42) Registry registry = LocateRegistry.getRegistry();
1) import java.awt.BorderLayout; 12) public void caretUpdate(CaretEvent caretEvent) {
2) import java.awt.Dimension; 43) Hello stub = (Hello) registry.lookup("RMITest");
13) System.out.println("Dot: "+ caretEvent.getDot()); 44) stub.Add(5,10);
3) /*from w w w. j av a2 s. co m*/ 14) System.out.println("Mark: "+caretEvent.getMark()); 45) }
4) import javax.swing.JDesktopPane; 15) } 46) catch(Exception e) {
5) import javax.swing.JFrame; 16) }; 47) System.err.println("Client Exception:"+e.toString());
6) import javax.swing.JInternalFrame; 17) textArea.addCaretListener(listener); 48) }
7) import javax.swing.JLabel; 18) frame.setSize(250, 150); 49) }
8) import javax.swing.SwingUtilities; 19) frame.setVisible(true); 50) }
9) import javax.swing.UIManager; 20) } ===============================================================
21) }
10) public class Main extends JFrame {
11) private final JDesktopPane desktopPane = new
==============================================================
JDesktopPane();
12) public Main() {
Write a swing program to show color panel using dialog box Write a GUI program to create table , insert and show 38) san..getDefaultCloseOperation (Frame. EXIT_ON_CLOSE);
to get color. product information which include id, name and price. 39) }
1. import java.awt.Color; o import java.sql.*; 40) public void actionPerformed(ActionEvent e){
2. import java.awt.event. o public class CreateProductTable{ 41) if(e.getsource).equals(btnregister)){
3. import javax.swing.*; o public static void main (String [] args){ 42) JOptionPane.showMessageDialog(frame,”you have
4. public class ShowColor implements ActionListener o try{ registered your information”);
5. Button btn; o Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriv 43) String tname=txtname.getText();
6. Color color; er"); 44) taddress=txtaddress.getText()
7. Panel panel; o String DB URL="jdbc: sqlserver://<usernames> \\ 45) String taddress=txtaddress.getText():
8. Frame frame; SQLEXPRESS2:1433;databaseName=BCA 46) String tlevel=txtlevel.getText():
9. public void showColor() { ;integratedSecurity=true;”; 47) createNewForm (tame, taddress,tlevel):
10. panel=new JPanel () ; o Connection con = DriverManager. getConnection( DB URL) ; 48) }
11. panel.setBackground (color) ; o System. out.println ("Database connected..."); 49) void createNewForm(String tname,String address, String
12. btn=new JButton ("Change color') ; o Statement statement = con.createStatement () ; tlevel){
13. btn.addActionlistener (this) ; o String sql="CREATE TABLE PRODUCT (ID VARCHAR (10) , 50) lblname = new JLabel (“Name:”);
14. panel.add (btn); NAME VARCHAR (30) , PRICE FLOAT, PRIMARY KEY (ID)) ;"; 51) lbladdress = new JLabel(“Address:”);
15. Frame = New JFrame(“sample frame”); o statement.executeUpdate ( sql); 52) lbllevel = new JLabel(“Level:);
16. frame.getContentPane () .add (panel) ; o } 53) lname= new JLabel();
17. frame.setSize (500, 500) ; o catch ( Exception e) 54) laddress=newJLabel();
18. frame.setLocationRelativeTo(null); o { 55) llevel =newJLabel();
19. frame.setVisible (true) ; o e.printstackTrace(); 56) Iname.setText (tname) :
20. frame.setDefaultCloseOperation (JFrame.EXIT ON CLOSE); o }}} 57) laddress.setText(taddress):
21. } o public class InsertProduct{ 58) llevel.setText(tlevel);
23. Public void actionPerformed(ActionEvent e) o public static void main (String[ ] args)( 59) lblname.setBounds (10, 20, 80, 25) ;
25. Color = JColorChooser.showDialog(frame,”choose a color o try{ 60) lbladdress.setBounds (10, 60,80,25);
“, color ); o String DB URL="jdbc:sqlserver: / /<username>\ 61) lbllevel.setBounds (10, 100,80,25);
26. If (color =null). color=color.LIGTH_GRAY; \(SQLEXPRESS 2: 1433; databaseName-BCA; 62) lblname.setBounds(100,20,160,25);
28. panel.setBackground(color); integratedSecurity=true;"; 63) lbladdress.setBounds (10, 60,80,25);
29. } o Connection con = DriverManager. getConnection( DB_URL) ; 64) level.setBounds(100,100,160,25);
30. public static void main (String args[]){ o System. out.println ("Database connected") ; 65) JPanel panel =new JPanel();
31. ShowColor show=new ShowColor(); o Statement statement = con.createStatement(); 66) panel.setLayout(null);
32. show. showColor(); o String sql="INSERT INTO PRODUCT VALUES ('A102', 'pant', 67) panel.setLayout(null);
33. } 950) ; "; 68) panel.add(lblname);
34. } o statement. executeUpdate ( sql): 69) panel.add(lbladdress);
================================================== o Catch (Exception e) 70) panel.add(lbllevel);
Write a program to show font. o { 71) panel.add(lname);
o e.printStackTrace(); 72) panel.add(laddress);
1) import java.awt.Color; o } 73) panel.add(llevel);
2) import java.awt.Font; o } 74) JFrame frame = new JFrame (“Data entry Form…”);
3) import java.awt.Graphics; o } 75) frame.add (panel);
4) import javax.swing.JPanel; o public class ViewProduct{ 76) frame.setSize(300,240);
5) public Class Fonts { o public static void main (String[]args){ 77) frame.setlocationRelativeTo (null) ;
6) public static void main (String args[]) o try{ 78) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
7) { o Class. 79) frame.setVisible (true) ;
8) JFrame frame=new Frame ("Font styles..”); forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 80) }
9) frame.add (new FontExample()); o String DB URL="idbc: sqlserver://<username>\\ 81) Public static void main (Sting args[]){
10) frame.setSize(480,150); SQLEXPRESS2:1433; 82) InformationformForm info=new InformationForm() ;
11) frame.setlocationRelativeTo(null) ; databaseName=BCA;integratedSecurity-true;"; 83) info.createForm();
12) frame.setDefaultCloseOperation(JFrame.EXIT ON o Connection con = DriverManager. getConnection( DB_URL) ; 84) }
CLOSE) ; o System. out.println ("Database connected...") ; 85) }
13) frame. getVisible(true); o Statement statement= con. createStatement () ; ===============================================================
14) } o String sql="SELECT * FROM PRODUCI;"; Write servlet program to add two number.
15) } o ResultSet rs=statement.executeQuery (sql) ; Index.html
16) public class FontExample extends JPanel{ o String id,name,price; <!DOCTYPE html>
17) public void paint (Graphics g) { o while(rs.next()) <html>
18) g.setFont (new Font ("Arial", Font.BOLD, 12)) ; o { <head>
19) g.drawString ("This is a sample text", 20, 30) ; o id= rs.getString(“ID”); <title>Practical Work</title>
20) g. setFont (new Font ("Serif",Font.ITALIC, 18)) ; o name=rs.getString(“Name”); </head>
21) g. drawString ("This is another sample text", 20, 60); o Price = rs.getString(“PRICE”); <body>
22) g. setColor (Color.RED) o System.out.println(id+”\t”+name+”\”+price); <form action="add_me">
23) g.setFont (new Font ("Monospaced", Font.BOLD, 20) ) o } <label>First number </label> <input type="text" name="num1"/> <br/><br/>
; o }catch (Exception e ) <label>Second number </label> <input type="text" name="num2"/>
24) g. drawString ("This is again, another sample text", o { <br/><br/>
20, 90) : o e.printStackTrack(); <button type="submit" name="calculate">Product and Sum </button><br/>
25) } o } </form>
26) } o } </body>
================================================== o } </html>
Write program to create Different shapes. ==================================================
1) import java.awt.Color; Write a program using jdbc to enter and display data to the Add_Numbers.java
2) import java.awt.Graphics; database. package com.programmerbay;
3) import javax.swing.JPanel; 1) Import javax. swing.*; import java.io.IOException;
4) public class DrawShapes 2) Import java.awt.event.*; import java.io.PrintWriter;
5) { 3) public class InformationForm implements ActionListener{
6) public static void main (String args[]) 4) JLabel lblname, lbladdress, lbllevel, Iname, laddress, llevel; import javax.servlet.http.*;
7) { 5) JTextfield txtname, txtaddress,txtlevel; public class Add_Numbers extends HttpServlet{
8) Frame frame=new Frame ("Sample shapes."); 6) JButton btnregister; public void service(HttpServletRequest request,HttpServletResponse
9) frame.add(new Draw()); 7) JPanel panel; response) throws IOException
10) frame.setSize (400, 200) . 8) Jfarme frame; {
11) frame. setLocationRelativeTo (null); 9) void createForm() { int num1 = Integer.parseInt(request.getParameter("num1"));
12) frame.setDefaultCloseOperation (JFrame.EXIT ON 10) lblname= new JLabel(“Name”); int num2 = Integer.parseInt(request.getParameter("num2"));
CLOSE) ; 11) Lbladress= new JLabel(“address:”); int sum = num1 + num2;
13) frame.setvisible(true) 12) Lbllevel = new JLabel(“Level:”); int product = num1 * num2;
14) } 13) txtname = new JTextField(); PrintWriter output = response.getWriter();
15) } 14) txtadress = new JtextField(10); output.println("The Answer :"+sum +"\n The product :"+product);
16) public class Draw extends JPanel{ 15) txtlevel =new JTextField(10); }
17) public void paint (Graphics g) { 16) btnregister = newButton ( “register”); }
18) g. setColor (Color.RED) ; 17) btnregister.addActionlistener(this); Web.xml
19) g. drawLine(5,30,380,30); 18) lblname.setBounds(10,20,80,25); <?xml version="1.0" encoding="UTF-8"?>
20) g. setColor (Color. BLUE) ; 19) lbladdress.setBounds(10,60,80,25); <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
21) g. drawRect (5,40, 90,55) : 20) lbllevel.setBounds(10,100,80,25) ; xmlns="http://xmlns.jcp.org/xml/ns/javaee"
22) g. fillRect (100, 40, 90,55) ; 21) txtname. setBounds(100, 20,160,25); xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
23) g.setColor (Color. GREEN) 22) txtaddress.setBounds(100,100,160,25); http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID"
24) g. drawOval (195, 40, 90, 23) txtlevel.setBounds(100,100,160,25); version="3.1">
25) g. filloval (290, 40, 90, 55) : 24) btnregister.setBounds(100,150,80,25);
26) g. setColor (Color. CYAN) ; 25) JPanel panel=new Jpanel(); <servlet>
27) g. fillOval (5, 100, 90, 90) ; 26) panel.setlayout(null); <servlet-name>Add</servlet-name>
28) } 27) panel.ad(lblname); <servlet-class>com.programmerbay.Add_Numbers</servlet-class>
29) } 28) panel.add (lbladdress); </servlet>
=============================================================== 29) panel.add (lbllevel); <servlet-mapping>
30) panel.add (txtname); <servlet-name>Add</servlet-name>
31) panel.add (txtaddress); <url-pattern>/add_me</url-pattern>
32) panel.add (txtlevel); </servlet-mapping>
33) panel.add (btnregister); </web-app>
34) JFrame= new uFrame ("Data entry Form frame….”); ===============================================================
35) frame.add (panel); ======
36) frame. setSize(300,240);
37) frame.setlocationRelativeTo(null):