SlideShare une entreprise Scribd logo
1  sur  32
Advance Java (Sem 5 – T.Y.B.Sc.I.T.)
Iram Ramrajkar

PRACTICAL 01:

Write a java program to present a set of choices for a user to select
Stationary products and display the price of Product after Selection from the
list.

Prac1.java:

import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;

class MyFrame extends JFrame implements ListSelectionListener
{
 Container cp;
 JList l1;
 JLabel lbl;

//creating a 1D array to store the items
String[] items ={"pen","pencil","ruler","eraser","sharpner"};

//creating another 1D array to store their prices.
int[] price={12,13,15,5,5,25,35};

MyFrame()
 {
 //call parent constructor
 super();

  //decide size of the frame
  setSize(400,400);

 //obtain the content pane to add components
  cp=this.getContentPane();

  //decide layout
  cp.setLayout(new FlowLayout());

  //instantiate components
  l1=new JList(items);
  lbl=new JLabel(" ");

  //register list to respond to events

1|Page
Advance Java


  l1.addListSelectionListener(this);

  //add components to container
  cp.add(l1);
  cp.add(lbl);
  }

public void valueChanged(ListSelectionEvent e)
 {
  //check if user selected an item or not
  if (l1.getSelectedIndex() == -1)
      { lbl.setText("no items selected"); }
  else
     {
        int indx = l1.getSelectedIndex();
        lbl.setText("price: "+price[indx]);
      }
   }
 }

class Prac1
 {
  public static void main(String args[])
   {
    MyFrame mf = new MyFrame();
    mf.setVisible(true);
   }
 }




2|Page
Advance Java



PRACTICAL 02:

Write a java program to demonstrate typical Editable Table, describing
employee details for a software company.

Prac2.java:

import java.awt.*;
import javax.swing.*;

class MyFrame extends JFrame
 {
  JTable jt;
  JScrollPane jsp;

 //create 2D array to store the table data
 Object[][] data = {
                    {"Shledon", "Cooper", "System Associate", new Integer(5)},
                    {"Leonard", "Hofstadter", "System Tester", new Integer(3)},
                    {"Kunal", "Kotherppalli", "Web Designer", new Integer(2)},
                    {"Penny", "Cuoco", "System Associate", new Integer(20)},
                    {"Joey", "Tribiani", "Network Admin", new Integer(10)}
                   };

 //create a 1D array to store table headers
  String[] title = {"First Name", "Last Name","Position","Experience"};

 public MyFrame()
   {
    //call parent constructor
    super();

    //decide size of frame
    setSize( 300, 300 );

    //obtain the content pane to add the components.
    Container cp = this.getContentPane();

    //decide layout
    cp.setLayout( new FlowLayout() );

    //instantiate components

3|Page
Advance Java


         jt = new JTable(data, title);

         //add table to a scroll pane so that table headers can be visible
         jsp = new JScrollPane(jt);

         add scroll pane to container
         cp.add(jsp);
     }
 }

class Prac2
 {
  public static void main(String args[])
   {
    MyFrame mf = new MyFrame();
    mf.setVisible(true);
   }
 }




4|Page
Advance Java




PRACTICAL 03:

Write a java program using Split pane to demonstrate a screen divided in two
parts, one part contains the names of Planets and another Displays the image
of planet. When user selects the planet name form Left screen, appropriate
image of planet displayed in right screen.


Prac3.java:

import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;

class MyFrame extends JFrame implements ListSelectionListener
 {
   JList lst;
   JLabel lbl;

   //create 1D array to store planet names
   String planets[] =
{"mercury","venus","earth","mars","jupiter","saturn","uranus","neptune","pluto"};

  public MyFrame()
   {
     //call parent constructor
     super();

     //decide size of frame
     setSize(150, 150);

     //instantiate components
     lst = new JList(planets);
     lbl = new JLabel(" ");

       //create the split pane
       JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true,
lst, lbl);

     //add split pane to frame
     cp.add(splitPane);


5|Page
Advance Java



         //register list to respond to events.
         lst.addListSelectionListener(this);
     }

public void valueChanged(ListSelectionEvent e)
  {
    //check if the user has selected an item or not:
    if (e.getSelectedIndex() == -1)
      {
       lbl.setText("Please select a planet..");
      }
      else
        {
          //obtain the selected item:
          String str = lst.getSelectedValue().toString();

              //set the image for the label:
             lbl.setIcon(new ImageIcon(str+".jpg"));
         }
     }
 }

class Prac3
  {
   public static void main(String args[])
    {
      MyFrame mf = new MyFrame();
      mf.setVisible(true);
     }
  }




6|Page
Advance Java


PRACTICAL 04:

Develop Simple Servlet Question Answer Application.

index.html:

<html>
   <body>
    <form action="processAnswer" method="post">
       Q.1. What is 2+2? <br/>
       <input type="radio" name="q1" value="1"/>1 <br/>
       <input type="radio" name="q1" value="2"/>2 <br/>
       <input type="radio" name="q1" value="3"/>3 <br/>
       <input type="radio" name="q1" value="4"/>4 <br/> <br/>

      Q.2. Which of the following is not a vowel? <br/>
      <input type="radio" name="q2" value="a"/>a <br/>
      <input type="radio" name="q2" value="e"/>e <br/>
      <input type="radio" name="q2" value="i"/>i <br/>
      <input type="radio" name="q2" value="c"/>c <br/> <br/>

      Q.3. Which of the following is a fruit?
      <input type="radio" name="q3" value="potatoe"/>potatoe <br/>
      <input type="radio" name="q3" value="onion"/>onion <br/>
      <input type="radio" name="q3" value="tomatoe"/>tomatoe <br/>
      <input type="radio" name="q3" value="pepper"/>pepper <br/> <br/>

       <input type="submit" value="check"/>
     </form>
   </body>
</html>

processAnswer.java:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class processAnswer extends HttpServlet
  {
   public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException
    {

7|Page
Advance Java


     int correct =0, incorrect=0;

    //obtain the values sent by the user
     String a1=req.getParameter("q1");
     String a2=req.getParameter("q2");
     String a3=req.getParameter("q3");

    //decide the type of response
     res.setContentType("text/html");

    //obtain a print writer object to print o/p to user
     PrintWriter pw = res.getWriter();

    //check if user’s selection matches correct ans accdngly change counter val
     if(a1.equals("4")) {correct ++;}
     else{incorrect++;}

     if(a2.equals("c")) {correct ++;}
     else{incorrect++;}

     if(a3.equals("tomatoe")) {correct ++;}
     else{incorrect++;}

    //display the result to user
     pw.println("Correct: " + correct + " Incorrect: "+incorrect);

     //close the print write
      pw.close();
    }
}




8|Page
Advance Java


PRACTICAL 05:

Develop Servlet Application of Basic Calculator (+,-,*, /, %).

index.html:

<html>
   <body>
    <form action="calculate" method="post">
       Number: <input type="text" name="t1"/> <br/>

      <select name="op">
         <option value="+">+</option>
         <option value="-">-</option>
         <option value="/">/</option>
         <option value="*">*</option>
         <option value="%">%</option>
       </select> <br/>

       Number: <input type="text" name="t2"/> <br/>

        <input type="submit" value="calculate"/>
     </form>
   </body>
</html>



calculate.java:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class calculate extends HttpServlet
  {
   public void doPost(HttpServletRequest req, HttpServletResponse res)
         throws ServletException, IOException
    {
      //obtain values from user’s html page
      int num1 = Integer.parseInt(req.getParameter("t1"));
      int num2 = Integer.parseInt(req.getParameter("t2"));
      String op = req.getParameter("op");


9|Page
Advance Java



        //set the kknid of data to be sent
        res.setContentType("text/html");

        //obtain print writer object to print o/p to user
        PrintWriter pw = res.getWriter();

        //check the operation selected and perform the task
        if(op.equals("+")) { pw.println((num1+num2));}

        else if(op.equals("-")) { pw.println((num1-num2));}

        else if(op.equals("/")) { pw.println((num1/num2));}

        else if(op.equals("*")) { pw.println((num1*num2));}

        else { pw.println((num1%num2));}

        //close the print writer
        pw.close();
    }
}




10 | P a g e
Advance Java


PRACTICAL 06:

Develop a JSP Application to accept Registration Details form user and Store
it into the database table.

index.html:

<html>
   <body>
    <form action="Register.jsp" method="post">
       User-Id: <input type="text" name="t1"/> <br/>
       Password: <input type="password" name="t2"/> <br/>
       First Name: <input type="text" name="t3"/> <br/>
       Last Name: <input type="text" name="t4"/> <br/>
       Email: <input type="text" name="t5"/> <br/>
       <input type="submit" value="register"/>
     </form>
   </body>
</html>



Register.jsp:

//import JDBC API package using page directive
<%@page import="java.sql.*"%>

//code logic in scritplet
<%
//obtain values entered by user
String user_id=request.getParameter("t1");
String password=request.getParameter("t2");
String first_name=request.getParameter("t3");
String last_name=request.getParameter("t4");
String email=request.getParameter("t5");

try
  {
   //load driver
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

   //establish connection
   Connection con=DriverManager.getConnection("jdbc:odbc:myDsn");


11 | P a g e
Advance Java


   //create statement
   PreparedStatement ps = con.prepareStatement("insert into reg values
                                                    (?,?,?,?,?)");

   //sert the values in the question mark
   ps.setString(1, user_id);
   ps.setString(2, password);
   ps.setString(3, first_name);
   ps.setString(4, last_name);
   ps.setString(5, email);

   //execute query
   ps.executeUpdate();

   //diaply o/p to user
   out.println("Registration done!");
  }
catch(Exception e) {out.println("Error: "+e);}
%>




12 | P a g e
Advance Java


PRACTICAL 07:

Develop a JSP Application to Authenticate User Login as per the registration
details. If login success the forward user to Index Page otherwise show login
failure Message.

index.html:

<html>
   <body>
    <form action="authenticate.jsp" method="post">
       User-Id: <input type="text" name="t1"/> <br/>
       Password: <input type="password" name="t2"/> <br/>
       <input type="submit" value="login"/>
     </form>
   </body>
</html>



authenticate.jsp

//import JDBC API using page directive
<%@page import="java.sql.*"%>

//code logic in scriptlet
<%

//obtain values entered by user
String user_id=request.getParameter("t1");
String password=request.getParameter("t2");

try
  {
   //load driver
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

   //establish connection
   Connection con=DriverManager.getConnection("jdbc:odbc:myDsn");

   //create statement
   PreparedStatement ps = con.prepareStatement("select * from reg where
                                                 user_id=? and password=?");


13 | P a g e
Advance Java


   //set values for question marks
   ps.setString(1, user_id);
   ps.setString(2, password);

   //execute query
   ResultSet rs=ps.executeQuery();

  //check if user and pwd are correct and accdngly perform task
  if (rs.next()) {response.sendRedirect("welcome.html");}
  else {out.println("could not login!");}
  }
catch(Exception e) {out.println("Error: "+e);}
%>




14 | P a g e
Advance Java


PRACTICAL 08:

Develop a web application to add items in the inventory using JSF.

index.xhtml:

<html xmlns="http://www.w3.org/1999/xhtml"
   xmlns:h="http://java.sun.com/jsf/html"
   xmlns:f="http://java.sun.com/jsf/core">

   <h:body>
      <h:form>
         Item Name: <h:inputText id="t1" value="#{inventory.item}"/> <br/>

         Item Price: <h:inputText id="t2" value="#{inventory.price}">
                   <f:convertNumber type="number"/>
                </h:inputText> <br/>

         Item Quantity: <h:inputText id="t2" value="#{inventory.qty}">
                  <f:convertNumber type="number"/>
               </h:inputText>

        <h:commandButton id="btn" value="Add Item"
                         action="#{inventory.addItem()}"/>
        </h:form>
   </h:body>
</html>



Inventory.java:

import javax.faces.bean.*;
import java.sql.*;

@ManagedBean
@SessionScoped
public class Inventory
{
  String item;
  int price, qty;

   public String getItem() { return item; }


15 | P a g e
Advance Java



    public void setItem(String item) { this.item = item; }

     public int getPrice() { return price; }

     public void setPrice(int price) { this.price = price; }

     public int getQty() { return qty; }

     public void setQty(int qty) { this.qty = qty; }

     public String addItem()
     {
       try
       {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con=DriverManager.getConnection("jdbc:odbc:myDsn");

         PreparedStatement ps = con.prepareStatement("insert into inven values
                                                         (?,?,?)");
         ps.setString(1, item);
         ps.setInt(2, price);
         ps.setInt(3, qty);

         ps.executeUpdate();

          return "success";
         }
         catch(Exception e)
            {return "fail";}
     }
}




16 | P a g e
Advance Java




faces-config.xml

<faces-config version="2.0"
   xmlns="http://java.sun.com/xml/ns/javaee" >

<navigation-rule>
       <from-view-id>index.xhtml</from-view-id>
       <navigation-case>
              <from-action>#{inventory.addItem()}</from-action>
              <from-outcome>success</from-outcome>
              <to-view-id>page1.xhtml</to-view-id>
       </navigation-case>

       <navigation-case>
              <from-action>#{inventory.addItem()}</from-action>
              <from-outcome>fail</from-outcome>
              <to-view-id>page2.xhtml</to-view-id>
       </navigation-case>
   </navigation-rule>
</faces-config>




17 | P a g e
Advance Java


PRACTICAL 09:

Develop a Room Reservation System Application Using Enterprise Java Beans.

ReservationBean.java:

package ejb;
import javax.ejb.Stateless;
import java.sql.*;

@Stateless
public class ReservationBean
 {
   public boolean canReserve(String name, String startDate, String endDate)
   {
     try
     {
        boolean flag=true;

         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         Connection con=DriverManager.getConnection("jdbc:odbc:myDsn");

       PreparedStatement ps = con.prepareStatement("select * from reservation
where startDate=?");
       ps.setDate(1,Date.valueOf(startDate) );

         ResultSet rs=ps.executeQuery();

       if (rs.next()) {flag=false;}
       else
         {
PreparedStatement ps1 = con.prepareStatement("insert into reservation values
                                                    (?,?,?)");
            ps.setString(1,name);
            ps.setDate(2,Date.valueOf(startDate) );
            ps.setDate(3,Date.valueOf(endDate) );
            ps.executeUpdate();
            flag=true;
         }
     return flag;
    }
    catch(Exception e) {return false;} } }



18 | P a g e
Advance Java


myServlet.java:

import    ejb.*;
import    javax.ejb.*;
import    java.io.*;
import    javax.servlet.*;
import    javax.servlet.http.*;

public class myServlet extends HttpServlet {

    @EJB
    private ReservationBean myBean;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException
    {
      String name = request.getParameter("t1");
      String startDate = request.getParameter("t2");
      String endDate = request.getParameter("t3");

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        boolean ans=myBean.canReserve(name, startDate, endDate);
        if(ans==true) {out.println("room has been reserved.");}
        else {out.println("room could not be reserved.");}
    }
}



index.html:

<html>
   <body>
    <form action="myServlet" method="get">
       Name: <input type="text" name="t1"/> <br/>
       Start Date: <input type="text" name="t2"/> <br/>
       End Date: <input type="text" name="t3"/> <br/>
       <input type="submit" value="reserve room"/>
     </form>
   </body> </html>




19 | P a g e
Advance Java


PRACTICAL 10:

Develop a Hibernate application to store Feedback of Website Visitor in
MySQL Database.

myBean.java:

package myApp;
import java.io.Serializable;

public class myBean implements Serializable{
  private String name;
  private String message;
  private Integer id;

    public myBean () {}

    public myBean (Integer i,String nm) {name=nm; id=i;}

    public void setName(String nm) {name=nm;}

    public String getName() {return name;}

    public void setMessage(String m) {message=m;}

    public String getMessage() {return message;}

    public Integer getId(){return id;}

    public void setId(Integer i) {id=i;}
}

Feedback.hbm.xml:

<hibernate-mapping>
   <class name="myApp.myBean" table="myFeedback" catalog="myDB">
      <id name="id" type="java.lang.Integer">
         <column name="userNo"/>
         <generator class="identity"/>
      </id>

      <property name="name" type="java.lang.String">
         <column name="name" length="25"/>

20 | P a g e
Advance Java


      </property>

      <property name="message" type="java.lang.String">
         <column name="message" length="120"/>
      </property>
   </class>
</hibernate-mapping>



hibernate.cgf.xml:

<hibernate-configuration>
 <session-factory>
   <property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
   <property
name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
   <property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/myDB</property>
   <property name="hibernate.connection.username">root</property>
   <property name="hibernate.connection.password">1234</property>
   <mapping resource="myApp/Feedback.hbm.xml"/>
 </session-factory>
</hibernate-configuration>



storeFeedback.jsp:

<%@page import="org.hibernate.*, org.hibernate.cfg.*, myApp.myBean"%>

<%!SessionFactory sf;
Session s; %>
<%
String name=request.getParameter("t1");
String message=request.getParameter("t2");

sf=new Configuration().configure().buildSessionFactory();
s=sf.openSession();

Transaction t=null;
myBean bean=new myBean();

try

21 | P a g e
Advance Java


  {
   t=s.beginTransaction();
   bean.setName(name);
   bean.setMessage(message);

   s.save(bean);
   t.commit();
   out.println("Added record!");
  }

catch(RuntimeException e)
  {
  if(t != null) t.rollback();
  out.println(e);
  }
%>



index.html:

<html>
   <body>
    <form action="storeFeedback.jsp" method="post">
       Name: <input type="text" name="t1"/> <br/>
       Message: <input type="text" name="t2"/> <br/>
       <input type="submit" value="store feedback"/>
     </form>
   </body>
</html>




22 | P a g e
Advance Java




PRACTICAL 11:

Develop a simple Struts Application to Demonstrate 3 page Website of
Teaching Classes which passes values from every page to another

First.java:

package coaching;
import com.opensymphony.xwork2.*;

public class First extends ActionSupport
{
 String first_name, last_name, course, college;

    public String getCollege() { return college; }

    public void setCollege(String c) { college = c; }

    public String getCourse() { return course; }

    public void setCourse(String c) { course = c; }

    public String getFirst_name() { return first_name; }

    public void setFirst_name(String f) { first_name = f; }

    public String getLast_name() { return last_name; }

    public void setLast_name(String l) { last_name = l; }

    public String execute()
    { return "secondPage"; }
}




23 | P a g e
Advance Java




Second.java:

package coaching;
import com.opensymphony.xwork2.*;

public class Second extends ActionSupport
{
 String first_name, last_name, course, college;

     public String getCollege() { return college; }

     public void setCollege(String c) { college = c; }

     public String getCourse() { return course; }

     public void setCourse(String c) { course = c; }

     public String getFirst_name() { return first_name; }

     public void setFirst_name(String f) { first_name = f; }

     public String getLast_name() { return last_name; }

     public void setLast_name(String l) { last_name = l; }

     public String execute()
     { return "thirdPage"; }
}

struts.xml:

<struts>
<package name="/" extends="struts-default">
 <action name="First" class="coaching.First">
   <result name="secondPage">/page2.jsp</result>
 </action>

    <action name="Second" class="coaching.Second">
      <result name="thirdPage">/page3.jsp</result>
    </action>

24 | P a g e
Advance Java


</package>
</struts>

page1.jsp:

<%@taglib prefix="s" uri="/struts-tags" %>
<html>
   <body>
      <s:form method="get" action="coaching/First.action">
         First Name: <s:textfield name="first_name"/> <br/>
         Last Name: <s:textfield name="last_name"/>
         <s:submit value="click me!"/>
      </s:form>
   </body>
</html>

page2.jsp:

<%@taglib prefix="s" uri="/struts-tags" %>
<html>
   <body>
     <s:form method="get" action="coaching/Second.action">
        <s:hidden name="first_name"/> <br/>
        <s:hidden name="last_name"/> <br/>

         College: <s:textfield name="college"/> <br/>
         Course: <s:textfield name="course"/>
         <s:submit value="click me!"/>
      </s:form>
   </body>
</html>

page3.jsp:

<%@taglib prefix="s" uri="/struts-tags" %>
<html>
   <body>
     <s:form method="get" action="coaching/First.action">
       You entered the following data: <br/>
        First Name: <s:property value="first_name"/> <br/>
        Last Name: <s:property value="last_name"/> <br/>
        College: <s:property value="college"/> <br/>
        Course: <s:property value="course"/> <br/>

25 | P a g e
Advance Java


     </s:form>
  </body> </html>
PRACTICAL 12:
Develop a simple Struts Application to Demonstrate E-mail Validator.

Validate.java:

package check;

import java.util.regex.*;
import com.opensymphony.xwork2.*;

public class Validate extends ActionSupport
{
 String email;

    public String getEmail() { return name; }

    public void setEmail(String e) { email = e; }

  public String execute()
  {
    String pattern ="^[_A-Za-z0-9]+(.[_A-Za-z0-9]+)*@[A-Za-z0-9]+(.[A-Za-
z0-9]+)*";

        Pattern p=Pattern.compile(pattern);
        Matcher m=p.matcher(email);
        boolean flg=m.matches();

        if(flag==true) {return "yes";}
        else {return "no";}
    }
}




26 | P a g e
Advance Java




struts.xml:

<struts>
<package name="/" extends="struts-default">
 <action name="Validate" class="check.Validate">
   <result name="yes">/page1.html</result>
   <result name="no">/page2.html</result>
 </action>
</package>
</struts>

index.jsp:

<%@taglib prefix="s" uri="/struts-tags" %>
<html>
   <body>
      <s:form method="get" action="check/Validate.action">
         Enter your Email ID: <s:textfield name="email"/>
         <s:submit value="click me!"/>
      </s:form>
   </body>
</html>



page1.html:

<html>
   <body>
     <p> Emial ID is correct </p>
   </body>
</html>



page2.html:

<html>
   <body>
     <p> Emial ID is not correct </p>
   </body>
</html>

27 | P a g e
Advance Java




28 | P a g e
Advance Java


PRACTICAL 13:

Develop a simple “Hello World” Web Service in Java.

HelloUser.java:

package myPack;

import   javax.jws.WebService;
import   javax.jws.WebMethod;
import   javax.jws.WebParam;
import   javax.ejb.Stateless;

@WebService( )
@Stateless()
public class HelloUser {

    @WebMethod( )
    public String sayHello(@WebParam( ) String name) {
      return "Hello, "+name+" ..!! Welcome to web services :) ";
    }
}



myServlet.java:

import   java.io.*;
import   javax.servlet.*;
import   javax.servlet.http.*;
import   javax.xml.ws.*;
import   pack.*;

public class myServlet extends HttpServlet {
  @WebServiceRef(wsdlLocation = "WEB-
INF/wsdl/localhost_8080/HelloUser/HelloUser.wsdl")
  private HelloUser_Service service;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException
       {
         String nm = request.getParameter("t1");
         response.setContentType("text/html");
         PrintWriter pw = response.getWriter();

29 | P a g e
Advance Java


         String ans=sayHello(nm);
         pw.println("<h2>"+ans+"</h2>");
         pw.close();
    }

    private String sayHello(java.lang.String user) {
       pack.HelloUser port = service.getHelloUserPort();
       return port.sayHello(user);
    }

}



index.html:

<html>
 <body>
  <form action="myServlet" method="get">
   Name: <input type="text" name="t1"/>
   <input type="submit" value="click me"/>
   </form>
 </body>
</html>




30 | P a g e
Advance Java




PRACTICAL 14:

Develop an application to show searching the Directory using JNDI capabilities

Dir.java:

import javax.naming.*;
import java.util.*;

class Dir
{
  pulbic static void main(String a[])
   {
    String addr="file:ad_java";

    Hashtable args = new Hashtable();

args.put(Context.INITIAL_CONTEXT_FACTORY,"test.sun.jndi.fscontext.FSConte
xtFactory");
   args.put(Context.PROVIDER_URL,addr);

    try
      {
          Context c = new InitialContext(args);
          NamingEnumeration ne = c.listBindings("");

          while(ne.hasMore())
            {
              Binding b = (Binding) ne.next();
              System.out.println("File: "+b.getName());
            }
          c.close();
       }
     catch(Exception e)
       { System.out.println("Error: "+e);}
    }
}




31 | P a g e
Advance Java




PRACTICAL 15:

Develop a program to show file access using JNDI capabilities.

import javax.naming.*;
import java.util.*;

class FileAccess
{
  pulbic static void main(String a[])
   {
    String file_nm="abc.txt";

    Hashtable args = new Hashtable();

args.put(Context.INITIAL_CONTEXT_FACTORY,"test.sun.jndi.fscontext.FSConte
xtFactory");

    try
      {
          Context ctx=new InitialContext();
          Object obj = ctx.lookup(name);
          System.out.println("The file is located at: "+obj);
          ctx.close();
       }
     catch(Exception e)
       { System.out.println("Error: "+e);}
    }
}




32 | P a g e

Contenu connexe

Tendances

Methods to test an e-learning Web application.
Methods to test an e-learning Web application.Methods to test an e-learning Web application.
Methods to test an e-learning Web application.
telss09
 
19701759 project-report-on-railway-reservation-system-by-amit-mittal
19701759 project-report-on-railway-reservation-system-by-amit-mittal19701759 project-report-on-railway-reservation-system-by-amit-mittal
19701759 project-report-on-railway-reservation-system-by-amit-mittal
satyaragha786
 

Tendances (20)

Visual Studio IDE
Visual Studio IDEVisual Studio IDE
Visual Studio IDE
 
Methods to test an e-learning Web application.
Methods to test an e-learning Web application.Methods to test an e-learning Web application.
Methods to test an e-learning Web application.
 
Python projects
Python projectsPython projects
Python projects
 
19701759 project-report-on-railway-reservation-system-by-amit-mittal
19701759 project-report-on-railway-reservation-system-by-amit-mittal19701759 project-report-on-railway-reservation-system-by-amit-mittal
19701759 project-report-on-railway-reservation-system-by-amit-mittal
 
resume builder.pptx
resume builder.pptxresume builder.pptx
resume builder.pptx
 
Performance optimization for Android
Performance optimization for AndroidPerformance optimization for Android
Performance optimization for Android
 
Liang- Barsky Algorithm, Polygon clipping & pipeline clipping of polygons
Liang- Barsky Algorithm, Polygon clipping & pipeline clipping of polygonsLiang- Barsky Algorithm, Polygon clipping & pipeline clipping of polygons
Liang- Barsky Algorithm, Polygon clipping & pipeline clipping of polygons
 
Visual studio
Visual studioVisual studio
Visual studio
 
Industrial Training report on java
Industrial  Training report on javaIndustrial  Training report on java
Industrial Training report on java
 
Content management system
Content management systemContent management system
Content management system
 
JAVA PPT by NAVEEN TOKAS
JAVA PPT by NAVEEN TOKASJAVA PPT by NAVEEN TOKAS
JAVA PPT by NAVEEN TOKAS
 
Sih ppt
Sih pptSih ppt
Sih ppt
 
Software Engineering - The Making of a Weather Application
Software Engineering - The Making of a Weather Application Software Engineering - The Making of a Weather Application
Software Engineering - The Making of a Weather Application
 
Octree Encoding- used in Computational Methods
Octree Encoding- used in Computational MethodsOctree Encoding- used in Computational Methods
Octree Encoding- used in Computational Methods
 
Report summer training core java
Report summer training core javaReport summer training core java
Report summer training core java
 
ANPR
ANPRANPR
ANPR
 
Android application development ppt
Android application development pptAndroid application development ppt
Android application development ppt
 
Eclipse IDE
Eclipse IDEEclipse IDE
Eclipse IDE
 
Odi 12c-getting-started-guide-2032250
Odi 12c-getting-started-guide-2032250Odi 12c-getting-started-guide-2032250
Odi 12c-getting-started-guide-2032250
 
Synopsis for Online Railway Railway Reservation System
Synopsis for Online Railway Railway Reservation SystemSynopsis for Online Railway Railway Reservation System
Synopsis for Online Railway Railway Reservation System
 

En vedette

Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
Java Code for Sample Projects Inheritance
Java Code for Sample Projects InheritanceJava Code for Sample Projects Inheritance
Java Code for Sample Projects Inheritance
jwjablonski
 
Practical java
Practical javaPractical java
Practical java
nirmit
 
9781111530532 ppt ch14
9781111530532 ppt ch149781111530532 ppt ch14
9781111530532 ppt ch14
Terry Yoast
 
AWS Innovate: AWS Container Management using Amazon EC2 Container Service an...
AWS Innovate:  AWS Container Management using Amazon EC2 Container Service an...AWS Innovate:  AWS Container Management using Amazon EC2 Container Service an...
AWS Innovate: AWS Container Management using Amazon EC2 Container Service an...
Amazon Web Services Korea
 

En vedette (20)

Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer science
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Java codes
Java codesJava codes
Java codes
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
Java Code for Sample Projects Inheritance
Java Code for Sample Projects InheritanceJava Code for Sample Projects Inheritance
Java Code for Sample Projects Inheritance
 
Linux practicals T.Y.B.ScIT
Linux practicals T.Y.B.ScITLinux practicals T.Y.B.ScIT
Linux practicals T.Y.B.ScIT
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 
Advance Java
Advance JavaAdvance Java
Advance Java
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for viva
 
Tybsc it sem5 advanced java_practical_soln_downloadable
Tybsc it sem5 advanced java_practical_soln_downloadableTybsc it sem5 advanced java_practical_soln_downloadable
Tybsc it sem5 advanced java_practical_soln_downloadable
 
Practical java
Practical javaPractical java
Practical java
 
9781285852744 ppt ch16
9781285852744 ppt ch169781285852744 ppt ch16
9781285852744 ppt ch16
 
Chap01
Chap01Chap01
Chap01
 
9781111530532 ppt ch14
9781111530532 ppt ch149781111530532 ppt ch14
9781111530532 ppt ch14
 
Data Structures- Part2 analysis tools
Data Structures- Part2 analysis toolsData Structures- Part2 analysis tools
Data Structures- Part2 analysis tools
 
Data Structures- Part9 trees simplified
Data Structures- Part9 trees simplifiedData Structures- Part9 trees simplified
Data Structures- Part9 trees simplified
 
AWS Innovate: AWS Container Management using Amazon EC2 Container Service an...
AWS Innovate:  AWS Container Management using Amazon EC2 Container Service an...AWS Innovate:  AWS Container Management using Amazon EC2 Container Service an...
AWS Innovate: AWS Container Management using Amazon EC2 Container Service an...
 

Similaire à Ad java prac sol set

33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
Step By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts AppStep By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts App
Syed Shahul
 
Exercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera CymbronExercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera Cymbron
cymbron
 
Need help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdfNeed help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdf
meerobertsonheyde608
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
JavaScript para Graficos y Visualizacion de Datos
JavaScript para Graficos y Visualizacion de DatosJavaScript para Graficos y Visualizacion de Datos
JavaScript para Graficos y Visualizacion de Datos
philogb
 
Enterprise workflow with Apps Script
Enterprise workflow with Apps ScriptEnterprise workflow with Apps Script
Enterprise workflow with Apps Script
ccherubino
 

Similaire à Ad java prac sol set (20)

比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Week 12 code
Week 12 codeWeek 12 code
Week 12 code
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Step By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts AppStep By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts App
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Exercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera CymbronExercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera Cymbron
 
Need help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdfNeed help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdf
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
Ajax - a quick introduction
Ajax - a quick introductionAjax - a quick introduction
Ajax - a quick introduction
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
 
DWR, Hibernate and Dojo.E - A Tutorial
DWR, Hibernate and Dojo.E - A TutorialDWR, Hibernate and Dojo.E - A Tutorial
DWR, Hibernate and Dojo.E - A Tutorial
 
Lab manual asp.net
Lab manual asp.netLab manual asp.net
Lab manual asp.net
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
JavaScript Lessons 2023
JavaScript Lessons 2023JavaScript Lessons 2023
JavaScript Lessons 2023
 
JavaScript para Graficos y Visualizacion de Datos
JavaScript para Graficos y Visualizacion de DatosJavaScript para Graficos y Visualizacion de Datos
JavaScript para Graficos y Visualizacion de Datos
 
Enterprise workflow with Apps Script
Enterprise workflow with Apps ScriptEnterprise workflow with Apps Script
Enterprise workflow with Apps Script
 
Mobile Day - React Native
Mobile Day - React NativeMobile Day - React Native
Mobile Day - React Native
 

Dernier

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 

Dernier (20)

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 

Ad java prac sol set

  • 1. Advance Java (Sem 5 – T.Y.B.Sc.I.T.) Iram Ramrajkar PRACTICAL 01: Write a java program to present a set of choices for a user to select Stationary products and display the price of Product after Selection from the list. Prac1.java: import javax.swing.*; import java.awt.*; import javax.swing.event.*; class MyFrame extends JFrame implements ListSelectionListener { Container cp; JList l1; JLabel lbl; //creating a 1D array to store the items String[] items ={"pen","pencil","ruler","eraser","sharpner"}; //creating another 1D array to store their prices. int[] price={12,13,15,5,5,25,35}; MyFrame() { //call parent constructor super(); //decide size of the frame setSize(400,400); //obtain the content pane to add components cp=this.getContentPane(); //decide layout cp.setLayout(new FlowLayout()); //instantiate components l1=new JList(items); lbl=new JLabel(" "); //register list to respond to events 1|Page
  • 2. Advance Java l1.addListSelectionListener(this); //add components to container cp.add(l1); cp.add(lbl); } public void valueChanged(ListSelectionEvent e) { //check if user selected an item or not if (l1.getSelectedIndex() == -1) { lbl.setText("no items selected"); } else { int indx = l1.getSelectedIndex(); lbl.setText("price: "+price[indx]); } } } class Prac1 { public static void main(String args[]) { MyFrame mf = new MyFrame(); mf.setVisible(true); } } 2|Page
  • 3. Advance Java PRACTICAL 02: Write a java program to demonstrate typical Editable Table, describing employee details for a software company. Prac2.java: import java.awt.*; import javax.swing.*; class MyFrame extends JFrame { JTable jt; JScrollPane jsp; //create 2D array to store the table data Object[][] data = { {"Shledon", "Cooper", "System Associate", new Integer(5)}, {"Leonard", "Hofstadter", "System Tester", new Integer(3)}, {"Kunal", "Kotherppalli", "Web Designer", new Integer(2)}, {"Penny", "Cuoco", "System Associate", new Integer(20)}, {"Joey", "Tribiani", "Network Admin", new Integer(10)} }; //create a 1D array to store table headers String[] title = {"First Name", "Last Name","Position","Experience"}; public MyFrame() { //call parent constructor super(); //decide size of frame setSize( 300, 300 ); //obtain the content pane to add the components. Container cp = this.getContentPane(); //decide layout cp.setLayout( new FlowLayout() ); //instantiate components 3|Page
  • 4. Advance Java jt = new JTable(data, title); //add table to a scroll pane so that table headers can be visible jsp = new JScrollPane(jt); add scroll pane to container cp.add(jsp); } } class Prac2 { public static void main(String args[]) { MyFrame mf = new MyFrame(); mf.setVisible(true); } } 4|Page
  • 5. Advance Java PRACTICAL 03: Write a java program using Split pane to demonstrate a screen divided in two parts, one part contains the names of Planets and another Displays the image of planet. When user selects the planet name form Left screen, appropriate image of planet displayed in right screen. Prac3.java: import javax.swing.*; import java.awt.*; import javax.swing.event.*; class MyFrame extends JFrame implements ListSelectionListener { JList lst; JLabel lbl; //create 1D array to store planet names String planets[] = {"mercury","venus","earth","mars","jupiter","saturn","uranus","neptune","pluto"}; public MyFrame() { //call parent constructor super(); //decide size of frame setSize(150, 150); //instantiate components lst = new JList(planets); lbl = new JLabel(" "); //create the split pane JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, lst, lbl); //add split pane to frame cp.add(splitPane); 5|Page
  • 6. Advance Java //register list to respond to events. lst.addListSelectionListener(this); } public void valueChanged(ListSelectionEvent e) { //check if the user has selected an item or not: if (e.getSelectedIndex() == -1) { lbl.setText("Please select a planet.."); } else { //obtain the selected item: String str = lst.getSelectedValue().toString(); //set the image for the label: lbl.setIcon(new ImageIcon(str+".jpg")); } } } class Prac3 { public static void main(String args[]) { MyFrame mf = new MyFrame(); mf.setVisible(true); } } 6|Page
  • 7. Advance Java PRACTICAL 04: Develop Simple Servlet Question Answer Application. index.html: <html> <body> <form action="processAnswer" method="post"> Q.1. What is 2+2? <br/> <input type="radio" name="q1" value="1"/>1 <br/> <input type="radio" name="q1" value="2"/>2 <br/> <input type="radio" name="q1" value="3"/>3 <br/> <input type="radio" name="q1" value="4"/>4 <br/> <br/> Q.2. Which of the following is not a vowel? <br/> <input type="radio" name="q2" value="a"/>a <br/> <input type="radio" name="q2" value="e"/>e <br/> <input type="radio" name="q2" value="i"/>i <br/> <input type="radio" name="q2" value="c"/>c <br/> <br/> Q.3. Which of the following is a fruit? <input type="radio" name="q3" value="potatoe"/>potatoe <br/> <input type="radio" name="q3" value="onion"/>onion <br/> <input type="radio" name="q3" value="tomatoe"/>tomatoe <br/> <input type="radio" name="q3" value="pepper"/>pepper <br/> <br/> <input type="submit" value="check"/> </form> </body> </html> processAnswer.java: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class processAnswer extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { 7|Page
  • 8. Advance Java int correct =0, incorrect=0; //obtain the values sent by the user String a1=req.getParameter("q1"); String a2=req.getParameter("q2"); String a3=req.getParameter("q3"); //decide the type of response res.setContentType("text/html"); //obtain a print writer object to print o/p to user PrintWriter pw = res.getWriter(); //check if user’s selection matches correct ans accdngly change counter val if(a1.equals("4")) {correct ++;} else{incorrect++;} if(a2.equals("c")) {correct ++;} else{incorrect++;} if(a3.equals("tomatoe")) {correct ++;} else{incorrect++;} //display the result to user pw.println("Correct: " + correct + " Incorrect: "+incorrect); //close the print write pw.close(); } } 8|Page
  • 9. Advance Java PRACTICAL 05: Develop Servlet Application of Basic Calculator (+,-,*, /, %). index.html: <html> <body> <form action="calculate" method="post"> Number: <input type="text" name="t1"/> <br/> <select name="op"> <option value="+">+</option> <option value="-">-</option> <option value="/">/</option> <option value="*">*</option> <option value="%">%</option> </select> <br/> Number: <input type="text" name="t2"/> <br/> <input type="submit" value="calculate"/> </form> </body> </html> calculate.java: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class calculate extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //obtain values from user’s html page int num1 = Integer.parseInt(req.getParameter("t1")); int num2 = Integer.parseInt(req.getParameter("t2")); String op = req.getParameter("op"); 9|Page
  • 10. Advance Java //set the kknid of data to be sent res.setContentType("text/html"); //obtain print writer object to print o/p to user PrintWriter pw = res.getWriter(); //check the operation selected and perform the task if(op.equals("+")) { pw.println((num1+num2));} else if(op.equals("-")) { pw.println((num1-num2));} else if(op.equals("/")) { pw.println((num1/num2));} else if(op.equals("*")) { pw.println((num1*num2));} else { pw.println((num1%num2));} //close the print writer pw.close(); } } 10 | P a g e
  • 11. Advance Java PRACTICAL 06: Develop a JSP Application to accept Registration Details form user and Store it into the database table. index.html: <html> <body> <form action="Register.jsp" method="post"> User-Id: <input type="text" name="t1"/> <br/> Password: <input type="password" name="t2"/> <br/> First Name: <input type="text" name="t3"/> <br/> Last Name: <input type="text" name="t4"/> <br/> Email: <input type="text" name="t5"/> <br/> <input type="submit" value="register"/> </form> </body> </html> Register.jsp: //import JDBC API package using page directive <%@page import="java.sql.*"%> //code logic in scritplet <% //obtain values entered by user String user_id=request.getParameter("t1"); String password=request.getParameter("t2"); String first_name=request.getParameter("t3"); String last_name=request.getParameter("t4"); String email=request.getParameter("t5"); try { //load driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //establish connection Connection con=DriverManager.getConnection("jdbc:odbc:myDsn"); 11 | P a g e
  • 12. Advance Java //create statement PreparedStatement ps = con.prepareStatement("insert into reg values (?,?,?,?,?)"); //sert the values in the question mark ps.setString(1, user_id); ps.setString(2, password); ps.setString(3, first_name); ps.setString(4, last_name); ps.setString(5, email); //execute query ps.executeUpdate(); //diaply o/p to user out.println("Registration done!"); } catch(Exception e) {out.println("Error: "+e);} %> 12 | P a g e
  • 13. Advance Java PRACTICAL 07: Develop a JSP Application to Authenticate User Login as per the registration details. If login success the forward user to Index Page otherwise show login failure Message. index.html: <html> <body> <form action="authenticate.jsp" method="post"> User-Id: <input type="text" name="t1"/> <br/> Password: <input type="password" name="t2"/> <br/> <input type="submit" value="login"/> </form> </body> </html> authenticate.jsp //import JDBC API using page directive <%@page import="java.sql.*"%> //code logic in scriptlet <% //obtain values entered by user String user_id=request.getParameter("t1"); String password=request.getParameter("t2"); try { //load driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //establish connection Connection con=DriverManager.getConnection("jdbc:odbc:myDsn"); //create statement PreparedStatement ps = con.prepareStatement("select * from reg where user_id=? and password=?"); 13 | P a g e
  • 14. Advance Java //set values for question marks ps.setString(1, user_id); ps.setString(2, password); //execute query ResultSet rs=ps.executeQuery(); //check if user and pwd are correct and accdngly perform task if (rs.next()) {response.sendRedirect("welcome.html");} else {out.println("could not login!");} } catch(Exception e) {out.println("Error: "+e);} %> 14 | P a g e
  • 15. Advance Java PRACTICAL 08: Develop a web application to add items in the inventory using JSF. index.xhtml: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:body> <h:form> Item Name: <h:inputText id="t1" value="#{inventory.item}"/> <br/> Item Price: <h:inputText id="t2" value="#{inventory.price}"> <f:convertNumber type="number"/> </h:inputText> <br/> Item Quantity: <h:inputText id="t2" value="#{inventory.qty}"> <f:convertNumber type="number"/> </h:inputText> <h:commandButton id="btn" value="Add Item" action="#{inventory.addItem()}"/> </h:form> </h:body> </html> Inventory.java: import javax.faces.bean.*; import java.sql.*; @ManagedBean @SessionScoped public class Inventory { String item; int price, qty; public String getItem() { return item; } 15 | P a g e
  • 16. Advance Java public void setItem(String item) { this.item = item; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getQty() { return qty; } public void setQty(int qty) { this.qty = qty; } public String addItem() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:myDsn"); PreparedStatement ps = con.prepareStatement("insert into inven values (?,?,?)"); ps.setString(1, item); ps.setInt(2, price); ps.setInt(3, qty); ps.executeUpdate(); return "success"; } catch(Exception e) {return "fail";} } } 16 | P a g e
  • 17. Advance Java faces-config.xml <faces-config version="2.0" xmlns="http://java.sun.com/xml/ns/javaee" > <navigation-rule> <from-view-id>index.xhtml</from-view-id> <navigation-case> <from-action>#{inventory.addItem()}</from-action> <from-outcome>success</from-outcome> <to-view-id>page1.xhtml</to-view-id> </navigation-case> <navigation-case> <from-action>#{inventory.addItem()}</from-action> <from-outcome>fail</from-outcome> <to-view-id>page2.xhtml</to-view-id> </navigation-case> </navigation-rule> </faces-config> 17 | P a g e
  • 18. Advance Java PRACTICAL 09: Develop a Room Reservation System Application Using Enterprise Java Beans. ReservationBean.java: package ejb; import javax.ejb.Stateless; import java.sql.*; @Stateless public class ReservationBean { public boolean canReserve(String name, String startDate, String endDate) { try { boolean flag=true; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:myDsn"); PreparedStatement ps = con.prepareStatement("select * from reservation where startDate=?"); ps.setDate(1,Date.valueOf(startDate) ); ResultSet rs=ps.executeQuery(); if (rs.next()) {flag=false;} else { PreparedStatement ps1 = con.prepareStatement("insert into reservation values (?,?,?)"); ps.setString(1,name); ps.setDate(2,Date.valueOf(startDate) ); ps.setDate(3,Date.valueOf(endDate) ); ps.executeUpdate(); flag=true; } return flag; } catch(Exception e) {return false;} } } 18 | P a g e
  • 19. Advance Java myServlet.java: import ejb.*; import javax.ejb.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class myServlet extends HttpServlet { @EJB private ReservationBean myBean; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("t1"); String startDate = request.getParameter("t2"); String endDate = request.getParameter("t3"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); boolean ans=myBean.canReserve(name, startDate, endDate); if(ans==true) {out.println("room has been reserved.");} else {out.println("room could not be reserved.");} } } index.html: <html> <body> <form action="myServlet" method="get"> Name: <input type="text" name="t1"/> <br/> Start Date: <input type="text" name="t2"/> <br/> End Date: <input type="text" name="t3"/> <br/> <input type="submit" value="reserve room"/> </form> </body> </html> 19 | P a g e
  • 20. Advance Java PRACTICAL 10: Develop a Hibernate application to store Feedback of Website Visitor in MySQL Database. myBean.java: package myApp; import java.io.Serializable; public class myBean implements Serializable{ private String name; private String message; private Integer id; public myBean () {} public myBean (Integer i,String nm) {name=nm; id=i;} public void setName(String nm) {name=nm;} public String getName() {return name;} public void setMessage(String m) {message=m;} public String getMessage() {return message;} public Integer getId(){return id;} public void setId(Integer i) {id=i;} } Feedback.hbm.xml: <hibernate-mapping> <class name="myApp.myBean" table="myFeedback" catalog="myDB"> <id name="id" type="java.lang.Integer"> <column name="userNo"/> <generator class="identity"/> </id> <property name="name" type="java.lang.String"> <column name="name" length="25"/> 20 | P a g e
  • 21. Advance Java </property> <property name="message" type="java.lang.String"> <column name="message" length="120"/> </property> </class> </hibernate-mapping> hibernate.cgf.xml: <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myDB</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">1234</property> <mapping resource="myApp/Feedback.hbm.xml"/> </session-factory> </hibernate-configuration> storeFeedback.jsp: <%@page import="org.hibernate.*, org.hibernate.cfg.*, myApp.myBean"%> <%!SessionFactory sf; Session s; %> <% String name=request.getParameter("t1"); String message=request.getParameter("t2"); sf=new Configuration().configure().buildSessionFactory(); s=sf.openSession(); Transaction t=null; myBean bean=new myBean(); try 21 | P a g e
  • 22. Advance Java { t=s.beginTransaction(); bean.setName(name); bean.setMessage(message); s.save(bean); t.commit(); out.println("Added record!"); } catch(RuntimeException e) { if(t != null) t.rollback(); out.println(e); } %> index.html: <html> <body> <form action="storeFeedback.jsp" method="post"> Name: <input type="text" name="t1"/> <br/> Message: <input type="text" name="t2"/> <br/> <input type="submit" value="store feedback"/> </form> </body> </html> 22 | P a g e
  • 23. Advance Java PRACTICAL 11: Develop a simple Struts Application to Demonstrate 3 page Website of Teaching Classes which passes values from every page to another First.java: package coaching; import com.opensymphony.xwork2.*; public class First extends ActionSupport { String first_name, last_name, course, college; public String getCollege() { return college; } public void setCollege(String c) { college = c; } public String getCourse() { return course; } public void setCourse(String c) { course = c; } public String getFirst_name() { return first_name; } public void setFirst_name(String f) { first_name = f; } public String getLast_name() { return last_name; } public void setLast_name(String l) { last_name = l; } public String execute() { return "secondPage"; } } 23 | P a g e
  • 24. Advance Java Second.java: package coaching; import com.opensymphony.xwork2.*; public class Second extends ActionSupport { String first_name, last_name, course, college; public String getCollege() { return college; } public void setCollege(String c) { college = c; } public String getCourse() { return course; } public void setCourse(String c) { course = c; } public String getFirst_name() { return first_name; } public void setFirst_name(String f) { first_name = f; } public String getLast_name() { return last_name; } public void setLast_name(String l) { last_name = l; } public String execute() { return "thirdPage"; } } struts.xml: <struts> <package name="/" extends="struts-default"> <action name="First" class="coaching.First"> <result name="secondPage">/page2.jsp</result> </action> <action name="Second" class="coaching.Second"> <result name="thirdPage">/page3.jsp</result> </action> 24 | P a g e
  • 25. Advance Java </package> </struts> page1.jsp: <%@taglib prefix="s" uri="/struts-tags" %> <html> <body> <s:form method="get" action="coaching/First.action"> First Name: <s:textfield name="first_name"/> <br/> Last Name: <s:textfield name="last_name"/> <s:submit value="click me!"/> </s:form> </body> </html> page2.jsp: <%@taglib prefix="s" uri="/struts-tags" %> <html> <body> <s:form method="get" action="coaching/Second.action"> <s:hidden name="first_name"/> <br/> <s:hidden name="last_name"/> <br/> College: <s:textfield name="college"/> <br/> Course: <s:textfield name="course"/> <s:submit value="click me!"/> </s:form> </body> </html> page3.jsp: <%@taglib prefix="s" uri="/struts-tags" %> <html> <body> <s:form method="get" action="coaching/First.action"> You entered the following data: <br/> First Name: <s:property value="first_name"/> <br/> Last Name: <s:property value="last_name"/> <br/> College: <s:property value="college"/> <br/> Course: <s:property value="course"/> <br/> 25 | P a g e
  • 26. Advance Java </s:form> </body> </html> PRACTICAL 12: Develop a simple Struts Application to Demonstrate E-mail Validator. Validate.java: package check; import java.util.regex.*; import com.opensymphony.xwork2.*; public class Validate extends ActionSupport { String email; public String getEmail() { return name; } public void setEmail(String e) { email = e; } public String execute() { String pattern ="^[_A-Za-z0-9]+(.[_A-Za-z0-9]+)*@[A-Za-z0-9]+(.[A-Za- z0-9]+)*"; Pattern p=Pattern.compile(pattern); Matcher m=p.matcher(email); boolean flg=m.matches(); if(flag==true) {return "yes";} else {return "no";} } } 26 | P a g e
  • 27. Advance Java struts.xml: <struts> <package name="/" extends="struts-default"> <action name="Validate" class="check.Validate"> <result name="yes">/page1.html</result> <result name="no">/page2.html</result> </action> </package> </struts> index.jsp: <%@taglib prefix="s" uri="/struts-tags" %> <html> <body> <s:form method="get" action="check/Validate.action"> Enter your Email ID: <s:textfield name="email"/> <s:submit value="click me!"/> </s:form> </body> </html> page1.html: <html> <body> <p> Emial ID is correct </p> </body> </html> page2.html: <html> <body> <p> Emial ID is not correct </p> </body> </html> 27 | P a g e
  • 28. Advance Java 28 | P a g e
  • 29. Advance Java PRACTICAL 13: Develop a simple “Hello World” Web Service in Java. HelloUser.java: package myPack; import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.ejb.Stateless; @WebService( ) @Stateless() public class HelloUser { @WebMethod( ) public String sayHello(@WebParam( ) String name) { return "Hello, "+name+" ..!! Welcome to web services :) "; } } myServlet.java: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import javax.xml.ws.*; import pack.*; public class myServlet extends HttpServlet { @WebServiceRef(wsdlLocation = "WEB- INF/wsdl/localhost_8080/HelloUser/HelloUser.wsdl") private HelloUser_Service service; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String nm = request.getParameter("t1"); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); 29 | P a g e
  • 30. Advance Java String ans=sayHello(nm); pw.println("<h2>"+ans+"</h2>"); pw.close(); } private String sayHello(java.lang.String user) { pack.HelloUser port = service.getHelloUserPort(); return port.sayHello(user); } } index.html: <html> <body> <form action="myServlet" method="get"> Name: <input type="text" name="t1"/> <input type="submit" value="click me"/> </form> </body> </html> 30 | P a g e
  • 31. Advance Java PRACTICAL 14: Develop an application to show searching the Directory using JNDI capabilities Dir.java: import javax.naming.*; import java.util.*; class Dir { pulbic static void main(String a[]) { String addr="file:ad_java"; Hashtable args = new Hashtable(); args.put(Context.INITIAL_CONTEXT_FACTORY,"test.sun.jndi.fscontext.FSConte xtFactory"); args.put(Context.PROVIDER_URL,addr); try { Context c = new InitialContext(args); NamingEnumeration ne = c.listBindings(""); while(ne.hasMore()) { Binding b = (Binding) ne.next(); System.out.println("File: "+b.getName()); } c.close(); } catch(Exception e) { System.out.println("Error: "+e);} } } 31 | P a g e
  • 32. Advance Java PRACTICAL 15: Develop a program to show file access using JNDI capabilities. import javax.naming.*; import java.util.*; class FileAccess { pulbic static void main(String a[]) { String file_nm="abc.txt"; Hashtable args = new Hashtable(); args.put(Context.INITIAL_CONTEXT_FACTORY,"test.sun.jndi.fscontext.FSConte xtFactory"); try { Context ctx=new InitialContext(); Object obj = ctx.lookup(name); System.out.println("The file is located at: "+obj); ctx.close(); } catch(Exception e) { System.out.println("Error: "+e);} } } 32 | P a g e