Ad java prac sol set

27,073 views

Published on

Solution Set for the practical list of Advance Java, T.Y.B.Sc.I.T. Semester 5 (Mumbai University)

Published in: Education
10 Comments
65 Likes
Statistics
Notes
No Downloads
Views
Total views
27,073
On SlideShare
0
From Embeds
0
Number of Embeds
56
Actions
Shares
0
Downloads
0
Comments
10
Likes
65
Embeds 0
No embeds

No notes for slide

Ad java prac sol set

  1. 1. Advance Java (Sem 5 – T.Y.B.Sc.I.T.)Iram RamrajkarPRACTICAL 01:Write a java program to present a set of choices for a user to selectStationary products and display the price of Product after Selection from thelist.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 itemsString[] 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 events1|Page
  2. 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. 3. Advance JavaPRACTICAL 02:Write a java program to demonstrate typical Editable Table, describingemployee 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 components3|Page
  4. 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. 5. Advance JavaPRACTICAL 03:Write a java program using Split pane to demonstrate a screen divided in twoparts, one part contains the names of Planets and another Displays the imageof planet. When user selects the planet name form Left screen, appropriateimage 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. 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. 7. Advance JavaPRACTICAL 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. 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. 9. Advance JavaPRACTICAL 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. 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. 11. Advance JavaPRACTICAL 06:Develop a JSP Application to accept Registration Details form user and Storeit 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 userString 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. 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. 13. Advance JavaPRACTICAL 07:Develop a JSP Application to Authenticate User Login as per the registrationdetails. If login success the forward user to Index Page otherwise show loginfailure 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 userString 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. 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. 15. Advance JavaPRACTICAL 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@SessionScopedpublic class Inventory{ String item; int price, qty; public String getItem() { return item; }15 | P a g e
  16. 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. 17. Advance Javafaces-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. 18. Advance JavaPRACTICAL 09:Develop a Room Reservation System Application Using Enterprise Java Beans.ReservationBean.java:package ejb;import javax.ejb.Stateless;import java.sql.*;@Statelesspublic 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 reservationwhere 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. 19. Advance JavamyServlet.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. 20. Advance JavaPRACTICAL 10:Develop a Hibernate application to store Feedback of Website Visitor inMySQL 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. 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> <propertyname="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <propertyname="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <propertyname="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();try21 | P a g e
  22. 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. 23. Advance JavaPRACTICAL 11:Develop a simple Struts Application to Demonstrate 3 page Website ofTeaching Classes which passes values from every page to anotherFirst.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. 24. Advance JavaSecond.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. 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. 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. 27. Advance Javastruts.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. 28. Advance Java28 | P a g e
  29. 29. Advance JavaPRACTICAL 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. 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. 31. Advance JavaPRACTICAL 14:Develop an application to show searching the Directory using JNDI capabilitiesDir.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.FSContextFactory"); 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. 32. Advance JavaPRACTICAL 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.FSContextFactory"); 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

×