You are on page 1of 37

Padmakanya Multiple Campus

Bagbazar, Kathmandu

Tribhuvan University

A Practical Report on

Advanced Java Programming [CSC 409]

Submitted To:
Kumar Prasun
Department of Computer Science

Padmakanya Multiple Campus

Submitted By:
Simran Shrestha

Roll No: 20313/075


Table of Contents
Lab 1:.........................................................................................................................................................3
WAP to demonstrate Exception Handling...............................................................................................3
WAP to create a Table GUI using the concept of Swing in java Programming language.........................5
Lab 2:.......................................................................................................................................................11
WAP to create a simple calculator GUI using the concept of Swing, Event Handling in Java
programming Language..........................................................................................................................11
Lab 3:.......................................................................................................................................................16
I. Write a java program using TCP such that client sends number to server and displays its
factorial. The server computes factorial of the number received from client.....................................16
II. Write a java program using UDP showing that the sending and receiving of message using
DatagramPacket and DatagramSocket class.........................................................................................19
LAB 4:......................................................................................................................................................22
Write a program to design a GUI form to take input for this table and insert the data into table
after clicking the OK button...................................................................................................................22
LAB 5:......................................................................................................................................................26
Write servlet application to:...................................................................................................................26
1. To print current date and time...........................................................................................................26
2. Communicate between Html and servlet...........................................................................................26
3. Create an auto refreshed page............................................................................................................26
LAB 6:......................................................................................................................................................33
Write JSP application program to login page.......................................................................................33
LAB 7:......................................................................................................................................................37
Write RMI program to add two numbers.............................................................................................37
Lab 1:

WAP to demonstrate Exception Handling.


Theory:

The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained. In Java, an exception is an
event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
Java exception handling is managed via five keywords: try, catch, throw, throws, finally.

 Program statements that we want to monitor for exceptions are contained within a
Try block.

 If an exception occurs within the try block, it is thrown.


 Our code can catch this exception (using catch) and handle it in some rational
manner.

 System-generated exceptions are automatically thrown by the Java run-time


system.

 To manually throw an exception, use the keyword throw


 Any exception that is thrown out of a method must be specified as such by a throws
clause.

 Any code that absolutely must be executed before a method returns is put in a finally block.
Source Code:

public class Exception handleing {

public static void main(String[] args) {

int a=6;

int b=0;

try{
int c=a/b;

System.out.println("The vale of c is "+c);

catch(ArithmeticException e)

System.out.println(e);

Output:
Lab 2:

WAP to create a simple calculator GUI using the concept of Swing, Event
Handling in Java programming Language.
Theory:
Java Swing is a GUI (graphical user Interface) widget toolkit for Java. Java Swing is a part of
Oracle’s Java foundation classes. Java Swing is an API for providing graphical user interface
elements to Java Programs. Swing was created to provide more powerful and flexible
components than Java AWT (Abstract Window Toolkit).

Methods used: 
1. add(Component c) : adds component to container.
2. addActionListenerListener(ActionListener d) : add actionListener for specified
component
3. setBackground(Color c) : sets the background color of the specified container
4. setSize(int a, int b) : sets the size of container to specified dimensions.
5. setText(String s) : sets the text of the label to s.
6. getText() : returns the text of the label.

Source Code:
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
class calculator extends JFrame implements ActionListener {
    static JFrame f;
    static JTextField l;
    String s0, s1, s2;
    calculator()
  {
        s0 = s1 = s2 = "";
  }
    public static void main(String args[])
  {
        f = new JFrame("calculator");
        calculator c = new calculator();

        l = new JTextField(16);

        l.setEditable(false);
        JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, be, beq, beq1;

        b0 = new JButton("0");
        b1 = new JButton("1");
        b2 = new JButton("2");
        b3 = new JButton("3");
        b4 = new JButton("4");
        b5 = new JButton("5");
        b6 = new JButton("6");
        b7 = new JButton("7");
        b8 = new JButton("8");
        b9 = new JButton("9");

        beq1 = new JButton("=");

        ba = new JButton("+");
        bs = new JButton("-");
        bd = new JButton("/");
        bm = new JButton("*");
        beq = new JButton("C");

        be = new JButton(".");
        JPanel p = new JPanel();
        bm.addActionListener(c);
        bd.addActionListener(c);
        bs.addActionListener(c);
        ba.addActionListener(c);
        b9.addActionListener(c);
        b8.addActionListener(c);
        b7.addActionListener(c);
        b6.addActionListener(c);
        b5.addActionListener(c);
        b4.addActionListener(c);
        b3.addActionListener(c);
        b2.addActionListener(c);
        b1.addActionListener(c);
        b0.addActionListener(c);
        be.addActionListener(c);
        beq.addActionListener(c);
        beq1.addActionListener(c);

        p.add(l);
        p.add(ba);
        p.add(b1);
        p.add(b2);
        p.add(b3);
        p.add(bs);
        p.add(b4);
        p.add(b5);
        p.add(b6);
        p.add(bm);
        p.add(b7);
        p.add(b8);
        p.add(b9);
        p.add(bd);
        p.add(be);
        p.add(b0);
        p.add(beq);
        p.add(beq1);
        f.add(p);
        f.setSize(200, 220);
        f.show();
  }
    public void actionPerformed(ActionEvent e)
  {
        String s = e.getActionCommand();
        if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') || s.charAt(0) == '.') {
            if (!s1.equals(""))
                s2 = s2 + s;
            else
                s0 = s0 + s;
            l.setText(s0 + s1 + s2);
    }
        else if (s.charAt(0) == 'C') {
            s0 = s1 = s2 = "";
            l.setText(s0 + s1 + s2);
    }
        else if (s.charAt(0) == '=') {
            double te;
            if (s1.equals("+"))
                te = (Double.parseDouble(s0) + Double.parseDouble(s2));
            else if (s1.equals("-"))
                te = (Double.parseDouble(s0) - Double.parseDouble(s2));
            else if (s1.equals("/"))
                te = (Double.parseDouble(s0) / Double.parseDouble(s2));
            else
                te = (Double.parseDouble(s0) * Double.parseDouble(s2));
            l.setText(s0 + s1 + s2 + "=" + te);
            s0 = Double.toString(te);
            s1 = s2 = "";
    }
        else {
            if (s1.equals("") || s2.equals(""))
                s1 = s;
            else {
                double te;

                if (s1.equals("+"))
                    te = (Double.parseDouble(s0) + Double.parseDouble(s2));
                else if (s1.equals("-"))
                    te = (Double.parseDouble(s0) - Double.parseDouble(s2));
                else if (s1.equals("/"))
                    te = (Double.parseDouble(s0) / Double.parseDouble(s2));
                else
                    te = (Double.parseDouble(s0) * Double.parseDouble(s2));
                s0 = Double.toString(te);
                s1 = s;
                s2 = "";
      }
            l.setText(s0 + s1 + s2);
    }
  }
}

Output:
Conclusion:
In this lab of Advanced Java Programming, we successfully created a simple calculator GUI
using the elements of Java Swing and the java event handling.
Lab 3:

I. Write a java program using TCP such that client sends number to
server and displays its factorial. The server computes factorial of the
number received from client.
Theory:
Java Socket Programming:

Java Socket programming is used for communication between the applications running on
different JRE. Java Socket programming can be connection-oriented or connection-less. Socket
and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
The client in socket programming must know two information:

1. IP Address of Server, and


2. Port number.

Here, we are going to make one-way client and server communication. In this application, client
sends a message to the server, server reads the message and prints it. Here, two classes are being
used: Socket and ServerSocket. The Socket class is used to communicate client and server.
Through this class, we can read and write message. The ServerSocket class is used at server-side.
The accept() method of ServerSocket class blocks the console until the client is connected. After
the successful connection of client, it returns the instance of Socket at server-side.

Source Code:

//server program
import java.io.*;
import java.net.*;
class Server
{
            public static void main(String args[])
      {
                        try
            {
                                    ServerSocket ss=new ServerSocket(1064);
                                    System.out.println("Waiting for Client Request");
                                    Socket s=ss.accept();
                                    BufferedReader br;
                                    PrintStream ps;
                                    String str;
                                    br=new BufferedReader(new InputStreamReader(s.getInputStream()));
                                    str=br.readLine();
                                    System.out.println("Received number");
                                    int x=Integer.parseInt(str);
                                    int fact=1;
                                    for(int i=1;i<=x;i++)
                                    fact=fact*i;
                  
                                    ps=new PrintStream(s.getOutputStream());
                                    ps.println(String.valueOf(fact));
                                    br.close();
                                    ps.close();
                                    s.close();
                                    ss.close();
            }
                        catch(Exception e)
            {
                                    System.out.println(e);
            }
      }
}

//Client program
import java.io.*;
import java.net.*;
class Client
{
            public static void main(String args[])throws IOException
      {
            
                        Socket s=new Socket(InetAddress.getLocalHost(),1064);
                        BufferedReader br;
                        PrintStream ps;
                        String str;
                        System.out.println("Enter a number  :");
                        br=new BufferedReader(new InputStreamReader(System.in));
                        ps=new PrintStream(s.getOutputStream());
                        ps.println(br.readLine());
                        br=new BufferedReader(new InputStreamReader(s.getInputStream()));
                        str=br.readLine();
                        System.out.println("The facorial of the number is : "+str);
                        br.close();
                        ps.close();
      }
}
II. Write a java program using UDP showing that the sending and
receiving of message using DatagramPacket and DatagramSocket
class.

Theory:
Java DatagramSocket and DatagramPacket

Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming using the UDP instead of TCP.

Datagram

Datagrams are collection of information sent from one device to another device via the
established network. When the datagram is sent to the targeted device, there is no assurance that
it will reach to the target device safely and completely. It may get damaged or lost in between.
Likewise, the receiving device also never know if the datagram received is damaged or not. The
UDP protocol is used to implement the datagrams in Java.

Java DatagramSocket class

Java DatagramSocket class represents a connection-less socket for sending and receiving


datagram packets. It is a mechanism used for transmitting datagram packets over network. A
datagram is basically an information but there is no guarantee of its content, arrival or arrival
time.

Source Code:
//sender
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
class Dsender  {
    public static void main(String[] args)throws Exception {
    DatagramSocket ds= new DatagramSocket();
    String str= "Message sent by server";
    InetAddress ip = InetAddress.getLocalHost();
    DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(),ip, 6666);
    ds.send(dp);
    System.out.println("Message sent!");
    ds.close();
  }
}
//receiver
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Dreceiver {
    public static void main(String[] args) throws Exception {
        DatagramSocket ds= new DatagramSocket(6666);
        byte[] buf= new byte[1024];
        DatagramPacket dp=new DatagramPacket(buf, 1024);
        ds.receive(dp);
        String str= new String(dp.getData(),0,dp.getLength());
        System.out.println(str);
        System.out.println("Message received!");
        ds.close();
    }   
}

Output:
Conclusion:
In this lab session, we successfully implement the concepts of Network Programming: TCP/IP
and UDP using the java.net package classes in Java programming language.
Lab 4:
You are hired by a reputed software company which is going to design an
application for "Movie Rental System". Your responsibility is to design a
schema named MRS and create a table named Movie (id, Title, Genre,
Language, Length).

WAP to design a GUI form to take input for this table and insert the data into
table after clicking the OK button.
Theory:
JDBC:

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. There are four types of JDBC drivers:

 JDBC-ODBC Bridge Driver,


 Native Driver,
 Network Protocol Driver, and
 Thin Driver

Source Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class Movie extends JFrame implements ActionListener {
    JFrame jf;
    JTextField t1, t2,t3,t4;
    JLabel l1,l2,l3,l4;
    JButton b1;
    public Movie(){
        jf = new JFrame("Movie Rental System");
        l1= new JLabel("Title");
        l2= new JLabel("Genera");
        l3= new JLabel("Language");
        l4= new JLabel("Length");
        t1= new JTextField(10);
        t2= new JTextField(10);
        t3= new JTextField(10);
        t4= new JTextField(10);
        b1= new JButton("ADD");
        jf.add(l1);
        jf.add(t1);
        jf.add(l2);
        jf.add(t2);
        jf.add(l3);
        jf.add(t3);
        jf.add(l4);
        jf.add(t4);
        jf.add(b1);
        jf.setSize(500,700);
        jf.setLayout(new FlowLayout());
        b1.addActionListener(this);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
    public void actionPerformed(ActionEvent ae){
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mrs","root","");
            Statement stmt= conn.createStatement();
            System.out.println("Database connected successfully");
            String sql="insert into movie(title, genera, language, length) values (?,?,?,?)";
            PreparedStatement ps= conn.prepareStatement(sql);
            ps.setString(1, t1.getText());
            ps.setString(2, t2.getText());
            ps.setString(3, t3.getText());
            ps.setString(4, t4.getText());
            ps.executeUpdate();
            conn.close();
            System.out.println("Inserted successfully");

        }catch(Exception se){
        System.out.println(se);
    }
  }
    public static void main(String[] args) {
    new Movie();
}
}
Output:
Inserting data into from GUI to Mysql Database as:
And, the reflected data in the database:

Conclusion:
In this lab session, we successfully connect to the MySQL database using JDBC connection
using above Movie Rental System GUI.
Lab 5:

Write servlet application to:

1. To print current date and time.

2. Communicate between Html and servlet.

3. Create an auto refreshed page.


Theory:
Servlet:

Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page). Servlet technology is robust and scalable because of java language. Before
Servlet, CGI (Common Gateway Interface) scripting language was common as a server-side
programming language.

Source Code:

1. to print current date and time:

//servlet.java file
package com.innovator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class servlet extends HttpServlet {
    public void processRequest(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out;
        try {
            out = response.getWriter();
            out.println(" <html>");
            out.println("<h1>The current date is: "+java.time.LocalDate.now()+"</h3>");
            out.println("<h1>And, the current time is: "+java.time.LocalTime.now()+"</h3>");

            out.println("</html>");
        } catch (IOException e) {
            e.printStackTrace();
    }
  }
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
  }
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
  }
}

//index.html
<html>
    <head>
        <title>Start page</title>
        <meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
    </head>
<body>
<h2>My servlet page!</h2>
<form action="./api" method="GET, POST">
    <Button>Show current Date and Time</Button>
</form>
</body>
</html>

//web.xml file
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>servlet</servlet-name>
    <servlet-class>com.innovator.servlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>servlet</servlet-name>
    <url-pattern>/api</url-pattern>
  </servlet-mapping>
</web-app>
Output:
3. create an auto refreshed page.
//Refresh.java file
package com.innovator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Refresh extends HttpServlet {
    public void processRequest(HttpServletRequest request, HttpServletResponse response) {
        response.setIntHeader("Refresh", 1);
          // Set response content type
          response.setContentType("text/html");
          // Get current time
          Calendar calendar = new GregorianCalendar();
          String am_pm;
          int hour = calendar.get(Calendar.HOUR);
          int minute = calendar.get(Calendar.MINUTE);
          int second = calendar.get(Calendar.SECOND);
          if(calendar.get(Calendar.AM_PM) == 0)
               am_pm = "AM";
          else
               am_pm = "PM";

          String CT = hour+":"+ minute +":"+ second +" "+ am_pm;


        PrintWriter out;
        try {
      
            out = response.getWriter();
            out.println(" <html>");
            out.println("<h1 align='center'>Auto Refresh Page</h1><hr>");
          out.println("<h3 align='center'>Current time: "+CT+"</h3>");

            out.println("</html>");
        } catch (IOException e) {
            e.printStackTrace();
    }

  }
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
  }
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
  }
}
//index.html file
<html>
    <head>
        <title>Start page</title>
        <meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
    </head>
<body>
<h2>My servlet page!</h2>
<form action="./Refresh" method="GET, POST">
    <Button>show autorefresh page</Button>
</form>
</body>
</html>
//web.xml file
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>Refresh</servlet-name>
    <servlet-class>com.innovator.Refresh</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Refresh</servlet-name>
    <url-pattern>/Refresh</url-pattern>
  </servlet-mapping>
</web-app>

Output:

Conclusion:
In this lab of Advanced Java Programming, we successfully implemented the concept of servlet
using Maven and Tomcat server in visual studio code.

Lab 6:

Write JSP application program to login page.


Theory:
JSP:
Java Server Pages (JSP) technology is used to create web application just like Servlet technology.
It can be thought of as an extension to Servlet because it provides more functionality than servlet
such as expression language, JSTL, etc. A JSP page consists of HTML tags and JSP tags. The
JSP pages are easier to maintain than Servlet because we can separate designing and
development. It provides some additional features such as Expression Language, Custom Tags,
etc.

Source Code:

// ControllerServlet.java file

package com.innovator.user;

import java.io.IOException;  

import javax.servlet.RequestDispatcher;  

import javax.servlet.ServletException;  

import javax.servlet.http.HttpServlet;  

import javax.servlet.http.HttpServletRequest;  

import javax.servlet.http.HttpServletResponse;

import com.innovator.ControllerServlet.LoginBean;  

public class ControllerServlet extends HttpServlet {  

    protected void doPost(HttpServletRequest request, HttpServletResponse response)  

            throws ServletException, IOException {  

        response.setContentType("text/html");           

        String name=request.getParameter("name");  

        String password=request.getParameter("password");  

        LoginBean bean=new LoginBean();  

        bean.setName(name);  

        bean.setPassword(password);  
        request.setAttribute("bean",bean);  

   

        boolean status=bean.validate();  

     

        if(status){  

            RequestDispatcher rd=request.getRequestDispatcher("login-success.jsp");  

            rd.forward(request, response);  

    } 

        else{  

            RequestDispatcher rd=request.getRequestDispatcher("login-error.jsp");  

            rd.forward(request, response);  

    } 

   

  } 

    @Override  

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)  

            throws ServletException, IOException {  

        doPost(req, resp);  

  } 

// LoginBean.java
package com.innovator.ControllerServlet;

public class LoginBean {  

    private String name,password;  

   

    public String getName() {  

        return name;  

  } 

    public void setName(String name) {  

        this.name = name;  

  } 

    public String getPassword() {  

        return password;  

  } 

    public void setPassword(String password) {  

        this.password = password;  

  } 

    public boolean validate(){  

        if(password.equals("saugat"))

            return true;  

        else

            return false;  

  } 
  } 

//index.jsp

<html>

  <body>

    <form action="ControllerServlet" method="post">

      Name:<input type="text" name="name" /><br />

      Password:<input type="password" name="password" /><br />

      <input type="submit" value="login" />

    </form>

  </body>

</html>

//login-error.jsp

<p>Sorry! username or password error</p>  

<%@ include file="index.jsp" %>

//login-success.jsp

<%@page import="com.javatpoint.LoginBean"%>  

<p>You are successfully logged in!</p>  

<%  

LoginBean bean=(LoginBean)request.getAttribute("bean");  

out.print("Welcome, "+bean.getName());  

%>  

Output:
Conclusion:
In this lab of Advanced Java Programming, we successfully implemented the concept of JSP
using Maven and Tomcat server in visual studio code.

Lab 7:

Write RMI program to add two numbers.


Theory:
RMI:
The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed
application in java. The RMI allows an object to invoke methods on an object running in another
JVM. The RMI provides remote communication between the applications using two
objects stub and skeleton.

Source Code:

//define remote interface

import java.rmi.*;

public interface AddRem extends Remote

public int addNum(int a, int b) throws RemoteException;

//implementation of interface
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class AddRemImp1 extends UnicastRemoteObject implements AddRem
{
public AddRemImp1() throws RemoteException{
  
}
public int addNum(int a, int b){
return (a+b);
}
}

//client program
import java.rmi.*;
import java.net.*;
import java.util.*;
public class AddClient {
    public static void main(String args[]) {
        Scanner sc;
        try {
            String host = "localhost";
            sc = new Scanner(System.in);
            System.out.println("Enter the 1st parameter");
            int a = sc.nextInt();
            System.out.println("Enter the 2nd parameter");
            int b = sc.nextInt();
            AddRem remobj = (AddRem) Naming.lookup("rmi://" + host + "/AddRem");
            System.out.println(remobj.addNum(a, b));
        } catch (RemoteException re) {
            re.printStackTrace();
        } catch (NotBoundException nbe) {
            nbe.printStackTrace();
        } catch (MalformedURLException mfe) {
            mfe.printStackTrace();
    }
  }
}

//server program
import java.rmi.*;
import java.net.*;
public class AddServer
{
public static void main(String args[])
{
try{
AddRemImp1 locobj= new AddRemImp1();
Naming.rebind("rmi:///AddRem",locobj);
}
catch(RemoteException re){
re.printStackTrace();
}
catch(MalformedURLException mfe){
mfe.printStackTrace();
}
}
}

Output:

You might also like