Java Lab Record
Java Lab Record
Java Lab Record
Program 1(a) Write a Java Program to demonstrate Constructor Overloading and Method overloading Program import java.io.*; import java.lang.*; class A { int a; A() { a=0; } A(int x) { a=x; } void show(int x) { a=x; System.out.println("a="+a); } void show() { System.out.println("a="+a); } } class J1_1 { public static void main(String args[]) { A a1=new A(); A a2=new A(2); a1.show(5); a2.show(); } } Output:To compile the file use the command as follows javac J1_1.java To run this program use command java J1_1 a=5 a=2
IV Semester
1MJ07MCA05
Program 1(b) Write a Java Program to implement inner class and demonstrate its Access Protections Program import java.io.*; import java.lang.*; class outer { int a=10; class inner { int b=20; void display() { System.out.println("a = " +a + "b=" +b); //here a is accessible } } void test() { inner in1=new inner(); in1.display(); System.out.println("a = " +a); //System.out.println("b = " +b); it will give an error because b is unknown here } } class J1_2 { public static void main(String args[]) { outer out1=new outer(); out1.test(); } } Output a = 10b=20 a = 10
IV Semester
1MJ07MCA05
Program 2(a)Write a Java Program to implement Inheritance. Program class abcd { int a; void get_a(int x) { a=x; } void show_a() { System.out.println("a=" +a); } } class xyz extends abcd { int x; void show_x() { x=a; System.out.println("x=" +x); } } class J2_1 { public static void main(String args[]) { xyz x1=new xyz(); x1.get_a(2); x1.show_a(); x1.show_x(); } } Output a=2 x=2
IV Semester
1MJ07MCA05
Program 2(b) Write a Java Program to implement Exception Handling (Using Nested try catch and finally) Program import java.io.*; class J2_2 { public static void main(String args[]) throws Exception { int a=5,b,c; DataInputStream in=new DataInputStream(System.in); System.out.println("Enter a integer ->"); b=Integer.parseInt(in.readLine()); try { c=a/(a-b); System.out.println("c=" +c); try { int d[]={1,2}; d[2]=5; } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index error Exception"); } } catch(ArithmeticException e) { System.out.println("Division by zero Exception"); } finally // block of code to be executed before try block ends { System.out.println("Default Exception"); } } } Output Enter a integer -> 5 Division by zero Exception Default Exception
IV Semester
1MJ07MCA05 Program 3(a)Write a Java Program to create an interface and implement it in a class
Program import java.io.*; interface intf1 { final int x=2; /*int x=2 - both can be written but the variable should not be altered later*/ void show(); } class abc implements intf1 { public void show() /*here public access specifier is essential otherwise it will show an error that show() in abc can't implement show() in intf1:attempting to assign weaker access privileges;was public */ { System.out.println("x=" +x); } } class J3_1 { public static void main(String args[]) { /*intf1 i1=new intf1();it will give an error that- intf1 is abstrct so can't be instantiated. Using reference object we can do it*/ intf1 i1; //creating reference object i1=new abc(); i1.show(); abc a1=new abc(); //in this way you can also access show() a1.show(); } } Output x=2 x=2
IV Semester
1MJ07MCA05
Program 3(b) Write a Java Program to create a class (extending Thread) and use methods thread class to change name, priority of the current thread and display the same. Program import java.io.*; import java.lang.*; class Mythread extends Thread { Mythread(String name) { super(name); } public void run() { int count=0; while (true) { try { sleep(100); } catch (InterruptedException e) {} if (count == 50) break; System.out.println(this+":" + count++); } } } class J3_2 { public static void main(String args[]) { Mythread thrd1=new Mythread("Thread1"); Mythread thrd2=new Mythread("Thread2"); thrd1.setPriority(Thread.MAX_PRIORITY); thrd2.setPriority(Thread.NORM_PRIORITY-1); thrd2.start(); thrd1.start(); } } Dept of MCA, MVJCE 6 IV Semester
1MJ07MCA05 Output Thread[Thread1,10,main]:0 Thread[Thread2,4,main]:0 Thread[Thread1,10,main]:1 Thread[Thread2,4,main]:1 Thread[Thread1,10,main]:2 Thread[Thread2,4,main]:2 Thread[Thread1,10,main]:3 Thread[Thread2,4,main]:3 Thread[Thread1,10,main]:4 Thread[Thread2,4,main]:4 Thread[Thread1,10,main]:5 Thread[Thread2,4,main]:5 Thread[Thread1,10,main]:6 Thread[Thread2,4,main]:6 Thread[Thread1,10,main]:7 Thread[Thread2,4,main]:7 Thread[Thread1,10,main]:8 Thread[Thread2,4,main]:8 Thread[Thread1,10,main]:9 Thread[Thread2,4,main]:9 Thread[Thread1,10,main]:10 Thread[Thread2,4,main]:10 Thread[Thread1,10,main]:11 Thread[Thread2,4,main]:11 Thread[Thread1,10,main]:12 Thread[Thread2,4,main]:12 Thread[Thread1,10,main]:13 Thread[Thread2,4,main]:13 Thread[Thread1,10,main]:14 Thread[Thread2,4,main]:14 Thread[Thread1,10,main]:15 Thread[Thread2,4,main]:15 Thread[Thread1,10,main]:16 Thread[Thread2,4,main]:16 Thread[Thread1,10,main]:17 Thread[Thread2,4,main]:17 . Thread[Thread1,10,main]:49 Thread[Thread2,4,main]:49
IV Semester
1MJ07MCA05 Program 4(a) Write a Java Program to create a Scrolling Text using Java Applets. Program import java.awt.*; import java.applet.*; /* <applet code="J4_1" width=300 height=300> </applet> */
public class J4_1 extends Applet { public void init() { String str="Hi.....\nwelcome to Java Applet \nThis is the use of Scrollling Text"; TextArea txt=new TextArea(str,5,15); add(txt); } } Output Compile this file in as usual manner using javac J4_1.java Then run this file using the command apletviewer J4_1.java Then the following output will appear
IV Semester
1MJ07MCA05 Program 4(b) Write a Java Program to pass parameters to Applets and display the same. Program import java.awt.*; import java.applet.*; /* <applet code="J4_2" width=300 height=300> <param name=font value="Times new roman"> <param name=fontsize value=10> </applet> */ public class J4_2 extends Applet { String font; int font_size; public void init() { try { font=getParameter("font"); font_size=Integer.parseInt(getParameter("fontsize")); } catch(Exception e) { System.out.println("Exception:" +e); } } public void paint(Graphics g) { g.drawString("font name=" +font,0,15); g.drawString("font size=" +font_size,0,30); } }
IV Semester
1MJ07MCA05 Output Compile the file using the command javac J4_2.java Then run the program using the command appletviewer J4_2.java The output will appear like this
10
IV Semester
1MJ07MCA05
Program 5 Write a Java Program to insert data into Student DATA BASE and retrieve info base on particular queries(Using JDBC Design Front end using Swings). Program import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.sql.*; class jconnection { static Connection conn; public void connect () throws SQLException { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn=DriverManager.getConnection("jdbc:odbc:database1","scott","tiger"); } catch(Exception e) { System.out.println("Unsuccessful!" + e); } } } public class J5 extends JFrame implements ActionListener { jconnection jconn; public static void main(String []args) throws Exception { new J5(); } JLabel lblUSN = new JLabel(" USN :"); JLabel lblNAME = new JLabel("NAME:"); JLabel lblDEPT = new JLabel("DEPT:"); JTextField txtUSN=new JTextField(15); JTextField txtNAME=new JTextField(15); JTextField txtDEPT=new JTextField(15); JButton btnAdd = new JButton("Add"); JButton btnSearch = new JButton("Search"); Dept of MCA, MVJCE 11 IV Semester
1MJ07MCA05 JButton btnClear = new JButton("Clear"); public J5() throws SQLException { super("This is JDBC swing program"); jconn = new jconnection(); jconn.connect(); Container cont = getContentPane(); cont.setLayout(new FlowLayout());
JPanel panel1 = new JPanel(); JPanel panel2 = new JPanel(); panel1.setLayout(new GridLayout(3,2)); //three rows and two items per row panel2.setLayout(new GridLayout()); panel1.add(lblUSN); panel1.add(txtUSN); panel1.add(lblNAME); panel1.add(txtNAME); panel1.add(lblDEPT); panel1.add(txtDEPT); cont.add(panel1); panel2.add(btnAdd); panel2.add(btnSearch); panel2.add(btnClear); cont.add(panel2); btnAdd.addActionListener(this); btnSearch.addActionListener(this); btnClear.addActionListener(this); setSize(500,150); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==btnAdd) { try { String txt1= txtUSN.getText(); String txt2= txtNAME.getText(); String txt3= txtDEPT.getText(); Statement stmt = jconn.conn.createStatement(); String updateString = "insert into student values('"+txt1+"','"+txt2+"','"+txt3+"')"; Dept of MCA, MVJCE 12 IV Semester
1MJ07MCA05 stmt.executeUpdate(updateString); txtUSN.setText(""); txtNAME.setText(""); txtDEPT.setText(""); stmt.close(); } catch(SQLException e) { System.out.println("Error:" +e); System.exit(0); } }
else if(ae.getSource()==btnSearch) { try { Statement stmt=jconn.conn.createStatement(); ResultSet rs=stmt.executeQuery("select * from student where usn = '"+txtUSN.getText()+"' "); while(rs.next()) { txtUSN.setText(rs.getString(1)); txtNAME.setText(rs.getString(2)); txtDEPT.setText(rs.getString(3)); } rs.close(); } catch(Exception e) { System.out.println("Error:" +e); System.exit(0); } } else if(ae.getSource()==btnClear) { txtUSN.setText(""); txtNAME.setText(""); txtDEPT.setText(""); } } }
13
IV Semester
1MJ07MCA05
Output Procedure First create a database named student using any of the database. Here I am using Oracle as the database To create the database, follow these steps Open SQL plus which will be installed in your machine. Then give user name as scott and password as tiger to open the sql prompt. When the sql prompt will appear create a table named student using the following command create table student(usn varchar2(10),name char(15),dept char(15)); Then exit the SQL. Now compile and run the source file using the commands javac J5.java java J5 When you will run the program it will show an exception with the following window in this manner
Unsuccessful!java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified This Exception came because we didnt crate any ODBC connection. Now close the above window and create the ODBC connection. To create ODBC connection go to control panel, Open Administrative Tools and then open Data Sources(ODBC). Now click on add to create a connection. When you will click on add, a new window will appear named as Create New DataSource. In this window select Microsoft ODBC for oracle and then click on Finish. When you click on finish, again a new window will appear named as Microsoft Odbc for Oracle setup. Here you give the datasource name in the field. Ex- chinu. Click on ok to finish database connection. Now, again you run the program. Now you can see that no Exception occurred. You give the necessary data in the window and click on Add to store into the database as below
14
IV Semester
1MJ07MCA05
After you add the entry to the database you can also see it using the USN. For that only fill the USN field and click on Search. This is shown below
15
IV Semester
1MJ07MCA05
Program 6 Write a Java Program to implement Client Server (Client requests a file, Server responds to client with contents of that file which is then display on the screen by client-Socket Programming) Program Client.java import java.net.*; import java.util.*; import java.io.*; public class Client { public static void main(String args[]) { Socket client=null; BufferedReader br=null; try { System.out.println(args[0]+" "+ args[1]); client=new Socket(args[0],Integer.parseInt(args[1])); } catch(Exception e){} BufferedReader input=null; PrintStream output=null; try { input=new BufferedReader(new InputStreamReader(client.getInputStream())); output=new PrintStream(client.getOutputStream()); br=new BufferedReader(new InputStreamReader(System.in)); String str=input.readLine(); //get the prompt from the server System.out.println(str);//display the prompt on the client machine String filename=br.readLine(); if(filename!=null) output.println(filename); String data; while((data=input.readLine())!=null) System.out.println(data); Dept of MCA, MVJCE 16 IV Semester
1MJ07MCA05 client.close(); } catch(Exception e) { System.out.println(e); } } } Server.java import java.net.*; import java.util.*; import java.io.*; public class Server { public static void main(String args[]) { ServerSocket server=null; try { server=new ServerSocket(Integer.parseInt(args[0])); } catch(Exception e){}
while(true) { Socket client=null; PrintStream output=null; BufferedReader input=null; try { client=server.accept(); output=new PrintStream(client.getOutputStream()); input=new BufferedReader(new InputStreamReader(client.getInputStream())) ; } catch(Exception e) { System.out.println(e); } output.println("Enter The File Name ->"); try { String filename=input.readLine(); System.out.println("Client requested file:" + filename); try { File f=new File(filename); Dept of MCA, MVJCE 17 IV Semester
1MJ07MCA05 BufferedReader br=new BufferedReader(new FileReader(f)); String data; while((data=br.readLine())!=null) { output.println(data); } } catch(FileNotFoundException e) { output.println("FILE NOT FOUND"); } client.close(); } catch(Exception e) { System.out.println(e); } }//End of While } //End of main } //End of class Output
Procedure Open two dos prompt for the program execution. One prompt is for the client and another is for the Server. In the client prompt compile the Client.java using the command javac Client.java Similarly in the server prompt compile the Server.java using the command javac Server.java Now on the Server prompt, run the Server.java using the command java Server 8080 Leave the server prompt as it is and now come back to the client prompt and execute Client.java using the command java Client localhost 8080 After you hit enter it will show the output as follows and will ask for a filename localhost 8080 Enter The File Name -> Dept of MCA, MVJCE 18 IV Semester
Here I have given the file name as 1.txt. And after that it will show the content of 1.txt as above. Note that the file 1.txt should present in the same directory as the source file.
Program 7 Write a Java Program to implement a simple Client server Application using RMI Program AddServerIntf.java import java.rmi.*; public interface AddServerIntf extends Remote { double add(double d1, double d2) throws RemoteException; } AddServerImpl.java import java.rmi.*; import java.rmi.server.*; public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf { public AddServerImpl() throws RemoteException { } public double add(double d1, double d2) throws RemoteException { return d1 + d2; } } AddServer.java import java.net.*; import java.rmi.*; public class AddServer { public static void main(String args[]) { try { AddServerImpl addServerImpl = new AddServerImpl(); Naming.rebind("AddServer", addServerImpl); } catch(Exception e) { System.out.println("Exception: " + e); Dept of MCA, MVJCE 19 IV Semester
1MJ07MCA05 } } }
AddClient.java import java.rmi.*; public class AddClient { public static void main(String args[]) { try { String addServerURL = "rmi://" + args[0] + "/AddServer"; AddServerIntf addServerIntf = (AddServerIntf)Naming.lookup(addServerURL); System.out.println("The first number is: " + args[1]); double d1 = Double.valueOf(args[1]).doubleValue(); System.out.println("The second number is: " + args[2]); double d2 = Double.valueOf(args[2]).doubleValue(); System.out.println("The sum is: " + addServerIntf.add(d1, d2)); } catch(Exception e) { System.out.println("Exception: " + e); } } } Output Procedure Explanation The first file, AddServerIntf.java, defines the remote interface that is provided by the server. The second source file, AddServerImpl.java, implements the remote interface.The third source file, AddServer.java, contains the main program for the server machine. Its primary function is to update the RMI registry on that machine.The fourth source file, AddClient.java, implements the client side of this distributed application. First compile all the 4 source files mentioned above. Then open two prompts one is for client and another is for server. Now on the server prompt execute following command rmic AddServerImpl (rmic rmi Compiler) This will generate the two files named as AddServerImpl_Skel.class (skeleton), Dept of MCA, MVJCE 20 IV Semester
1MJ07MCA05
AddServerImpl_Stub.class (stub). In the context of RMI, a stub is a Java object that resides on the client machine. A skeleton is a Java object that resides on the server machine. Now execute following command on the server prompt which will start the RMI Registry on the Server Machine. start rmiregistry Now on the server prompt execute this command also java AddServer
Now on the Client prompt execute the commad ipconfig to get the ip address of the client in the following manner Connection-specific DNS Suffix . : IP Address. . . . . . . . . . . . : 192.168.1.2 This is the IP address of the client Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . : 192.168.1.1 And then execute following command by using the above IP to get the output as follows AddClient 192.168.1.2 10 15 The first number is: 10 The second number is: 15 The sum is: 25.0
21
IV Semester
1MJ07MCA05
Program 8 Write a Java Program to implement a dynamic HTML using servlet(user name and password should be accepted using HTML and displayed) Program J8.html <html> <head> <title>Servlet Test Program</title> </head> <body> <form name="detailsForm" method="post" action="http://localhost:8080/servlets-examples/index"> User Id:<input type="text" name="username" value=""> <br> Password:<input type="password" name="password" value=""> <br> <input type="submit" name="btn_submit" value="submit"></td> </form> </body> </html> J8.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class J8 extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("username"); String passwd = request.getParameter("password"); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); Dept of MCA, MVJCE 22 IV Semester
Output Procedure Step 1: Compile the file using the following command D:\>javac J8.java -classpath "C:\Program Files\Apache Software Foundation\Tomcat 5.5\lib\servlet-api.jar" Step 2: Now copy the above compiled file to the path below D:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ servlets-examples\WEB-INF\classes Step 3: Edit the web.xml file that is situated in D:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ servlets-examples\WEB-INF\web.xml (If web.xml is not present on the above path, then copy it form the directory D:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ ROOT\WEB-INF) And set class name i.e J8 in the following tags <servlet> <servlet-name>org.apache.jsp.index_jsp</servlet-name> <servlet-class>J8</servlet-class> </servlet> <servlet-mapping> <servlet-name>org.apache.jsp.index_jsp</servlet-name> <url-pattern>/index</url-pattern> </servlet-mapping> Step 4: Dept of MCA, MVJCE 23 IV Semester
1MJ07MCA05
In the above window give necessary input and click on submit. Then following output will appear
24
IV Semester
1MJ07MCA05
Program 9 Write a java Servlet Program to Download a file and display it on the screen(A link has to be provided in HTML, when the Link is clicked corresponding file has to be displayed on screen). Program import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class J9 extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { PrintWriter out = res.getWriter(); out.println("<html><body>"); out.println("<a href=1.txt> Click Here to Download </a>"); out.println("</body></html> "); } } Dept of MCA, MVJCE 25 IV Semester
1MJ07MCA05 Output
Procedure Step 1: Compile the file using the following command D:\>javac J9.java -classpath "C:\Program Files\Apache Software Foundation\Tomcat 5.5\lib\servlet-api.jar" Step 2: Now copy the above compiled file(J9.class) to the path belowD:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ servlets-examples\WEB-INF\classes Create a file (Ex- 1.txt) that, you want to download through browser with any content in the directory D:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ servlets-examples Step 3: Edit the web.xml file that is situated in D:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ servlets-examples\WEB-INF\web.xml
(If web.xml is not present on the above path, then copy it form the directory D:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ ROOT\WEB-INF) And set class name i.e J9 in the following tags <servlet> <servlet-name>org.apache.jsp.index_jsp</servlet-name> <servlet-class>J9</servlet-class> </servlet> <servlet-mapping> <servlet-name>org.apache.jsp.index_jsp</servlet-name> <url-pattern>/index</url-pattern> </servlet-mapping> Step 4: Now open the web browser and open the following url http://localhost:8080/servlets-examples/index when you will open this the following window will appear
26
IV Semester
1MJ07MCA05
When you click on the link Click Here to Download. It will show the content of the file 1.txt that you have created already. The output is as follows
Program 10(a) Write a JAVA Servlet Program to implement RequestDispatcher object (use include () and forward () method). Program J10_1.java import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class J10_1 extends HttpServlet { protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,java.io.IOException { response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("This text is displayed at Level 1.<br>"); out.println("<h1>Hello from present doGet method</h1>"); Dept of MCA, MVJCE 27 IV Semester
1MJ07MCA05
RequestDispatcher dispatcher = request.getRequestDispatcher("/J10_1_1"); dispatcher.include(request, response); out.println("Back to Level 1.<br>"); out.println("</body>"); out.println("</html>"); out.close(); } } J10_1_1.java import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class J10_1_1 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,java.io.IOException { java.io.PrintWriter out = response.getWriter(); out.println("This text is displayed from J10_1_1 prgram.<br>"); out.println("<h1>Hello from another doGet</h1>"); } }
Output Procedure Step 1: Compile the above two file using the following command D:\>javac J10_1.java J10_1_1.java -classpath "C:\Program Files\Apache Software Foundation\Tomcat 5.5\lib\servlet-api.jar" Step 2: Now copy the above compiled file(J10_1.class & J10_1_1.class ) to the path belowD:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ servlets-examples\WEB-INF\classes Step 3: Edit the web.xml file that is situated in D:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ servlets-examples\WEB-INF\web.xml (If web.xml is not present on the above path, then copy it form the directory Dept of MCA, MVJCE 28 IV Semester
1MJ07MCA05
D:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ ROOT\WEB-INF) And set class name i.e J10_1 & J10_1_1 in the following tags, 2 times <servlet> <servlet-name>J10_1</servlet-name> <servlet-class>J10_1</servlet-class> </servlet> <servlet-mapping> <servlet-name>J10_1</servlet-name> <url-pattern>/J10_1</url-pattern> </servlet-mapping> <servlet> <servlet-name>J10_1_1</servlet-name> <servlet-class>J10_1_1</servlet-class> </servlet> <servlet-mapping> <servlet-name>J10_1_1</servlet-name> <url-pattern>/J10_1_1</url-pattern> </servlet-mapping>
Step 4: Now open the web browser and open the following url http://localhost:8080/servlets-examples/J10_1 When you will open this, the following window will appear
29
IV Semester
1MJ07MCA05
Program 10(b) Write a Java Servlet Program to implement and demonstrate get() and Post methods(Using HTTP Servlet Class Program J10_2.html <html> Dept of MCA, MVJCE 30 IV Semester
<form name="Form1" action="http://localhost:8080/servlets-examples/index"> <h3>For Get Method</h3> <b>Color:</b> <select name="Color" size="1"> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> </select> <br><br> <input type="submit" value="submit" name="submit"> </form> <form name="Form2" method="post" action="http://localhost:8080/servlets-examples/index"> <h3>For Post Method</h3> <B>Color:</B> <select name="Color" size="1"> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> </select> <br><br> <input type="submit" value="submit"> </form> </body> </html> J10_2.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class J10_2 extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { String color=req.getParameter("Color"); res.setContentType("Text/html"); PrintWriter pw=res.getWriter(); pw.println("<b>The color:"); pw.println(color); pw.close(); } Dept of MCA, MVJCE 31 IV Semester
1MJ07MCA05
public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { String color=req.getParameter("Color"); res.setContentType("Text/html"); PrintWriter pw=res.getWriter(); pw.println("<b>The color:"); pw.println(color); pw.close(); } } Output Procedure Step 1: Compile the file using the following command D:\>javac J10_2.java -classpath "C:\Program Files\Apache Software Foundation\Tomcat 5.5\lib\servlet-api.jar" Step 2: Now copy the above compiled file to the path below D:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ servlets-examples\WEB-INF\classes Step 3: Edit the web.xml file that is situated in D:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ servlets-examples\WEB-INF\web.xml (If web.xml is not present on the above path, then copy it form the directory D:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ ROOT\WEB-INF)
And set class name i.e J10_2 in the following tags <servlet> <servlet-name>org.apache.jsp.index_jsp</servlet-name> <servlet-class>J10_2</servlet-class> Dept of MCA, MVJCE 32 IV Semester
1MJ07MCA05 </servlet>
<servlet-mapping> <servlet-name>org.apache.jsp.index_jsp</servlet-name> <url-pattern>/index</url-pattern> </servlet-mapping> Step 4: Now open the J10_2.html. The output will be as follows
Select any option from drop down list and click on submit Here I have chosen green in the Get method. The output will be as follows
Program 12 Write a Java Servlet Program to implement sessions (Using HTTP Session Interface) Program J12.java Dept of MCA, MVJCE 33 IV Semester
1MJ07MCA05
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class J12 extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException { HttpSession hs=request.getSession(); response.setContentType("text/html"); PrintWriter pw=response.getWriter(); pw.println("<B>"); Date date=(Date)hs.getAttribute("date"); if(date!=null) { pw.println("Last access : " +date+ "<br>"); } date=new Date(); hs.setAttribute("Date",date); pw.println("Current date : "+date); } } Output Procedure Step 1: Compile the file using the following command D:\>javac J12.java -classpath "C:\Program Files\Apache Software Foundation\Tomcat 5.5\lib\servlet-api.jar" Step 2: Now copy the above compiled file(J12.class) to the path belowD:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ servlets-examples\WEB-INF\classes Step 3: Edit the web.xml file that is situated in D:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ servlets-examples\WEB-INF\web.xml
(If web.xml is not present on the above path, then copy it form the directory D:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ ROOT\WEB-INF) Dept of MCA, MVJCE 34 IV Semester
1MJ07MCA05 And set class name i.e J12 in the following tags
<servlet> <servlet-name>org.apache.jsp.index_jsp</servlet-name> <servlet-class>J12</servlet-class> </servlet> <servlet-mapping> <servlet-name>org.apache.jsp.index_jsp</servlet-name> <url-pattern>/index</url-pattern> </servlet-mapping> Step 4: Now open the web browser and open the following url http://localhost:8080/servlets-examples/index when you will open this the following window will appear
35
IV Semester
1MJ07MCA05 Program 13(a) Write a Java JSP Program to print 10 even and 10 odd number Program J13_1.jsp <html> <head> <title> Printing 10 even and odd numbers </title> </head> <body> <%!int x=0,y=1; %> <p> Ten Even numbers are -> </p> <% for(int i=0;i<10;i++,x=x+2) {%> <%=x %> <%}%> <p> Ten Odd numbers are -> </p> <% for(int i=0;i<10;i++,y=y+2) { %> <%=y %> <%}%> </body> </html>
Output Procedure Copy J13_1.jsp into the directory D:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ servlets-examples\ Then open Web browser and type the following URL http://localhost:8080/servlets-examples/J13_1.jsp Now the output will be like this
36
IV Semester
1MJ07MCA05
Program 13(b) Write a Java JSP Program to implement verification of a particular user login and display a welcome page. Program J13_2.jsp <html> <head> <title> Simple validation program </title> <style type="text/css"> #a {MARGIN: 100px; WIDTH: 300px; BORDER: lime 2px solid; BACKGROUND: #f3f3f3} </style> <body> <center> <div id=a> <form name="form1" method="post" action="J13_2_1.jsp" ><BR> <b>UserName :</b> <input name="name"> <br> <b>Password :</b> <input type="password" name="passwd"> <br> <pre> <input type="submit" value="Submit"> </pre> </form> </div> </center> </body> </html> J13_2_1.jsp <%@page contentType="text/html" %> <html> <body> <%if(request.getParameter("name").equals("manjunath")){%> <%if(request.getParameter("passwd").equals("bangalore")) { %> <p> Success </p> <%} %> <%}else { %> <p> Username and password is not valid </p> <% } %> </body> </html>
37
IV Semester
1MJ07MCA05 Output
Procedure Copy the above two files into the directory D:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ servlets-examples\ Then open Web browser and type the following URL http://localhost:8080/servlets-examples/J13_2.jsp Now the output will be like this
Give Necessary input and then click on submit then the following output will appear
38
IV Semester
1MJ07MCA05
Program 14 Write a Java JASP program to get student information through a HTML and create a JAVA beans Class, Populate bean and display the same information through another JSP. Program Employee.java package beans; public class Employee { public String ename; public int eno; public void setename(String e) {ename = e;} public String getename() {return ename;} public void seteno(int en) {eno=en;} public int geteno() {return eno;} } first.jsp <html> <body> <jsp:useBean id="emp" scope="request" class="beans.Employee"/> <jsp:setProperty name="emp" property="*"/> <jsp:forward page="display.jsp"/> </body> </html> display.jsp <html> <body> <jsp:useBean id="emp" scope="request" class="beans.Employee"/> USN: <jsp:getProperty name="emp" property="eno"/><br> Name: <jsp:getProperty name="emp" property="ename"/><br> </body> </html>
39
IV Semester
1MJ07MCA05
StudInfo.html <html> <head><title> Student information </title></head> <body> <form action ="first.jsp" method = "post"> Usn : <input type = "text" name = "eno"/><br> Name : <input type = "text" name ="ename"/><br> <input type ="submit" value ="show"/> </form> </body> </html> Output Procedure First write above 4 files with correct extension Then compile this file using the command below javac Employee.java Then create a folder named beans and put the compiled file Employee.class into that. Now copy the beans folder into the directory as follows D:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\servlets-examples\WEBINF\classes Then copy the remaining 3 files first.jsp, display.jsp, StudInfo.html into the directory as given below D:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\servlets-examples Now open Web browser and type the following URL to get the output as below http://localhost:8080/servlets-examples/StudInfo.html
40
IV Semester
1MJ07MCA05
Here fill out both the fields and click on submit to get the output as below
41
IV Semester