Showing posts with label Advanced JAVA. Show all posts
Showing posts with label Advanced JAVA. Show all posts
Saturday, 19 September 2015
Introduction about Servlet
Servlet is used to create web application, Servlet is robust and scalable because of java language, Servlet is a server-side programming language. it was many advantages of this technology compare to CGI (Common Gateway Interface)
Interfaces and classes in the servlet API
- Servlet
- GenericServlet
- HttpServlet
- ServletRequest
- ServletResponse
CGI(Commmon Gateway Interface) Vs Servlet
CGI
Disadvantage
- If number of clients increases, it takes more time for sending response.
- For each request, it starts a process and Web server is limited to start processes.
Servlet
Advantage
- Servlet creates a thread for each request not process.
- Servlets are managed by JVM so no need to worry about momory leak, garbage collection other services.
Friday, 7 August 2015
Client Server Communication using UDP
UDP_Server.java
import java.net.*;
import java.io.*;
public class UDP_Server {
public static void main(String args[]) {
DatagramSocket dgSocket = null;
if (args.length < 1) {
System.out.println("UDP_Server");
System.exit(1);
}
try {
int socket_no = Integer.valueOf(args[0]).intValue();
dgSocket = new DatagramSocket(socket_no);
byte[] buffer_array = new byte[1000];
while (true) {
DatagramPacket request = new DatagramPacket(buffer_array, buffer_array.length);
dgSocket.receive(request);
DatagramPacket reply = new DatagramPacket(request.getData(), request.getLength(), request.getAddress(), request.getPort());
dgSocket.send(reply);
}
} catch (SocketException e) {
System.out.println("Socket : " + e.getMessage());
} catch (IOException e) {
System.out.println("i/o: " + e.getMessage());
} finally {
if (dgSocket != null) {
dgSocket.close();
}
}
}
}
UDP_Client.java
import java.net.*;
import java.io.*;
public class UDP_Client {
public static void main(String args[]) {
DatagramSocket dgSocket = null;
if (args.length < 3) {
System.out.println("UDP_Client ");
System.exit(1);
}
try {
dgSocket = new DatagramSocket();
byte[] m = args[0].getBytes();
InetAddress hostAdr = InetAddress.getByName(args[1]);
int serverPort = Integer.valueOf(args[2]).intValue();
DatagramPacket request
= new DatagramPacket(m, args[0].length(), hostAdr, serverPort);
dgSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket dgRreply = new DatagramPacket(buffer, buffer.length);
dgSocket.receive(dgRreply);
System.out.println("Reply: " + new String(dgRreply.getData()));
} catch (SocketException e) {
System.out.println("Socket: " + e.getMessage());
} catch (IOException e) {
System.out.println("i/o " + e.getMessage());
} finally {
if (dgSocket != null) {
dgSocket.close();
}
}
}
}
Wednesday, 15 July 2015
Client Server Communication using TCP
TcpServer.java
import java.io.*;
import java.net.*;
public class TcpServer {
public static void main(String[] args) throws IOException {
//Open the Server Socket
ServerSocket srv = new ServerSocket(1234);
//Wait for the Client Request
Socket skt = srv.accept();
//Create I/O streams for communicating to the client
OutputStream sout = skt.getOutputStream();
DataOutputStream dout = new DataOutputStream(sout);
//Perform communication with client
dout.writeUTF("This is server Msg..!");
//Close socket
dout.close();
sout.close();
skt.close();
}
}
TcpClient.java
import java.io.*;
import java.net.*;
public class TcpClient {
public static void main(String[] args) throws IOException {
//Create a Socket Object
Socket skt = new Socket("localhost", 1234);
//Create I/O streams for communicating with the server
InputStream sin = skt.getInputStream();
DataInputStream din = new DataInputStream(sin);
//Perform I/O or communication with the server
String str = new String(din.readUTF());
System.out.println(str);
//Close the socket when done
din.close();
sin.close();
skt.close();
}
}
Find Host IP Address and Host name
import java.net.InetAddress;
public class FindhostInfo {
public static void main(String[] args) throws Exception {
InetAddress addr = InetAddress.getLocalHost();
System.out.println("Local Host Address:" + addr.getHostAddress());
System.out.println("Local Host Address:" + addr.getHostName());
}
}
Create JDBC Connection Using Derby Database and fetch the table data
import java.sql.*;
public class JavaDB {
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch (ClassNotFoundException e) {
System.out.println("Class not found " + e);
}
String DbURL = "jdbc:derby://localhost:1527/test";
String Uname = "root";
String Pwd = "root";
try {
Connection con = DriverManager.getConnection(DbURL, Uname, Pwd);
System.out.println("DB Connected");
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("SELECT NAME FROM MOVIE");
while (rs.next()) {
System.out.println("Name: = " + rs.getString("name"));
}
con.close();
System.out.println("DB disconnected");
} catch (SQLException e) {
System.out.println("SQL exception occured" + e);
}
}
}
MVC (Model View Controller) Architecture
Model View Controller or MVC as it is popularly called, is a software design pattern for developing web applications. A Model View Controller pattern is made up of the following three parts:
- Model
- The lowest level of the pattern which is responsible for maintaining data.It responds to the request from the view and it also responds to instructions from the controller to update itself.
- View
- This is responsible for displaying all or a portion of the data to the user.A presentation of data in a particular format, triggered by a controller's decision to present the data. They are script based templating systems like JSP, ASP, PHP
- Controller
- Software Code that controls the interactions between the Model and View.The controller is responsible for responding to user input and perform interactions on the data model objects. The controller receives the input, it validates the input and then performs the business operation that modifies the state of the data model.
MVC is popular as it isolates the application logic from the user interface layer and supports separation of concerns. Here the Controller receives all requests for the application and then works with the Model to prepare any data needed by the View.
Friday, 10 July 2015
Apply Look and feel in your Swing Java Application
Look and feel apply in main method
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SwingCalc().setVisible(true);
}
});
} catch (ClassNotFoundException ex) {
Logger.getLogger(SwingCalc.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(SwingCalc.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(SwingCalc.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(SwingCalc.class.getName()).log(Level.SEVERE, null, ex);
}
}
you also apply following method too
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Thursday, 9 July 2015
Create JDBC Connection Using Derby Database
Open Netbeans IDE and click on services tab, Right click on Java DB connect server + create new database
Right click on YourDB link and connect After creating database
Required DerbyClient jar file
You can easy download derbyclient.jar file here
How to add .jar file into your projects
Step 1 : Right click on your Project and go to the project property Step 2 : click on libraries and click on add JAR/Folder button
Java JDBC Connection Program using Derby DB
package javadb;
import java.sql.*;
public class JavaDB {
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch (ClassNotFoundException e) {
System.out.println("Class not found " + e);
}
String DbURL = "jdbc:derby://localhost:1527/test";
String Uname = "root";
String Pwd = "root";
try {
Connection con = DriverManager.getConnection(DbURL, Uname, Pwd);
System.out.println("DB Connected");
con.close();
System.out.println("DB disconnected");
} catch (SQLException e) {
System.out.println("SQL exception occured" + e);
}
}
}
Tuesday, 7 July 2015
Write a Program to create calculator using Java Swing
Swing Program
public class SwingCalc extends javax.swing.JFrame {
public SwingCalc() {
initComponents();
}
@SuppressWarnings("unchecked")
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
inputTxt1 = new javax.swing.JTextField();
inputTxt2 = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
outputTxt = new javax.swing.JTextField();
sumbt = new javax.swing.JButton();
subbt = new javax.swing.JButton();
mulbt = new javax.swing.JButton();
divbt = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Input Value 1");
jLabel2.setText("Input Value 2");
inputTxt1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
inputTxt1ActionPerformed(evt);
}
});
jLabel3.setText("Output Value");
sumbt.setText("SUM");
sumbt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sumbtActionPerformed(evt);
}
});
subbt.setText("SUB");
subbt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
subbtActionPerformed(evt);
}
});
mulbt.setText("MUL");
mulbt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mulbtActionPerformed(evt);
}
});
divbt.setText("DIV");
divbt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
divbtActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(70, 70, 70)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addGap(55, 55, 55)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(inputTxt1, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
.addComponent(inputTxt2)
.addComponent(outputTxt)))
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(sumbt, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(subbt, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(mulbt, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(divbt, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(37, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(48, 48, 48)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(inputTxt1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(inputTxt2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(outputTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(49, 49, 49)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(sumbt)
.addComponent(subbt)
.addComponent(mulbt)
.addComponent(divbt))
.addContainerGap(63, Short.MAX_VALUE))
);
pack();
}
private void sumbtActionPerformed(java.awt.event.ActionEvent evt) {
int val1 = Integer.parseInt(inputTxt1.getText());
int val2 = Integer.parseInt(inputTxt2.getText());
int val3 = val1 + val2;
outputTxt.setText(Integer.toString(val3));
}
private void subbtActionPerformed(java.awt.event.ActionEvent evt) {
int val1 = Integer.parseInt(inputTxt1.getText());
int val2 = Integer.parseInt(inputTxt2.getText());
int val3 = val1 - val2;
outputTxt.setText(Integer.toString(val3));
}
private void mulbtActionPerformed(java.awt.event.ActionEvent evt) {
int val1 = Integer.parseInt(inputTxt1.getText());
int val2 = Integer.parseInt(inputTxt2.getText());
int val3 = val1 * val2;
outputTxt.setText(Integer.toString(val3));
}
private void divbtActionPerformed(java.awt.event.ActionEvent evt) {
int val1 = Integer.parseInt(inputTxt1.getText());
int val2 = Integer.parseInt(inputTxt2.getText());
int val3 = val1 / val2;
outputTxt.setText(Integer.toString(val3));
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SwingCalc().setVisible(true);
}
});
}
private javax.swing.JButton divbt;
private javax.swing.JTextField inputTxt1;
private javax.swing.JTextField inputTxt2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JButton mulbt;
private javax.swing.JTextField outputTxt;
private javax.swing.JButton subbt;
private javax.swing.JButton sumbt;
}
Output
Write a Program to create calculator using Applet
Applet Program
import java.applet.Applet;
import java.awt.Button;
import java.awt.GridLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AppletCalc extends Applet implements ActionListener {
TextField ipValue1, ipValue2, display;
Button sum, div, sub, mul;
public void init() {
ipValue1 = new TextField();
ipValue2 = new TextField();
display = new TextField();
sum = new Button("SUM");
div = new Button("DIV");
sub = new Button("SUB");
mul = new Button("MUL");
ipValue1.addActionListener(this);
ipValue2.addActionListener(this);
display.addActionListener(this);
sum.addActionListener(this);
sub.addActionListener(this);
div.addActionListener(this);
mul.addActionListener(this);
add(ipValue1);
add(ipValue2);
add(display);
add(sum);
add(sub);
add(div);
add(mul);
GridLayout gl = new GridLayout(3, 1);
setLayout(gl);
}
@Override
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();
int val1 = Integer.parseInt(ipValue1.getText());
int val2 = Integer.parseInt(ipValue2.getText());
int val3;
if (str.equals("SUM")) {
val3 = val1 + val2;
display.setText(Integer.toString(val3));
} else if (str.equals("SUB")) {
val3 = val1 - val2;
display.setText(Integer.toString(val3));
} else if (str.equals("MUL")) {
val3 = val1 * val2;
display.setText(Integer.toString(val3));
} else if (str.equals("DIV")) {
val3 = val1 / val2;
display.setText(Integer.toString(val3));
}
}
}
Output
Subscribe to:
Posts (Atom)








