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

Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Nishan Barot
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Hibernate
Hibernate Hibernate
Hibernate Sunil OS
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivitybackdoor
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySqlDhyey Dattani
 
Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
Developing Java Web Applications
Developing Java Web ApplicationsDeveloping Java Web Applications
Developing Java Web Applicationshchen1
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#Doncho Minkov
 
Introducing Async/Await
Introducing Async/AwaitIntroducing Async/Await
Introducing Async/AwaitValeri Karpov
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisIan Macali
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeletonIram Ramrajkar
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeRamon Ribeiro Rabello
 
JavaScript
JavaScriptJavaScript
JavaScriptSunil OS
 

Tendances (20)

JUnit 4
JUnit 4JUnit 4
JUnit 4
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Hibernate
Hibernate Hibernate
Hibernate
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Android UI
Android UIAndroid UI
Android UI
 
Developing Java Web Applications
Developing Java Web ApplicationsDeveloping Java Web Applications
Developing Java Web Applications
 
C sharp
C sharpC sharp
C sharp
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
Introducing Async/Await
Introducing Async/AwaitIntroducing Async/Await
Introducing Async/Await
 
.Net Assemblies
.Net Assemblies.Net Assemblies
.Net Assemblies
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
 
Spring AOP in Nutshell
Spring AOP in Nutshell Spring AOP in Nutshell
Spring AOP in Nutshell
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack Compose
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 

En vedette

Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
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 scienceNiraj Bharambe
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - PraticalsFahad Shaikh
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL fileRACHIT_GUPTA
 
Java Code for Sample Projects Inheritance
Java Code for Sample Projects InheritanceJava Code for Sample Projects Inheritance
Java Code for Sample Projects Inheritancejwjablonski
 
Linux practicals T.Y.B.ScIT
Linux practicals T.Y.B.ScITLinux practicals T.Y.B.ScIT
Linux practicals T.Y.B.ScITvignesh0009
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for vivaVipul Naik
 
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_downloadableAjit Vishwakarma
 
Practical java
Practical javaPractical java
Practical javanirmit
 
9781285852744 ppt ch16
9781285852744 ppt ch169781285852744 ppt ch16
9781285852744 ppt ch16Terry Yoast
 
9781111530532 ppt ch14
9781111530532 ppt ch149781111530532 ppt ch14
9781111530532 ppt ch14Terry Yoast
 
Data Structures- Part2 analysis tools
Data Structures- Part2 analysis toolsData Structures- Part2 analysis tools
Data Structures- Part2 analysis toolsAbdullah Al-hazmy
 
Data Structures- Part9 trees simplified
Data Structures- Part9 trees simplifiedData Structures- Part9 trees simplified
Data Structures- Part9 trees simplifiedAbdullah Al-hazmy
 
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
 
Data Structures- Part8 stacks and queues
Data Structures- Part8 stacks and queuesData Structures- Part8 stacks and queues
Data Structures- Part8 stacks and queuesAbdullah Al-hazmy
 

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
 
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...
 
Data Structures- Part8 stacks and queues
Data Structures- Part8 stacks and queuesData Structures- Part8 stacks and queues
Data Structures- Part8 stacks and queues
 

Similaire à Java program to select stationary product and display price

比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
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 TestsTomek 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 AppSyed Shahul
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingVisual Engineering
 
Exercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera CymbronExercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera Cymbroncymbron
 
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.pdfmeerobertsonheyde608
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginnersDivakar Gu
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stackTomáš Kypta
 
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 6Dmitry Soshnikov
 
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 Tutorialjbarciauskas
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
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 Datosphilogb
 
Enterprise workflow with Apps Script
Enterprise workflow with Apps ScriptEnterprise workflow with Apps Script
Enterprise workflow with Apps Scriptccherubino
 
Mobile Day - React Native
Mobile Day - React NativeMobile Day - React Native
Mobile Day - React NativeSoftware Guru
 

Similaire à Java program to select stationary product and display price (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

GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 

Dernier (20)

GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 

Java program to select stationary product and display price

  • 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