Adv Java Programs

1.      Program to accept and display the details of the user using servlets.
Form.html
<html>
<head>
<title> Form </title>
</head>
<body>
<form name="form1" action="http://localhost:8080/examples/servlet/sdemo11">
First Name: <input type="text" name="first_name"><br/><br/>
Last Name: <input type="text" name="Last_name"><br/><br/>
Email Id: <input type="text" name="Email_Id"><br/><br/>
<input type="submit" value="SUBMIT">
</form>
</body>
</html>

sdemo11.java
import java.io.*;
importjava.util.*;
importjavax.servlet.*;
public class sdemo11 extends GenericServlet
{
public void service(ServletRequestreq, ServletResponse res) throws ServletException,IOException
  {
PrintWriter out=res.getWriter();
    Enumeration en=req.getParameterNames();
while(en.hasMoreElements())
    {
      String name_received=(String)en.nextElement();
out.println(name_received +"=");
      String value_received=req.getParameter(name_received);
if(value_received!=null||value_received!=" ")
out.println(value_received);
out.println  (" ");
    }
out.close();
 }
}

  



Output:








2.     Program to display the selected choice of the user using servlet.
Form.html
<html>
<body>
<form name=”form1” method=GET
<b> Language </b>
<select name=”Language” size=1?
<option value=”C”> C </option>
<option value=”C++”> C++ </option>
<option value=”Java”> Java </option>
<option value=”C#”> C# </option>
</select>
<br><br>
<input type=”Submit” value=”SUBMIT”>
</form>
</body>
</html>

choiceservlet .java

import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
public class choiceservlet extends HttpServlet
{
public void doGet(HttpServletRequestreq, HttpServletResponse res) throws ServletException,IOException
  {
    String lang=req.getParameter("Language");
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("The selected language is" +lang);
out.close();
  }
}














Output:







3.      Program to display the checked result of the user using servlets.
Form.html
<html>
<head>
<title>CheckBox</title>
</head>
<body>
<b> Choose </b><br/><br/>
<form>
<input type="Checkbox" name="id"><b> C </b><br/>
<input type="Checkbox" name="id"><b> C++ </b><br/>
<input type="Checkbox" name="id"><b> JAVA </b><br/>
<input type="Checkbox" name="id"><b> DOT NET </b><br/><br/><br/>
<input type="Submit" value="SUBMIT"><br/><br/>
</form>

<%
   String select[]=request.getParameter("id");
if(select !=null &&select.length!=0)
  {
out.println(" You have selected:");
for(int i=0;i<select.length;i++)
out.println(select[i]);
  } 
</body>
</html>

CheckServlet .java
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
public class CheckServlet extends HttpServlet
{
public void doPost(HttpServletRequestreq, HttpServletResponse res) throws ServletException,IOException
 {
res.setContentType("text/html");
PrintWriter out=res.getWriter();
  String title="Reading Checkbox Data";
  String docType="<!docType html public\"-//w3c//dtd html 4.0"+"transistional//en\">\n";
out.println(docType+"<html>\n"+
"<head><title>"+ title +"</title></head>"+
"<body>\n"+"<h1>"+title+"</h1>\n"+
"<ul>\n"+"<li><b>MathsFlag:</b></li>"+req.getParameter("maths")+"\n"+
"<ul>\n"+"<li><b>Physics Flag:</b></li>"+req.getParameter("phy")+"\n"+
"<ul>\n"+"<li><b>Chemistry Flag:</b></li>"+req.getParameter("che")+"\n"+
"</ul>\n"+"</body>"+"</html>");
out.close();
}
}
Output:












4.      Program to add cookie and retrieve cookie by using servlets.
Form.html
<html>
<head>
<title> Cookie </title>
</head>
<body>
<h3> Enter Cookie value </h3>
<input type=”text” value=”textdata”>
<input type=”submit” vale=”SUBMIT”>
</form>
</body>
</html>


Servlet to add a cookie
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
public class CookieServlet extends HttpServlet
{
public void doPost(HttpServletRequestreq, HttpServletResponse res) throws ServletException, IOException
  {
    String textdata=req.getParameter("textdata");
    Cookie ck=new Cookie("mycookie",textdata);
res.addCookie(ck);
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<h2> My cookie value set to");
out.println(textdata);
out.println("<br><br><br>");
out.println("Cookie added");
 }
}














Output:







Servlet to retrieve a cookie
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
public class GetCookieServlet extends HttpServlet
{
public void doGet(HttpServletRequestreq,HttpServletResponse res) throws ServletException,IOException
  {
Cookie[] mycookie=req.getCookies();
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<b>");
int n=mycookie.length;
for(int i=0;i<n;i++)
    {
      String name=mycookie[i].getName();
      String value=mycookie[i].getValue();
out.println("Name="+name);
out.println("and Value="+value);
    }
out.close();
   }
 }

Output:
















5.      Program to display the number of visits to a web page using servlet.

import java.io.*;
importjava.util.*;
importjavax.servlet.*;
importjava.servlet.http.*;
public class SessionServlet extends HttpServlet
{
public void doGet(HttpServletRequestreq,HttpServletResponse res) throws ServletException,IOException
  {
res.setContentType("text/html");
HttpSessionhs=req.getSession();
    String heading;
    Integer cnt=(Integer)hs.getAttribute("cnt");
if(cnt==null)
    {
cnt=new Integer(0);
heading=("Welcome you are visiting page for first time");
    }
else
    {
heading="Welcome once again";
cnt=new Integer(cnt.intValue()+1);
    }
hs.setAttribute("cnt",cnt);
PrintWriter out=res.getWriter();
out.println("<html><head>");
out.println("</head>");
out.println("<body>");
out.println("<h1>"+heading);
out.println("<h2>Previous Access=" +cnt);
out.println("</body>");
out.println("</html>");
  }
}













6.      Program to retrieve the data from the database using JDBC.
import java.io.*;
importjava.sql.*;
public class JdbcDemo
{
public static void main(String args[]) throws Exception
  {
try
    {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      Connection con=DriverManager.getConnection("jdbc:odbc:mydb");
System.out.println("Connection Established!!");
      Statement stmt=con.createStatement();
ResultSetrs=stmt.executeQuery("Select * from Stud");
while(rs.next())
      {
System.out.println(rs.getInt(1)+" "+rs.getString(2));
      }
con.close();
    }

catch(ClassNotFoundException e)
    {
System.err.println("Exception:" +e.getMessage());
    }
catch(SQLException e)
    {
System.err.println("Exception:"+e.getMessage());
    }
catch(Exception e)
    {
e.printStackTrace();
    }
  }
}

Output:









7.      Program to insert records into the database using JDBC.

import java.sql.*;
import java.io.*;

class JdbcStmtInsertRecord
{
public static void main(String[] args)
 {
Connection con=null;
Statement stmt=null;
try
      {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("driver has loaded");

con=DriverManager.getConnection("jdbc:odbc:stu");
System.out.println("Connetion db successfully");
stmt=con.createStatement();
System.out.println("Inserting records into the table");
String sql="insert into emp values(15,'lalitha')";
stmt.executeUpdate(sql);
System.out.println("Inserted record into the table...");

stmt.close();
con.close();
      }
catch(Exception e)
    {
e.printStackTrace();
    }
  }
}

Output:










8.      Program to delete records in database using JDBC.
import java.io.*;
import java.sql.*;
public class pre
{
public static void main(String args[])throws SQLException,IOException
{
Connection con=null;
ResultSet rs;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:stu1");
System.out.println("Connection successful");
String sql="delete from stu1 where  sid=3";
PreparedStatement ps=con.prepareStatement(sql);

int rows=ps.executeUpdate();

Statement st=con.createStatement();
rs=st.executeQuery("select * from stu1");
while(rs.next())
{
}
System.out.println("rows deleted");
rs.close();
con.close();
}
catch(ClassNotFoundException e)
{
System.out.println("Class not found");
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}

Output:
9.      Program to update records in database using JDBC.

import java.io.*;
import java.sql.*;

class JdbcStmtUpdateRecord
{
public static void main(String[] args)
 {
Connection con=null;
Statement stmt=null;
try
      {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("driver has loaded");

con=DriverManager.getConnection("jdbc:odbc:stu");
System.out.println("Connetion db successfully");

stmt=con.createStatement();

String sql="update emp set id=5 where id=15";
stmt.executeUpdate(sql);
System.out.println(" record updated...");

stmt.close();
con.close();
      }
catch(Exception e)
    {
e.printStackTrace();
    }
  }
}

Output:










10.  Program to retrieve the data from the database using Prepared statement.

import java.io.*;
importjava.sql.*;
public class Prepare
{
public static void main(String args[]) throws SQLException,IOException
 {
PreparedStatement PS;
ResultSet RS;
   String SQL;
try
   {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     Connection con=DriverManager.getConnection("jdbc:odbc:Prepare");
     SQL="Select * from Studata where CO>? and JAVA>?";
     PS=con.prepareStatement(SQL);
PS.setInt(1,80);
PS.setInt(2,90);
     RS=PS.executeQuery();
System.out.println("RNO"+"\t"+"NAME"+"\t"+"CO"+"\t"+"JAVA"+"\t"+"MULTIMEDIA\n");
while(RS.next())
     {
       System.out.println(RS.getInt(1)+"\t"+RS.getString(2)+"\t"+RS.getString(3)+"\t"+RS.getString(4)+"\t"+RS.getString(5));
     }
PS.close();
con.close();
    }
catch(SQLException e)
    {
System.out.println("SQL Error!!");
    }
catch(ClassNotFoundException e)
    {
System.out.println("Class Not Found!!");
    }
  }
}

Output:




11.  Program to update date in the database using prepared statement.

import java.io.*;
importjava.sql.*;
classUpdateEmp
{
public static void main(String args[])
  {
try
    {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      Connection con=DriverManager.getConnection("jdbc:odbc:Emp");
System.out.println("Connection Established!!");
      String sql="Update Emp set Age=? whereEno=?";
PreparedStatement PS=con.prepareStatement(sql);
PS.setInt(1,50);
PS.setInt(2,2);
PS.executeUpdate();
System.out.println("Updated Successfully!!");
     }

catch(SQLException e)
    {
System.out.println("SQL statement not executed!!");
    }

catch(Exception e)
    {
e.printStackTrace();
    }
  }
}

Output:












12.  Program to insert the records in the database using prepared statement.

import java.io.*;
importjava.sql.*;
public class InsertRecords
{
public static Connection getConnection() throws SQLException,IOException,Exception
 {
   String driver="sun.jdbc.odbc.JdbcOdbcDriver";
   String url="jdbc:odbc:Dept";
Class.forName(driver);
   Connection con=DriverManager.getConnection(url);
return con;
 }
public static void main(String agrs[]) throws Exception
   {
intm,i;
    String s1,s2;
    Connection con=null;
PreparedStatementPstmt=null;
try
     {
con=getConnection();
       String query="Insert into dept(deptno,deptname,deptloc) values (?,?,?)";
Pstmt=con.prepareStatement(query);
BufferedReaderbr= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of records to be inserted:");
int n=Integer.parseInt(br.readLine());
for(i=1;i<n;i++)
       {
System.out.println("Enter Deptno:");
         m=Integer.parseInt(br.readLine());
Pstmt.setInt(1,m);
System.out.println("Enter Deptname:");
        s1=br.readLine();
Pstmt.setString(2,s1);
System.out.println("Enter DeptLoc:");
       s2=br.readLine();
Pstmt.setString(3,s2);
Pstmt.executeUpdate();
     }
   } 
catch(Exception e)
     {
e.printStackTrace();
     }

finally
     {
Pstmt.close();
con.close();
     }
  }
}

Output:










13.  Program to update the result and display the results using prepared statement.

import java.io.*;
importjava.sql.*;
classUpdateEmp
{
public static void main(String args[])
  {
try
    {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      Connection con=DriverManager.getConnection("jdbc:odbc:Emp");
System.out.println("Connection Established!!");
      String sql="Update Emp set Age=? whereEno=?";
PreparedStatement PS=con.prepareStatement(sql);
PS.setInt(1,50);
PS.setInt(2,2);
PS.executeUpdate();
System.out.println("Updated Successfully!!");
int rows=PS.executeUpdate();
System.out.println("Updated rows="+rows);
     Statement stmt=con.createStatement();
    String sql1="select Eno,Ename,Age from Emp";
ResultSet RS=stmt.executeQuery(sql1);
while(RS.next())
     {

intEno=RS.getInt("Eno");
      String Ename=RS.getString("Ename");
int age=RS.getInt("Age");     
System.out.println("ID is:"+Eno);                                                                                    
System.out.println("Name is:"+Ename);
System.out.println("Age is:"+age);
    }

RS.close();
con.close();
    }

catch(SQLException e)
    {
System.out.println("SQL statement not executed!!");
    }

catch(Exception e)
    {
e.printStackTrace();
    }
  }
}
Output:
















14.  Program to delete records in the database  using prepared statement.

import java.sql.*;
import java.io.*;
class JdbcPstmtDeleteRecord
{
public static void main(String[] args)
 {
Connection con=null;
PreparedStatement pstmt=null;
try
      {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("driver has loaded");

con=DriverManager.getConnection("jdbc:odbc:stu");
System.out.println("Connetion db successfully");

String sql="delete from emp where id=?";

pstmt=con.prepareStatement(sql);
System.out.println("PreparedStatement object created");

pstmt.setInt(1,15);

System.out.println("deleting record into the table");

pstmt.executeUpdate();
System.out.println(" record deleted.");
pstmt.close();
con.close();
      }
catch(Exception e)
    {
e.printStackTrace();
    }
 }
}

Output:





15.  Program to retrieve data using scrollable resultset.

import java.io.*;
import java.sql.*;
public class ScrollableResults
{
            public static void main(String args[])throws Exception,IOException
            {
                        Connection con = null;
                        Statement stmt = null;
                        try
                        {
                                    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            con = DriverManager.getConnection("jdbc:odbc:ScrollableResults");
String sql = "select id,age,first,last from emp";
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery(sql);
rs.last();
                                    int id1 = rs.getInt("id");
                                    int age1 = rs.getInt("age");
                                    String first1 = rs.getString("first");
                                    String last1 = rs.getString("last");
                                    //display records
                                    System.out.println("ID:" + id1);
                                    System.out.println("Age:" + age1);
                                    System.out.println("First:" + first1);
                                    System.out.println("Last" + last1);
                                    rs.first();
                                    int id2 = rs.getInt("id");
                                    int age2 = rs.getInt("age");
                                    String first2 = rs.getString("first");
                                    String last2 = rs.getString("last");
                                    //display records
                                    System.out.println("ID:" + id2);
                                    System.out.println("Age:" + age2);
                                    System.out.println("First:" + first2);
                                    System.out.println("Last" + last2);
                                    rs.next();
                                    int id3 = rs.getInt("id");
                                    int age3 = rs.getInt("age");
                                    String first3 = rs.getString("first");
                                    String last3 = rs.getString("last");
                                    //display records
                                    System.out.println("ID:" + id3);
                                    System.out.println("Age:" + age3);
                                    System.out.println("First:" + first3);
                                    System.out.println("Last" + last3);
                                    rs.close();
                                    stmt.close();
                                    con.close();
                        }
                        catch (SQLException e)
                        {
                                    e.printStackTrace();
                        }
                        finally
                        {
                                    if (stmt != null || con != null)
                                                stmt.close();
                                    con.close();
                        }
            }
}

Output:






16.  Program to update batch of SQL queries using Using addBatch() and executeBatch() in Statement Interface.

import java.io.*;
import java.sql.*;
class BatchUpdate
    {
public static void main(String args[])
       {
Connection con=null;
Statement stmt=null;

try
             {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver Loaded");

con=DriverManager.getConnection("jdbc:odbc:stu");
System.out.println("Connection success");

stmt=con.createStatement();

stmt.addBatch("insert into emp values(4,'ddd')");
stmt.addBatch("update emp set name='lalitha' where id=1");
stmt.addBatch("update emp set name='nagalakshmi' where id=2");
stmt.addBatch("delete from emp where id=3");

stmt.executeBatch();
System.out.println("records updated");

stmt.close();
con.close();
              }
catch(Exception e)
              {
e.printStackTrace();
              }
       }
}
Output:






17.  Program to create menubar and menu items java swings.

import javax.swing.*;
public class SwingMenu
{
  public static void main(String args[])
  {
    SwingMenu s = new SwingMenu();
  }
 
  public SwingMenu()
  {
    JFrame frame=new JFrame("Creating a menubar, menuitems");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JMenuBar menubar=new JMenuBar();
    JMenu filemenu=new JMenu("File");
    filemenu.add(new JSeparator());
    JMenu editmenu=new JMenu("Edit");
    editmenu.add(new JSeparator());
    JMenuItem ft1=new JMenuItem("New");
    JMenuItem ft2=new JMenuItem("Open");
    JMenuItem ft3=new JMenuItem("Save");
    JMenuItem ft4=new JMenuItem("SaveAs");
    ft4.add(new JSeparator());
   JMenuItem et1=new JMenuItem("Cut");
   JMenuItem et2=new JMenuItem("Copy");
   JMenuItem et3=new JMenuItem("Paste");
   et3.add(new JSeparator());
   filemenu.add(ft1);
   filemenu.add(ft2);
   filemenu.add(ft3);
   filemenu.add(ft4);
   editmenu.add(et1);
   editmenu.add(et2);
   editmenu.add(et3);
   menubar.add(filemenu);
   menubar.add(editmenu);
   frame.setJMenuBar(menubar);
   frame.setSize(400,400);
   frame.setVisible(true);
  }
}








Output:













18.  Program to select an item using radio buttions java swings.

import java.io.*;
import java.awt.event.*;
import javax.swing.*;
class RadioEx extends JFrame implements ActionListener
{
  JRadioButton rb1,rb2;
  JButton b;
  RadioEx()
  {
    rb1=new JRadioButton("Male");
    rb1.setBounds(100,50,100,30);
    rb2= new JRadioButton("Female");
    rb2.setBounds(100,100,100,30);
    ButtonGroup bg = new ButtonGroup();
    bg.add(rb1);
    bg.add(rb2);
    b = new JButton("Click");
    b.setBounds(100,150,80,30);
    b.addActionListener(this);
    add(rb1);
    add(rb2);
    add(b);
    setSize(300,300);
    setLayout(null);
    setVisible(true);
}
  public void actionPerformed(ActionEvent e)
  {
    if(rb1.isSelected())
    {
      JOptionPane.showMessageDialog(this,"You are Male!!");
    }
   
    if(rb2.isSelected())
    {
      JOptionPane.showMessageDialog(this,"You are Female!!");
    }
  }
 
  public static void main(String args[])
  {
      new RadioEx();
       
  }
}



Output:














19.  Program to choose a color using java swings.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JColorChooserEx extends JFrame implements ActionListener
{
  JButton b;
  Container c;
  JColorChooserEx()
  {
    c=getContentPane();
    c.setLayout(new FlowLayout());
    b=new JButton("Color");
    b.addActionListener(this);
    c.add(b);
  }

  public void actionPerformed(ActionEvent e)
  {
    Color initialcolor=Color.RED;
    Color color=JColorChooser.showDialog(this,"Select a color", initialcolor);
    c.setBackground(color);
  }

  public static void main(String args[])
  {
    JColorChooserEx ch=new JColorChooserEx();
    ch.setSize(400,400);
    ch.setVisible(true);
    ch.setDefaultCloseOperation(EXIT_ON_CLOSE);
  }
}

















Output:
20.  Program to select an item using combo box using java swings.

import javax.swing.*;
public class Combo
{
  JFrame f;
  Combo()
 {
   f=new JFrame("Combo");
   String country[]={"India","America"};
   JComboBox cb = new JComboBox(country);
    cb.setBounds(50,50,90,20);
    f.add(cb);
    f.setLayout(null);
    f.setSize(400,500);
    f.setVisible(true);
 }

  public static void main(String args[])
 {
  new Combo();
}
}



Output:








21.  Program to accept and display the details of the user using JSP.
Form.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
 </head>
<body> <h1>Login Page</h1>
 <center> <h2>Signup Details</h2>
 <form action="Logincheck.jsp" method="post"> <br/>Username:<input type="text" name="username"> <br/>Password:<input type="password" name="password"> <br/><input type="submit" value="Submit">
 </form>
 </center>
</body>
</html>
Logincheck.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head> <body>
 <% String username=request.getParameter("username");
String password=request.getParameter("password");
if((username.equals("MCA") && password.equals("Students")))
 {
session.setAttribute("username",username);
 response.sendRedirect("Home.jsp");
}
else
response.sendRedirect("Error.jsp"); %>
 </body>
 </html>





Error.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
 </head>
<body> <h1>Some Error has occured,Please try again later...</h1>
 </body>
 </html>




Logout.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>JSP Page</title>
</head>
 <body>
 <% session.removeAttribute("username");
session.removeAttribute("password");
session.invalidate(); %>
 <h1>Logout was done successfully.</h1>
 </body>
</html>


22.  Program for Setting and getting the cookie value using JSP.

CookiesInJsp.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="javax.servlet.http.Cookie" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Cookies In JSP</title>
</head>
<body>
<form>
<table>
<tr>
<td>Enter Your Name :</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Enter Your Age :</td>
<td><input type="text" name="age"/></td>
</tr>
<tr>
<td></td><td><input type="submit" value="submit"/></td>
</tr>
</table>
</form>
<%
String nm = request.getParameter("name");
String ag = request.getParameter("age");

if(nm != null)
{
String trim = ag.trim();
int a = Integer.parseInt(ag);
%>
<table>
<tr>
<td>Name = </td> <td><%=nm %></td>
</tr>
<tr>
<td>Age = </td> <td><%=a %></td>
</tr>
</table>
<%
Cookie nCookie = new Cookie("nam", nm);
//Name cookie add to the response header
response.addCookie(nCookie);
}
%>

<%
Cookie cookie = null;
Cookie[] cookieArray = request.getCookies();
if(cookieArray != null)
{
%>
<p><b>Cookies Information</b></p>
<%
for(int i=0; i<cookieArray.length; i++)
{
cookie = cookieArray[i];
out.println("CookieName :" + cookie.getName());
out.println("CookieValue :" + cookie.getValue());
}
}
else
{
out.println("Cookies is not added in the response");
}
%>
</body>
</html>




23.  Program to add two numbers using RMI Interface.

Client.java
import java.rmi.*;
import java.io.*;
public class Client

{
public static void main(String args[])
{
try
{
String ip="rmi://192.168.1.97/RMIAPPLICATION";
Remote Interface S=Remote Interface Naming.lookup(ip);
System.out.println("sum:"+s.add(1,3));
}
catch(exception e)
{
System.out.print(e.getMessage());
e.printStackTrace();
}
}
}


Remoteinterface.java
import java.rmi.*;
public interface Remote interface extends Remote
{
public int add (int x,int y)throws Exception;
}
Server.java:
import java.rmi.*;
import java.net.*;
public class server
{
public static void main(String args[])
{
try
{
serverimplements s=new server implements();
naming.rebind("SEWRVICE",s);
System.outprint in("server started");
}
catch(Exception e);
{
System.out.printin(e.get message()();
}
}
}
Serverimplements.java
import java.rmi.*;
import java.rmi.server.*;
import java.lang.string.*;
interface Remote Interface extands Remote
{
public intadd(int x,int y)throws Exception;
}
public class server Implements extends unicast Remote object Implement Romote Interface
{
public server Implemts()throws Exception
{
super();
}
public intadd(int x,int y)
{
return(x+y);
}
}

Output:

Sum: 4


24.  Program for running session beans using eclipse.

AdderImpl.java
package com.javatpoint; 
import javax.ejb.Stateless; 
 
@Stateless(mappedName="st1") 
public class AdderImpl implements AdderImplRemote { 
  public int add(int a,int b){ 
      return a+b; 
  } 

AdderImpl2.java
package com.javatpoint; 
import javax.naming.Context; 
import javax.naming.InitialContext; 
 
public class Test { 
public static void main(String[] args)throws Exception { 
    Context context=new InitialContext(); 
    AdderImplRemote remote=(AdderImplRemote)context.lookup("st1"); 
    System.out.println(remote.add(32,32)); 
AdderImplRemote.java

package com.javatpoint; 
import javax.ejb.Remote; 
 
@Remote 
public interface AdderImplRemote { 
int add(int a,int b); 


Output:












No comments:

Post a Comment

teaching methods- gamification