CONTENTS S.No. Programs Pg. No. 1. RMI – Addition 1 2. RMI – Calculator 5 3. JDBC – Creating Table 9 4. JDBC – Viewing a Table using SELECT Statement 11 5. JDBC – Inserting values in Table 13 6. JDBC – Updating a Table 15 7. JDBC – Using Prepared Statements 17 8. JDBC – Scrollable RESULTSET Statement 19 9. JDBC – Deleting values in Table 21 10. JDBC – Using Callable Statements 23 11. SERVLETS – Hidden Form Fields 25 12. SERVLETS – URL Rewriting 29 13. SERVLETS - Cookies 33 14. SERVLETS - HttpSession 37 15. SERVLETS – User Authorization 41 16. JSP – Forward Action Tag 46 17. JSP – Include Action Tag 48 18. JSP – useBean Action Tag 50 Sign 19. JSP – getProperty and setProperty Action Tag 52 20. EJB – Stateless Session Bean 54 21. EJB – Statefull Session Bean 57 22. EJB – Message Driven Bean 60 23. EJB – Entity Session Bean 65 24. STRUTS – HelloWorld 68 25. ANDROID – Database Connectivity 71 Advanced JAVA LAB 1. RMI PROGRAM -Addition P1. AddServerIntf.java import java.rmi.*; public interface AddServerIntf extends Remote { double add(double d1, double d2) throws RemoteException; } P2. 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; } } P3. AddServer.java import java.net.*; import java.rmi.*; import java.lang.Throwable; 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); } } } 4. 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(); 1|Page Advanced JAVA LAB 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); } } } 2|Page Advanced JAVA LAB Output: Start RMI Registry: Start Server: 3|Page Advanced JAVA LAB Client Side Class (At another JVM) 4|Page Advanced JAVA LAB 2. RMI PROGRAM –Calculator P1. AddServerIntf.java import java.rmi.*; public interface AddServerIntf extends Remote { double add(double d1, double d2) throws RemoteException; double sub(double d1, double d2) throws RemoteException; double mul(double d1, double d2) throws RemoteException; double div(double d1, double d2) throws RemoteException; } P2. 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; } public double sub(double d1, double d2) throws RemoteException { return d1 - d2; } public double mul(double d1, double d2) throws RemoteException { return d1 * d2; } public double div(double d1, double d2) throws RemoteException { return d1 / d2; } } P3. AddServer.java import java.net.*; import java.rmi.*; import java.lang.Throwable; 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); } } } 5|Page Advanced JAVA LAB 4. 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)); System.out.println("The diff is: " + addServerIntf.sub(d1, d2)); System.out.println("The product is: " + addServerIntf.mul(d1, d2)); System.out.println("The quotient is: " + addServerIntf.div(d1, d2)); } catch(Exception e) { System.out.println("Exception: " + e); } } } 6|Page Advanced JAVA LAB OUTPUT Start RMI REGISTRY RMI REGISTRY 7|Page Advanced JAVA LAB CLIENT 8|Page Advanced JAVA LAB JDBC Program 1. Creating a table in database. import java.sql.*; import java.io.*; public class Marktest{ public Marktest() { } public void mks() { Connection con = null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:moviecatalog","", ""); Statement stmt = con.createStatement(); String sql = "CREATE TABLE MARKS" + "(id INTEGER not NULL, " + " java INTEGER ," + " distsys INTEGER, " + " compiler INTEGER, " + " ada INTEGER, " + " maths INTEGER, " + " PRIMARY KEY ( id ))"; stmt.executeUpdate(sql); } catch(SQLException se) { se.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } finally { // try{ // if(stmt!=null) // con.close(); // } // catch(SQLException se){ // } try{ if(con!=null) con.close(); } catch(SQLException se){ se.printStackTrace(); } } System.out.println("End"); } public static void main(String[] args) { Marktest mtest = new Marktest(); mtest.mks(); } } 9|Page Advanced JAVA LAB OUTPUT Compile: Database: 10 | P a g e Advanced JAVA LAB Program 2. View a table in database using SELECT Statement. import java.sql.*; import java.io.*; public class SelectDataApp { public SelectDataApp() { } public void selectData() { Connection con = null; try { // Load the Driver class file Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Make a connection to the ODBC datasource Movie Catalog con = DriverManager.getConnection("jdbc:odbc:moviecatalog", "", ""); // Create the statement Statement statement = con.createStatement(); // Use the created statement to SELECT the DATA // FROM the Titles Table. ResultSet rs = statement.executeQuery("SELECT * " + "FROM Titles"); // Iterate over the ResultSet while ( rs.next() ) { // get the title_name, which is a String System.err.println("Title Name = " + rs.getString("title_name")); // get the rating System.err.println("Title Rating = " + rs.getString("rating")); // get the price System.err.println("Title Price = " + rs.getString("price")); // get the quantity System.err.println("Title Quantity = " + rs.getString("quantity") + "\n"); } // Close the ResultSet rs.close(); System.in.read(); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } catch (SQLException sqle) { System.err.println(sqle.getMessage()); } catch (ClassNotFoundException cnfe) { System.err.println(cnfe.getMessage()); } catch (Exception e) { System.err.println(e.getMessage()); } finally { try { if ( con != null ) { 11 | P a g e Advanced JAVA LAB // Close the connection no matter what con.close(); } } catch (SQLException sqle) { System.err.println(sqle.getMessage()); } } } public static void main(String[] args) { SelectDataApp selectDataApp = new SelectDataApp(); selectDataApp.selectData(); }} OUTPUT 12 | P a g e Advanced JAVA LAB Program 3. Inserting values in a table in database. import java.sql.*; import java.io.*; public class Insertmarks{ public Insertmarks() { } public void imks()throws IOException { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:moviecatalog","", ""); Statement stmt = con.createStatement(); String sql = "INSERT INTO MARKS VALUES(1,66,67,98,87,90)"; stmt.executeUpdate(sql); String sql1 = "INSERT INTO MARKS VALUES(3,66,67,98,87,90)"; stmt.executeUpdate(sql1); String sql2 = "INSERT INTO MARKS VALUES(21,66,67,98,87,90)"; stmt.executeUpdate(sql2); String sql3 = "INSERT INTO MARKS VALUES(23,66,67,98,87,90)"; stmt.executeUpdate(sql3); System.out.println("Inserted records into the table..."); stmt.executeUpdate(sql); } catch(SQLException se) { se.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } finally { // try{ // if(stmt!=null) // con.close(); // } // catch(SQLException se){ // } try{ if(con!=null) con.close(); } catch(SQLException se){ se.printStackTrace(); } }} public static void main(String[] args)throws IOException { Insertmarks imarks = new Insertmarks(); imarks.imks(); } } 13 | P a g e Advanced JAVA LAB OUTPUT Compile: Database: 14 | P a g e Advanced JAVA LAB Program 4. Updating values in a table in database. import java.sql.*; import java.io.*; public class Updatemarks{ public Updatemarks() { } public void umks()throws IOException { Connection con = null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:moviecatalog","", ""); Statement stmt = con.createStatement(); String sql = "UPDATE MARKS SET java=90, ada=98 WHERE Id=3;"; stmt.executeUpdate(sql); System.out.println("Updated Records..."); stmt.executeUpdate(sql); } catch(SQLException se) { se.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } finally { // try{ // if(stmt!=null) // con.close(); // } // catch(SQLException se){ // } try{ if(con!=null) con.close(); } catch(SQLException se){ se.printStackTrace(); } } } public static void main(String[] args)throws IOException { Updatemarks umarks = new Updatemarks(); umarks.umks(); } } 15 | P a g e Advanced JAVA LAB OUTPUT Compile: Database 16 | P a g e Advanced JAVA LAB Program 5. Prepared Statements in database import java.sql.*; class InsertPrepared{ public static void main(String args[]){ try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=con = DriverManager.getConnection("jdbc:odbc:moviecatalog","", ""); PreparedStatement stmt=con.prepareStatement("insert into MARKS values(?,?,?,?,?,?)"); stmt.setInt(1,123);//1 specifies the first parameter in the query stmt.setInt(2,69); stmt.setInt(3,78); stmt.setInt(4,74); stmt.setInt(5,91); stmt.setInt(6,56); int i=stmt.executeUpdate(); System.out.println(i+" records inserted"); con.close(); }catch(Exception e){ System.out.println(e);} } } 17 | P a g e Advanced JAVA LAB OUTPUT Compile: Database Affected: 18 | P a g e Advanced JAVA LAB Program 6. Scrollable RESULTSET in database import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class MyScrollableResultSetEx { public static void main(String a[]) { Connection con = null; Statement st = null; ResultSet rs = null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:moviecatalog","", ""); st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = st.executeQuery("select java, ada from MARKS"); System.out.println("ResultSet Curson is at before first: "+rs.isBeforeFirst()); while(rs.next()) { System.out.println(rs.getInt(1)+" "+rs.getInt(2)); } //now result set cursor reached the last position System.out.println("Is After Last: "+rs.isAfterLast()); while(rs.previous()) { System.out.println(rs.getInt(1)+" "+rs.getInt(2)); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try{ if(rs != null) rs.close(); if(st != null) st.close(); if(con != null) con.close(); } catch(Exception ex){} } } } 19 | P a g e Advanced JAVA LAB OUTPUT 20 | P a g e Advanced JAVA LAB Program 7. Deleting values in a table in database. import java.sql.*; import java.io.*; public class Deleterecord{ public Deleterecord() { } public void dltb()throws IOException { Connection con = null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:moviecatalog","", ""); Statement stmt = con.createStatement(); String sql = "DELETE FROM MARKS WHERE id=123;"; stmt.executeUpdate(sql); System.out.println("Deleted records from the table..."); stmt.executeUpdate(sql); } catch(SQLException se) { se.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } finally { // try{ // if(stmt!=null) // con.close(); // } // catch(SQLException se){ // } try{ if(con!=null) con.close(); } catch(SQLException se){ se.printStackTrace(); } }} public static void main(String[] args)throws IOException { Deleterecord dt = new Deleterecord(); dt.dltb(); } } 21 | P a g e Advanced JAVA LAB OUTPUT: Compile: Database View: 22 | P a g e Advanced JAVA LAB Program 8. Callable Statements in database Stored Procedure: CREATE DEFINER=`root`@`localhost` PROCEDURE `film_in_stock`(IN p_film_id INT, IN p_store_id INT, OUT p_film_count INT) READS SQL DATA BEGIN SELECT inventory_id FROM inventory WHERE film_id = p_film_id AND store_id = p_store_id AND inventory_in_stock(inventory_id); SELECT FOUND_ROWS() INTO p_film_count; END Program: import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class MySimpleCallableStatement { public static void main(String a[]){ Connection con = null; CallableStatement callSt = null; try { Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila","root","test"); callSt = con.prepareCall("{call film_in_stock(?,?,?)}"); callSt.setInt(1,200); callSt.setDouble(2, 3000); callSt.execute(); System.out.println("Executed stored procedure!!!"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try{ if(callSt != null) callSt.close(); if(con != null) con.close(); } catch(Exception ex){} } } } 23 | P a g e Advanced JAVA LAB OUTPUT 24 | P a g e SERVLETS Program 1: Hidden Form Field Index.html <form action="servlet1"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="go"/> </form> FirstServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class FirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); //creating form that have invisible textfield out.print("<form action='servlet2'>"); out.print("<input type='hidden' name='uname' value='"+n+"'>"); out.print("<input type='submit' value='go'>"); out.print("</form>"); out.close(); }catch(Exception e){System.out.println(e);} } } SecondServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); //Getting the value from the hidden field String n=request.getParameter("uname"); out.print("Hello "+n); 25 | P a g e out.close(); } catch(Exception e) { System.out.println(e); } } } Web.xml <web-app> <servlet> <servlet-name>servlet1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>servlet1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>servlet2</servlet-name> <servlet-class>SecondServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>servlet2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> </web-app> 26 | P a g e OUTPUT 1st Page: 2nd Page: 27 | P a g e 3rd Page: 28 | P a g e Program 2: URL Re-Writing Index.html <form action="servlet1"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="go"/> </form> FirstServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class FirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); //appending the username in the query string out.print("<a href='servlet2?uname="+n+"'>visit</a>"); out.close(); }catch(Exception e){System.out.println(e);} } } SecondServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); //getting value from the query string String n=request.getParameter("uname"); out.print("Hello "+n); out.close(); }catch(Exception e){System.out.println(e);} } } 29 | P a g e Web.xml <web-app> <servlet> <servlet-name>servlet1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>servlet1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>servlet2</servlet-name> <servlet-class>SecondServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>servlet2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> </web-app> 30 | P a g e OUTPUT 1st Page: 2nd Page: 31 | P a g e 3rd Page: 32 | P a g e Program 3: Cookies Index.html <form action="servlet1"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="go"/> </form> FirstServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class FirstServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); Cookie ck=new Cookie("uname",n);//creating cookie object response.addCookie(ck);//adding cookie in the response //creating submit button out.print("<form action='servlet2'>"); out.print("<input type='submit' value='go'>"); out.print("</form>"); out.close(); }catch(Exception e){System.out.println(e);} } } SecondServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); Cookie ck[]=request.getCookies(); out.print("Hello "+ck[0].getValue()); out.close(); }catch(Exception e){System.out.println(e);} } } 33 | P a g e Web.xml <web-app> <servlet> <servlet-name>servlet1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>servlet1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>servlet2</servlet-name> <servlet-class>SecondServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>servlet2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> </web-app> 34 | P a g e OUTPUT 1st Page: 2nd Page: 35 | P a g e 3rd Page: 36 | P a g e Program 4: HttpSession Index.html <form action="servlet1"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="go"/> </form> Index.html <form action="servlet1"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="go"/> </form> FirstServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class FirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); HttpSession session=request.getSession(); session.setAttribute("uname",n); out.print("<a href='servlet2'>visit</a>"); out.close(); }catch(Exception e){System.out.println(e);} } } SecondServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session=request.getSession(false); String n=(String)session.getAttribute("uname"); out.print("Hello "+n); 37 | P a g e out.close(); }catch(Exception e){System.out.println(e);} } } Web.xml <web-app> <servlet> <servlet-name>servlet1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>servlet1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>servlet2</servlet-name> <servlet-class>SecondServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>servlet2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> </web-app> 38 | P a g e OUTPUT 1st Page: 2nd Page: 39 | P a g e 3rd Page: 40 | P a g e Program 5: User Authorization First.html <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Servlet Login Example</title> </head> <body> <h1>Login App using HttpSession</h1> <a href="login.html">Login</a>| <a href="LogoutServlet">Logout</a>| <a href="ProfileServlet">Profile</a> </body> </html> Link.html <a href="login.html">Login</a> | <a href="LogoutServlet">Logout</a> | <a href="ProfileServlet">Profile</a> <hr> Login.html <form action="LoginServlet" method="post"> Name:<input type="text" name="name"><br> Password:<input type="password" name="password"><br> <input type="submit" value="login"> </form> Login Servlet import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); request.getRequestDispatcher("link.html").include(request, response); 41 | P a g e String name=request.getParameter("name"); String password=request.getParameter("password"); if(password.equals("admin123")){ out.print("Welcome, "+name); HttpSession session=request.getSession(); session.setAttribute("name",name); } else{ out.print("Sorry, username or password error!"); request.getRequestDispatcher("login.html").include(request, response); } out.close(); } } Logout Servlet import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LogoutServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); request.getRequestDispatcher("link.html").include(request, response); HttpSession session=request.getSession(); session.invalidate(); out.print("You are successfully logged out!"); out.close(); } } Profile Servlet import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class ProfileServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 42 | P a g e response.setContentType("text/html"); PrintWriter out=response.getWriter(); request.getRequestDispatcher("link.html").include(request, response); HttpSession session=request.getSession(false); if(session!=null){ String name=(String)session.getAttribute("name"); out.print("Hello, "+name+" Welcome to Profile"); } else{ out.print("Please login first"); request.getRequestDispatcher("login.html").include(request, response); } out.close(); } } 43 | P a g e OUTPUT Start Page: Login Page: 44 | P a g e Profile Page: Logout Page: 45 | P a g e JSP Program 1: Forward Action Tag Index.jsp <html> <body> <h2>this is index page</h2> <jsp:forward page="printdate.jsp" > <jsp:param name="name" value="Test Kumar"/> </jsp:forward> </body> </html> Printdate.jsp <html> <body> <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %> parameter name is: <%=request.getParameter("name") %> </body> </html> 46 | P a g e OUTPUT 47 | P a g e Program 1: Include Action Tag Index.jsp <html> <body> <h2>this is index page</h2> <jsp:include page="printdate.jsp" /> <h2>this is end of index page</h2> </body> </html> Printdate.jsp <html> <body> <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %> parameter name is: <%=request.getParameter("name") %> </body> </html> 48 | P a g e OUTPUT 49 | P a g e Program 3: useBean Tag Calculator.java package com.javatpoint; public class Calculator{ public int cube(int n){return n*n*n;} } Index.java <jsp:useBean id="obj" class="com.javatpoint.Calculator"/> <% int m=obj.cube(5); out.print("cube of 5 is "+m); %> 50 | P a g e OUTPUT 51 | P a g e Program 4: setProperty & getProperty Tag Index.html <form action="process.jsp" method="post"> Name:<input type="text" name="name"><br> Password:<input type="password" name="password"><br> Email:<input type="text" name="email"><br> <input type="submit" value="register"> </form> Process.jsp <jsp:useBean id="u" class="org.sssit.User"></jsp:useBean> <jsp:setProperty property="*" name="u"/> Record:<br> <jsp:getProperty property="name" name="u"/><br> <jsp:getProperty property="password" name="u"/><br> <jsp:getProperty property="email" name="u" /><br> User.java package org.sssit; public class User { private String name,password,email; //setters and getters } 52 | P a g e OUTPUT 1st Page: 2nd Page: 53 | P a g e Advanced JAVA Lab EJB Program 1: Stateless session bean Bean class package com.hubberspot.session.stateless; import javax.ejb.Stateless; import javax.ejb.LocalBean; @Stateless @LocalBean public class NewSessionBean { public int Add(int a,int b) { return(a+b); } public int Sub(int a,int b) { return(a-b); } public int Mul(int a,int b) { return(a*b); } public int Div(int a,int b) { return(a/b); }} Calculator Servlet package com.hubbersport.calculator; import com.hubberspot.session.stateless.NewSessionBean; import java.io.IOException; import java.io.PrintWriter; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name = "Calculator", urlPatterns = {"/Calculator"}) public class Calculator extends HttpServlet { @EJB private NewSessionBean cal; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); int a=Integer.parseInt(request.getParameter("number1")); int b=Integer.parseInt(request.getParameter("number2")); 54 | P a g e Advanced JAVA Lab try (PrintWriter out = response.getWriter()) { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Calculator</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>SUM=" + cal.Add(a,b) + "</h1>"); out.println("<h1>Difference=" + cal.Add(a,b) + "</h1>"); out.println("<h1>Multiplication=" + cal.Add(a,b) + "</h1>"); out.println("<h1>Division=" + cal.Add(a,b) + "</h1>"); out.println("Click <a href='index.html'>here</a> to go back "); out.println("</body>"); out.println("</html>"); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Short description"; } } 55 | P a g e Advanced JAVA Lab OUTPUT 56 | P a g e Advanced JAVA Lab Program 2: Statefull Session Bean Interface import javax.ejb.Remote; @Remote public interface Calculator { public int Add(int a,int b); public int Sub(int a,int b); public int Mul(int a,int b); public int Div(int a,int b); } Class implementing the interface import javax.ejb.Stateful; @Stateful public class StatefulSessionBean implements Calculator { @Override public int Add(int a, int b) { return(a+a); } @Override public int Sub(int a, int b) { return(a-a); } @Override public int Mul(int a, int b) { return(a*a); } @Override public int Div(int a, int b) { return(a/a); } } Servlet import java.io.IOException; import java.io.PrintWriter; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name = "Cal", urlPatterns = {"/Cal"}) public class Cal extends HttpServlet { @EJB 57 | P a g e Advanced JAVA Lab private StatefulSessionBean cal1; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); int a=Integer.parseInt(request.getParameter("number1")); int b=Integer.parseInt(request.getParameter("number2")); try (PrintWriter out = response.getWriter()) { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Cal</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>SUM=" + cal1.Add(a,b) + "</h1>"); out.println("<h1>Difference=" + cal1.Add(a,b) + "</h1>"); out.println("<h1>Multiplication=" + cal1.Add(a,b) + "</h1>"); out.println("<h1>Division=" + cal1.Add(a,b) + "</h1>"); out.println("Click <a href='index.html'>here</a> to go back "); out.println("</body>"); out.println("</html>"); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Short description"; } 58 | P a g e Advanced JAVA Lab Output 59 | P a g e Advanced JAVA Lab Program 3: Message driven bean MessageBean.java package com.message; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.ActivationConfigProperty; import javax.ejb.MessageDriven; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; @MessageDriven(mappedName = "jms/dest", activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") }) public class NewMessageBean implements MessageListener { public NewMessageBean() { } @Override public void onMessage(Message message) { TextMessage tmsg=null; tmsg=(TextMessage)message; try { System.out.println(tmsg.getText()); } catch (JMSException ex) { Logger.getLogger(NewMessageBean.class.getName()).log(Level.SEVERE, null, ex); } } } Index.jsp <html> <head> <title>Calculator</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form method="POST" action="/Calculator"> <table> <tr> <td>Enter the 1st number</td> <td><input type="TEXT" name="number1" id="number1"/></td> </tr> <tr> <td>Enter the 2nd number</td> <td><input type="TEXT" name="number2" id="number2"/></td> </tr> <tr> 60 | P a g e Advanced JAVA Lab <td><input type="submit" value="sub"/></td> </tr> </table> </form> </body> </html> Servlet package com.message; import java.io.IOException; import java.io.PrintWriter; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Resource; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name = "NewServlet", urlPatterns = {"/NewServlet"}) public class NewServlet extends HttpServlet { @Resource(mappedName = "jms/dest") private Queue dest; @Resource(mappedName = "jms/queue") private ConnectionFactory queue; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String str=request.getParameter("msg"); try { sendJMSMessageToDest(str); } catch (JMSException ex) { Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex); } try (PrintWriter out = response.getWriter()) { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet NewServlet</title>"); out.println("</head>"); out.println("<body>"); 61 | P a g e Advanced JAVA Lab out.println("<h1>Your message" + str + "has been send to the server</h1>"); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> private Message createJMSMessageForjmsDest(Session session, Object messageData) throws JMSException { // TODO create and populate message to send TextMessage tm = session.createTextMessage(); tm.setText(messageData.toString()); return tm; } private void sendJMSMessageToDest(Object messageData) throws JMSException { Connection connection = null; 62 | P a g e Advanced JAVA Lab Session session = null; try { connection = queue.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(dest); messageProducer.send(createJMSMessageForjmsDest(session, messageData)); } finally { if (session != null) { try { session.close(); } catch (JMSException e) { Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e); } } if (connection != null) { connection.close(); } } } } 63 | P a g e Advanced JAVA Lab Output 64 | P a g e Advanced JAVA Lab Program 4: Entity Session Bean NewEntityBean.java package SampleBean; import java.rmi.RemoteException; import javax.ejb.EJBException; import javax.ejb.EntityBean; import javax.ejb.EntityContext; import javax.ejb.RemoveException; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.TableGenerator; public class NewEntityBean implements EntityBean{ // Add business logic below. (Right-click in editor and choose // "Insert Code > Add Business Method") @Id @TableGenerator(name = "") @Column() Integer key; public Integer getID(){ return key; } public Integer doCalculation(int a,int b){ return a+b; } public NewEntityBean(){ } @Override public void setEntityContext(EntityContext ctx) throws EJBException, RemoteException { } @Override public void unsetEntityContext() throws EJBException, RemoteException { } @Override public void ejbRemove() throws RemoveException, EJBException, RemoteException { } @Override public void ejbActivate() throws EJBException, RemoteException { } @Override public void ejbPassivate() throws EJBException, RemoteException { } @Override public void ejbLoad() throws EJBException, RemoteException { } @Override public void ejbStore() throws EJBException, RemoteException { }} 65 | P a g e Advanced JAVA Lab HomeInterface.java package SampleBean; import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.EJBHome; public interface HomeInterface extends EJBHome{ public NewEntityBean create() throws CreateException,RemoteException; } ClientApplication.java public class ClientApplication { public static void main(String args[]) throws NamingException, CreateException, RemoteException{ Context initial =new InitialContext(); Context environment=(Context)initial.lookup("java:comp/env"); HomeInterface home=(HomeInterface)initial.lookup("NewEntityBean"); NewEntityBean bean= home.create(); System.out.println(bean.doCalculation(4,5)); } } 66 | P a g e Advanced JAVA Lab Output 67 | P a g e Advanced JAVA LAB STRUTS Create Action Class: package com.tutorialspoint.struts2; public class HelloWorldAction{ private String name; public String execute() throws Exception { return "success"; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Create a View <%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>Hello World</title> </head> <body> Hello World, <s:property value="name"/> </body> </html> Create main page: <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Hello World</title> </head> <body> <h1>Hello World From Struts2</h1> <form action="hello"> <label for="name">Please enter your name</label><br/> 68 | P a g e Advanced JAVA LAB <input type="text" name="name"/> <input type="submit" value="Say Hello"/> </form> </body> </html> struts.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="helloworld" extends="struts-default"> <action name="hello" class="com.tutorialspoint.struts2.HelloWorldAction" method="execute"> <result name="success">/HelloWorld.jsp</result> </action> </package> </struts> web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> 69 | P a g e Advanced JAVA LAB OUTPUT 70 | P a g e Advanced JAVA LAB ANDROID DATABASE CONNECTIVITY MainActivity.java. package com.example.addressbook; import java.util.ArrayList; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends Activity { public final static String EXTRA_MESSAGE = "com.example.AddressBook.MESSAGE"; private ListView obj; DBHelper mydb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mydb = new DBHelper(this); ArrayList array_list = mydb.getAllCotacts(); ArrayAdapter arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list); //adding it to the list view. obj = (ListView)findViewById(R.id.listView1); obj.setAdapter(arrayAdapter); obj.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub int id_To_Search = arg2 + 1; Bundle dataBundle = new Bundle(); dataBundle.putInt("id", id_To_Search); Intent intent = new Intent(getApplicationContext(),com.example.addressbook.DisplayContact.class); intent.putExtras(dataBundle); startActivity(intent); } 71 | P a g e Advanced JAVA LAB }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.mainmenu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch(item.getItemId()) { case R.id.item1: Bundle dataBundle = new Bundle(); dataBundle.putInt("id", 0); Intent intent = new Intent(getApplicationContext(),com.example.addressbook.DisplayContact.class); intent.putExtras(dataBundle); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } public boolean onKeyDown(int keycode, KeyEvent event) { if (keycode == KeyEvent.KEYCODE_BACK) { moveTaskToBack(true); } return super.onKeyDown(keycode, event); } } src/com.example.addressbook/DisplayContact.java package com.example.addressbook; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; 72 | P a g e Advanced JAVA LAB import android.widget.TextView; import android.widget.Toast; public class DisplayContact extends Activity { int from_Where_I_Am_Coming = 0; private DBHelper mydb ; TextView name ; TextView phone; TextView email; TextView street; TextView place; int id_To_Update = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_contact); name = (TextView) findViewById(R.id.editTextName); phone = (TextView) findViewById(R.id.editTextPhone); email = (TextView) findViewById(R.id.editTextStreet); street = (TextView) findViewById(R.id.editTextEmail); place = (TextView) findViewById(R.id.editTextCity); mydb = new DBHelper(this); Bundle extras = getIntent().getExtras(); if(extras !=null) { int Value = extras.getInt("id"); if(Value>0){ //means this is the view part not the add contact part. Cursor rs = mydb.getData(Value); id_To_Update = Value; rs.moveToFirst(); String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME)); String phon = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE)); String emai = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL)); String stree = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET)); String plac = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY)); if (!rs.isClosed()) { rs.close(); } Button b = (Button)findViewById(R.id.button1); b.setVisibility(View.INVISIBLE); name.setText((CharSequence)nam); name.setFocusable(false); name.setClickable(false); phone.setText((CharSequence)phon); 73 | P a g e Advanced JAVA LAB phone.setFocusable(false); phone.setClickable(false); email.setText((CharSequence)emai); email.setFocusable(false); email.setClickable(false); street.setText((CharSequence)stree); street.setFocusable(false); street.setClickable(false); place.setText((CharSequence)plac); place.setFocusable(false); place.setClickable(false); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. Bundle extras = getIntent().getExtras(); if(extras !=null) { int Value = extras.getInt("id"); if(Value>0){ getMenuInflater().inflate(R.menu.display_contact, menu); } else{ getMenuInflater().inflate(R.menu.main, menu); } } return true; } public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch(item.getItemId()) { case R.id.Edit_Contact: Button b = (Button)findViewById(R.id.button1); b.setVisibility(View.VISIBLE); name.setEnabled(true); name.setFocusableInTouchMode(true); name.setClickable(true); phone.setEnabled(true); phone.setFocusableInTouchMode(true); phone.setClickable(true); 74 | P a g e Advanced JAVA LAB email.setEnabled(true); email.setFocusableInTouchMode(true); email.setClickable(true); street.setEnabled(true); street.setFocusableInTouchMode(true); street.setClickable(true); place.setEnabled(true); place.setFocusableInTouchMode(true); place.setClickable(true); return true; case R.id.Delete_Contact: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.deleteContact) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mydb.deleteContact(id_To_Update); Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(getApplicationContext(),com.example.addressbook.MainActivity.class); startActivity(intent); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); AlertDialog d = builder.create(); d.setTitle("Are you sure"); d.show(); return true; default: return super.onOptionsItemSelected(item); } } public void run(View view) { Bundle extras = getIntent().getExtras(); 75 | P a g e Advanced JAVA LAB if(extras !=null) { int Value = extras.getInt("id"); if(Value>0){ if(mydb.updateContact(id_To_Update,name.getText().toString(), phone.getText().toString(), email.getText().toString(), street.getText().toString(), place.getText().toString())){ Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(getApplicationContext(),com.example.addressbook.MainActivity.class); startActivity(intent); } else{ Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show(); } } else{ if(mydb.insertContact(name.getText().toString(), phone.getText().toString(), email.getText().toString(), street.getText().toString(), place.getText().toString())){ Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show(); } Intent intent = new Intent(getApplicationContext(),com.example.addressbook.MainActivity.class); startActivity(intent); } } } } src/com.example.addressbook/DBHelper.java package com.example.addressbook; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase; public class DBHelper extends SQLiteOpenHelper { 76 | P a g e Advanced JAVA LAB public static final String DATABASE_NAME = "MyDBName.db"; public static final String CONTACTS_TABLE_NAME = "contacts"; public static final String CONTACTS_COLUMN_ID = "id"; public static final String CONTACTS_COLUMN_NAME = "name"; public static final String CONTACTS_COLUMN_EMAIL = "email"; public static final String CONTACTS_COLUMN_STREET = "street"; public static final String CONTACTS_COLUMN_CITY = "place"; public static final String CONTACTS_COLUMN_PHONE = "phone"; private HashMap hp; public DBHelper(Context context) { super(context, DATABASE_NAME , null, 1); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL( "create table contacts " + "(id integer primary key, name text,phone text,email text, street text,place text)" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXISTS contacts"); onCreate(db); } public boolean insertContact (String name, String phone, String email, String street,String place) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", name); contentValues.put("phone", phone); contentValues.put("email", email); contentValues.put("street", street); contentValues.put("place", place); db.insert("contacts", null, contentValues); return true; } 77 | P a g e Advanced JAVA LAB public Cursor getData(int id){ SQLiteDatabase db = this.getReadableDatabase(); Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null ); return res; } public int numberOfRows(){ SQLiteDatabase db = this.getReadableDatabase(); int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME); return numRows; } public boolean updateContact (Integer id, String name, String phone, String email, String street,String place) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", name); contentValues.put("phone", phone); contentValues.put("email", email); contentValues.put("street", street); contentValues.put("place", place); db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } ); return true; } public Integer deleteContact (Integer id) { SQLiteDatabase db = this.getWritableDatabase(); return db.delete("contacts", "id = ? ", new String[] { Integer.toString(id) }); } public ArrayList getAllCotacts() { ArrayList array_list = new ArrayList(); //hp = new HashMap(); SQLiteDatabase db = this.getReadableDatabase(); Cursor res = db.rawQuery( "select * from contacts", null ); res.moveToFirst(); while(res.isAfterLast() == false){ array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME))); res.moveToNext(); } return array_list; } } res/layout/activity_main.xml 78 | P a g e Advanced JAVA LAB <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" > </ListView> </RelativeLayout> res/layout/activity_display_contact.xml <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/scrollView1" android:layout_width="match_parent" android:layout_height="wrap_content" tools:context=".DisplayContact" > <RelativeLayout android:layout_width="match_parent" android:layout_height="370dp" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" > <EditText android:id="@+id/editTextName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_marginTop="5dp" android:layout_marginLeft="82dp" 79 | P a g e Advanced JAVA LAB android:ems="10" android:inputType="text" > </EditText> <EditText android:id="@+id/editTextEmail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editTextStreet" android:layout_below="@+id/editTextStreet" android:layout_marginTop="22dp" android:ems="10" android:inputType="textEmailAddress" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/editTextName" android:layout_alignParentLeft="true" android:text="@string/name" android:textAppearance="?android:attr/textAppearanceMedium" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editTextCity" android:layout_alignParentBottom="true" android:layout_marginBottom="28dp" android:onClick="run" android:text="@string/save" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/editTextEmail" android:layout_alignLeft="@+id/textView1" android:text="@string/email" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/editTextPhone" 80 | P a g e Advanced JAVA LAB android:layout_alignLeft="@+id/textView1" android:text="@string/phone" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/editTextEmail" android:layout_alignLeft="@+id/textView5" android:text="@string/street" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/editTextCity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/editTextName" android:layout_below="@+id/editTextEmail" android:layout_marginTop="30dp" android:ems="10" android:inputType="text" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/editTextCity" android:layout_alignBottom="@+id/editTextCity" android:layout_alignParentLeft="true" android:layout_toLeftOf="@+id/editTextEmail" android:text="@string/country" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/editTextStreet" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editTextName" android:layout_below="@+id/editTextPhone" android:ems="10" android:inputType="text" > <requestFocus /> </EditText> <EditText 81 | P a g e Advanced JAVA LAB android:id="@+id/editTextPhone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editTextStreet" android:layout_below="@+id/editTextName" android:ems="10" android:inputType="phone|text" /> </RelativeLayout> </ScrollView> res/value/string.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Address Book</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="Add_New">Add New</string> <string name="edit">Edit Contact</string> <string name="delete">Delete Contact</string> <string name="title_activity_display_contact">DisplayContact</string> <string name="name">Name</string> <string name="phone">Phone</string> <string name="email">Email</string> <string name="street">Street</string> <string name="country">City/State/Zip</string> <string name="save">Save Contact</string> <string name="deleteContact">Are you sure, you want to delete it.</string> <string name="yes">Yes</string> <string name="no">No</string> </resources> res/menu/mainmenu.xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/item1" android:icon="@drawable/add" android:title="@string/Add_New" android:showAsAction="ifRoom|withText"> </item> 82 | P a g e Advanced JAVA LAB </menu> Following is the content of the res/menu/display_contact.xml <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/Edit_Contact" android:orderInCategory="100" android:title="@string/edit"/> <item android:id="@+id/Delete_Contact" android:orderInCategory="100" android:title="@string/delete"/> </menu> AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.addressbook" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.addressbook.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.addressbook.DisplayContact" android:label="@string/title_activity_display_contact" > </activity> </application> </manifest> 83 | P a g e Advanced JAVA LAB OUTPUT 84 | P a g e Advanced JAVA LAB 85 | P a g e Advanced JAVA LAB 86 | P a g e