J2EE Lab Manual 2013

160
J2EE LABORATORY BMSI T 1) Write a JAVA Program to insert data into Student DATA BASE and retrieve info based on particular queries (queries can be given which covers all the topics of 2nd U NIT). Procedure for Execution. Step1: Open MySQL and create a database called stud. Step2: Open the NetBeans 7.1 Editor‐> Select File‐>New Project Step3: Code the java file which is there below (Lab1.java) and save it and co mpile F9 Step4: Right Click on project folder‐> Select properties ‐> Select Libraries ‐>Click Add Jar/Folder button ‐> find the MYSQL Connector plug‐in and click ok. Step5: Right click on the java file and select run.

description

VTU MCA 4th sem TEA-I J2EE lab manual

Transcript of J2EE Lab Manual 2013

Page 1: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  1)  Write  a  JAVA  Program  to  insert  data  into  Student  DATA  BASE  and  retrieve  info  based  on particular queries (queries can be given which covers all the topics of 2nd UNIT).  Procedure for Execution. Step1: Open MySQL and create a database called stud.  Step2: Open the NetBeans 7.1 Editor >‐  Select File >New‐  Project  

  Step3: Code the java file which is there below (Lab1.java) and save it and compile F9 

Step4: Right Click on project folder >‐  Select properties  >‐  Select Libraries  >Click‐  Add Jar/Folder button  >‐  find the MYSQL Connector plug in‐  and click ok.  

  Step5: Right click on the java file and select run.     

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 1  

Page 2: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Brief Introduction about the Program:  1.  Statement  Object:  Is  used  whenever  a  J2EE  component  needs  to  immediately  execute  a  query without first having the query compiled. It contains the executeQuery() method, which is passed the qu ry ae s an argument. The query is then transmitted to the DBMS for processing.  2.  The  executeQuery()  method  r eturns  o ne  R esultSet  o bject  t hat  c ontains  r ows,  c olumns,  and metadata that represent data requested by query.  3. The execute() method of the statement object is used when there may be multiple results returned.  4.  The  executeUpdate()  method  is  used  to execute  queries  that  contain  INSERT,  UPDATE,  DELETE and DDL statements.  5. PreparedStatement object: A SQL query must be compiled before the DBMS processes the query. Compiling occurs after one of the Statement object’s execution methods is called.  6.  CallableStatement  object:  Is  used  to  call  a  stored  procedure  within  a  J2EE  object.  A  stored procedure is a block of code and is identified by a unique name.  7. CallableStatement object uses three types of parameters when calling a stored procedure. These are IN, OUT, INOUT.  8. Class.forName(“com.mysql.jdbc.Driver”) – Is used to load the JDBC driver.  9.  DriverManager.getConnection(url,userID,password)  –  Method returns a Connection interface that is used throughout the process to reference the database.  10. java.sql package that manages communication between the driver and the J2EE component.   Program:  package lab1; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.sql.*; public class Lab1 {     private Connection con;     private Statement Datareq;     private ResultSet rs;     public Lab1()     {         final String url="jdbc:mysql://localhost:3306/stud";         String userid="root";         String password="root";         try         {             Class.forName("com.mysql.jdbc.Driver");             con=DriverManager.getConnection(url,userid,password);                      

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 2  

Page 3: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T          }             catch(ClassNotFoundException err)             {                 System.err.println("Unable to load the mysql Driver"+err);                 System.exit(1);             }         catch(SQLException error1)         {             System.err.println("Cannot connect to the Database"+error1);             System.exit(2);         }         try         {             while(true)             {               System.out.println("\n1.Queries Like:Create table,view,alter,drop,update and delete");               System.out.println("\n2.Queries Like:Insert");               System.out.println("\n3.QueriesLike:Selection/Calculation/GroupBy/OrderBy 

 /Join/Conditional Testing");               System.out.println("\n4.Exit");               InputStreamReader isr=new InputStreamReader(System.in);               BufferedReader br=new BufferedReader(isr);               System.out.println("\nSelect Your Choice");               int ch=Integer.parseInt(br.readLine());               switch(ch)                 {                     case 1:                         try                         {                             System.out.println("\nQueries Like:Create table,view,alter,drop,update                             and  delete\n");                             String q1=br.readLine();                             Datareq=con.createStatement();                             Datareq.execute(q1);                             System.out.println("\nQuery Executed Successfully\n");                             Datareq.close();                         }                         catch(SQLException sqle)                         {                             System.err.println(sqle);                         }                         break;                     case 2:                         try                         {                             PreparedStatement pst;                             System.out.println("\nQueries Like:Insert\n");                             String q2=br.readLine();                             pst=con.prepareStatement(q2);                             pst.execute();                             System.out.println("\nRecods inserted Successfully\n");                             pst.close(); 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 3  

Page 4: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T                          }                         catch(SQLException e)                         {                             System.out.println(e);                         }                         break;                     case 3:                         try                         {                              System.out.println("\nQueries Like:Selection/Calculation/GroupBy/OrderBy       /Join/Conditional Testing\n");                     String str=br.readLine();                             Datareq=con.createStatement();                             rs=Datareq.executeQuery(str);                             DisplayResult(rs);                                   Datareq.close();                         }                         catch(Exception eq)                         {                             System.err.println(eq);                         }                     case 4:                         System.exit(0);                         break;                 }             }         }                 catch(IOException ioe)                 {                     System.err.println(ioe);                 }    }     private void DisplayResult(ResultSet Result2) throws SQLException     {         ResultSetMetaData rmd=Result2.getMetaData();         int col=rmd.getColumnCount();         int Count=1;         boolean b=Result2.next();         if(!b)         {             System.out.println("\nData Found\n");         }         else         {             do             {                 System.out.print("Record"+(Count++)+"=>");                 for(int i=0;i<col;i++)                 System.out.println(Result2.getString(i+1)+"\t");                 System.out.println();             }             while(Result2.next()); 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 4  

Page 5: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T          }     }     public static void main(String args[])     {         final Lab1 stud1= new Lab1();     }  }  Output:  1.Queries Like:Create table,view,alter,drop,update and delete 2.Queries Like:Insert 3.Queries Like:Selection/Calculation/GroupBy/OrderBy/Join/Conditional Testing 4.Exit   Select Your Choice: 1  Queries Like:Create table,view,alter,drop,update and delete create table studinfo(usn varchar(10) primary key, name varchar(20)); Query Executed Successfully  1.Queries Like:Create table,view,alter,drop,update and delete 2.Queries Like:Insert 3.Queries Like:Selection/Calculation/GroupBy/OrderBy/Join/Conditional Testing 4.Exit  Select Your Choice: 3  desc studinfo; Record =>us1 n   varcha (10) r  NO   PRI      Record =>na2 me   varcha (20)   rYES   Null  1.Queries Like:Create table,view,alter,drop,update and delete 2.Queries Like:Insert 3.Queries Like:Selection/Calculation/GroupBy/OrderBy/Join/Conditional Testing 4.Exit  Select Your Choice: 2  Queries Like:Insert  insert into studinfo values('1BY11MCA40','RAVIKUMARA M M'); Recods inserted Successfully  

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 5  

Page 6: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  1.Queries Like:Create table,view,alter,drop,update and delete 2.Queries Like:Insert 3.Queries Like:Selection/Calculation/GroupBy/OrderBy/Join/Conditional Testing 4.Exit  Select Your Choice3  Queries Like:Selection/Calculation/GroupBy/OrderBy/Join/Conditional Testing  select * from studinfo; Record1=>1BY11MCA40   RAVIKUMARA M M  1.Queries Like:Create table,view,alter,drop,update and delete 2.Queries Like:Insert 3.Queries Like:Selection/Calculation/GroupBy/OrderBy/Join/Conditional Testing 4.Exit  Select Your Choice: 1  Queries Like:Create table,view,alter,drop,update and delete  Alter table studinfo add column course varchar(10); Query Executed Successfully  1.Queries Like:Create table,view,alter,drop,update and delete 2.Queries Like:Insert 3.Queries Like:Selection/Calculation/GroupBy/OrderBy/Join/Conditional Testing 4.Exit  Select Your Choice: 1  Queries Like:Create table,view,alter,drop,update and delete  update studinfo set course='MCA' where usn='1BY11MCA40'; Query Executed Successfully  1.Queries Like:Create table,view,alter,drop,update and delete 2.Queries Like:Insert 3.Queries Like:Selection/Calculation/GroupBy/OrderBy/Join/Conditional Testing 4.Exit  Select Your Choice: 3  Queries Like:Selection/Calculation/GroupBy/OrderBy/Join/Conditional Testing  select * from studinf ;o  Record1=>1BY11MCA40   RAVIKUMARA M M   MCA   

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 6  

Page 7: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  2) Write a JAVA Servlet Program to implement a dynamic HTML using Servlet (user name and password should be accepted using HTML and displayed using a Servlet).  Procedure for Execution.  Step1.:Open the NetBeans 6.9.1 Editor >‐  Select File >New‐  Project Step2: Select Java Web Folder in Categories >‐  Select Web Application option >‐  click Next Step3: Give the project name and select Main project check box  >click‐  Next.  

  Step 4. Select the Server Tomcat >‐ ‐  Click Next  >‐  Click Finish  

    

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 7  

Page 8: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Step 5:Right Click the WebPages folder and select new then select html  >‐  Give the name of HTML file  >‐  Click finish.  Step6: Code the HTML file and save it. Step 7: Right Click on project folder >‐  Select New  >‐  Select Servlet  >‐  Give the name of Servlet and package name >‐  Click next.  

     Step 8:Observe the Configure Servlet Deployment as Servlet Name and URL pattern; it will create the web.xml descriptor file for our Servlet  >‐  Click finish  >‐  Code the Servlet file Step 9.:Right click on the HTML file and select run.  Brief Introduction.  1.  Servlet  – is a server side program. A Java Servlet is a Java class that reads requests sent from a client and responds by sending information to the client.  2. Java class must extend Httpservlet and override Httpservlet’s doGet() or doPost() methods.  3. doGet() or doPost() methods require two arguments. The HttpServletRequest object and HttpServletResponse object arguments. 4. HttpServletRequest object contains incoming information and HttpServletResponse object is used by the java servlet to send outgoing information to the client.  5. Both method throws a servletException and IOException,        

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 8  

Page 9: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Program:  //Prog2.html  <html>     <head>         <title> Display Username and Password using Servlet  </title> </head>     <body bgcolor="pink">         <form method="post" action="Prog2Servlet">             Username <input type="text" name="username" size="35">             Password <input type="password" name="password" size="35"><br/>             <input type="submit" value="Submit"/>             <input type="reset" value="Reser">         </form>     </body> </html>  //Prog2Servlet.java  package mypackage; 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; public class Prog2Servlet extends HttpServlet {     @Override        protected void doPost(HttpServletRequest req, HttpServletResponse res)             throws ServletException, IOException        {         PrintWriter out = res.getWriter();         String uname=req.getParameter("username");         String pass=req.getParameter("password");             out.println("<html>");             out.println("<head>");             out.println("<title>Servlet prog2servlet</title>");             out.println("</head>");             out.println("<body>");             out.println("<h1>User Information</h1>");             out.println("<br><hr1><br/>");             out.println("<h3>Dear user your information<br/><br/>");             out.println("Username:  "+uname+"<br/>");             out.println("Password:  "+pass+"<br/></h3>");             out.println("</body>");             out.println("</html>");         }     }    

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 9  

Page 10: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  //Web.xml  <web app>‐      <servlet>         <servlet name>Prog2Servlet</servlet name>‐ ‐          <servlet class>mypackage.Prog2Servlet</servlet class>‐ ‐      </servlet>     <servlet mapping>‐          <servlet name>Prog2Servlet</servlet name>‐ ‐          <url pattern>/Prog2Servlet</url pattern>‐ ‐      </servlet mapping>‐  </web app>‐   Output:  

   

                 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 10  

Page 11: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  3) 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).  Procedure for Execution.  1. Open the NetBeans 7.1 Editor >‐  Select File >New‐  Project 2. Select Java Web Folder in Categories >‐  Select Web Application option >‐  click Next 3. Give the project name and select Main project check box  >click‐  Next.  

  4. Select the Server Tomcat >‐ ‐  Click Next  >‐  Click Finish 5. Right Click the WebPages folder and select new then select html  >‐  Give the name of HTML file  >‐  Click finish. 

  

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 11  

Page 12: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  6. Code the HTML file and save it. 7. Right Click on project folder >‐  Select New  >‐  Select Servlet  >‐  Give the name of Servlet and package name >‐  Click next  

    8. Observe the Configure Servlet Deployment as Servlet Name and URL pattern; it will create the web.xml descriptor file for our Servlet  >‐  Click finish  >‐  Code the Servlet file 9. Right click on the HTML file and select run.  Program:  //Prog3.html <html>     <head>         <title> File Download </title>     </head>     <body>     <center>         <h1> The File Download Program</h1>     </center>     <a href="Prog3Servlet"> click here to download the file </a>     </body> </html>  //Prog3Servlet.java package mypackage; import javax.servlet.http.*; import javax.servlet.*; import java.io.*; public class Prog3Servlet extends HttpServlet { 

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException  { 

ServletContext sc = getServletContext(); String filename = sc.getRealPath("Test.txt"); String mimeType = sc.getMimeType(filename); if (mimeType == null)  { 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 12  

Page 13: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  

sc.log("Could not get MIME type of "+filename); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; 

} resp.setContentType(mimeType); File file = new File(filename); resp.setContentLength((int)file.length()); FileInputStream in = new FileInputStream(file); OutputStream out = resp.getOutputStream(); byte[] buf = new byte[1024]; int count = 0; while ((count = in.read(buf)) >= 0)  { 

out.write(buf, 0, count); } 

in.close(); out.close(); } 

}  //Web.xml  <web app>‐      <servlet>         <servlet name>Prog3Servlet</servlet name>‐ ‐          <servlet class>mypackage.Prog3Servlet</servlet class>‐ ‐      </servlet>     <servlet mapping>‐          <servlet name>Prog3Servlet</servlet name>‐ ‐          <url pattern>/Prog3Servlet</url pattern>‐ ‐      </servlet mapping>‐  </web app>‐   //Test.txt  You fool nothing is there to Download.                 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 13  

Page 14: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Output:  

           

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 14  

Page 15: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  4)  Write  a  JAVA  Servlet  Program  to  implement  RequestDispatcher  object  (use  include()  and forward() methods).  Procedure for Execution.  Step1. Open the NetBean 7.1 Editor >‐  Select File >New‐  Project Step 2. Select Java Web Folder in Categories >‐  Select Web Application option >‐  click Next Step 3. Give the project name and select Main project check box  >click‐  Next.  

  Step 4. Select the Server Tomcat >‐ ‐  Click Next  >‐  Click Finish Step 5. Right Click the webpages folder and select new then select html  >‐  Give the name of HTML file  >‐  Click finish.  

   

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 15  

Page 16: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Step 6. Code the HTML file and save it. Step 7.1. Right Click on project folder >‐  Select New  >‐  Select Servlet  >‐  Give the name of Servlet and package name >‐  Click next.  

  Step 7. 2.Right Click on project folder >‐  Select New  >‐  Select Servlet  >‐  Give the name of Servlet and package name >‐  Click next. 

  Step 8. Observe the Configure Servlet Deployment as Servlet Name and URL pattern; it will create the web.xml descriptor file for our Servlet  >‐  Click finish  >‐  Code the Servlet file Step 9. Right click on the HTML file and select run.   

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 16  

Page 17: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Brief Introduction   1.  RequestDispatcher  class  is  mainly  used  to  'pass  on'  the  current  request  to  another  program (servlet) and therefore allows 'chaining' of the programs. A RequestDispatcher primarily contains two methods include() and forward(). include() method includes the response of another program while forward() method forwards the request of the current program to another one.  2. forward(): The forward() method of RequestDispatcher forwards the request and response objects of  ServletRequest  and  ServletResponse  interface  respectively  to  the  path  specified  in getRequestDispatcher(String path). The response is sent back to the client therefore the client does not know about this change of resource on the server. This method helps for communicating between server  resources,  (servlet  to  servlet).  Since  request  and  response  objects  are  forwarded  to  another resource therefore all request parameters are maintained and available for use. Any code written after forward(request, response) method will not execute as the request is already forwarded. As the client is not aware about this forward on the server therefore no history will be stored on the client and as a result backward and forward buttons does not work. This method is faster as compared to using sendRedirect because no network round trip to the server and back is required.  3. include(): This method includes the content of a resource in the response. The resource may either be a servlet, or a JSP page, or an HTML file. This method also enables  programmatic  server side‐  includes. The included servlet can't change the status code or set headers of the response, any attempt made to do so is ignored. This method can be called at any time. It can only use ServletOutputStream or Writer of the response object to write the information.  Program:  //Prog4.html  <html>     <head>         <title></title>      </head>     <body bgcolor="violet">         <form action="Prog4Servlet" method="post">               <input type="hidden" name="decider" value="forward"/>             <input type="submit" value="forward"/>         </form>         <form action="Prog4Servlet" method="post">               <input type="hidden" name="decider" value="include"/>             <input type="submit" value="include"/>         </form>     </body> </html>          

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 17  

Page 18: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  //Prog4Servlet.java  package mypackage; import java.io.IOException; import java.io.PrintWriter; 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 Prog4Servlet extends HttpServlet  {     @Override     protected void doPost(HttpServletRequest request, HttpServletResponse response)     throws ServletException, IOException      {         String decider=request.getParameter("decider");         RequestDispatcher rd=null;         if("forward".equals(decider))         {             rd=request.getRequestDispatcher("RegServlet");             rd.forward(request, response);         }         else             if("include".equals(decider))         {             rd=request.getRequestDispatcher("RegServlet");             rd.include(request, response);         }         PrintWriter out = response.getWriter();         out.println("Welcome to the requestdispatcher i am from requestdispatcher<br/>");         out.println("<br/>I am due to request dispatcher method include<br/>");     } }  //RegServlet.java  package mypackage; 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; public class RegServlet extends HttpServlet  {     protected void doPost(HttpServletRequest request, HttpServletResponse response)             throws ServletException, IOException      {             PrintWriter out = response.getWriter();             out.println("<html>");             out.println("<head>"); 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 18  

Page 19: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T              out.println("<title>Servlet RegServlet</title>");                         out.println("</head>");             out.println("<body bgcolor=pink>");             out.print("<p>Hi my name is Ravikumar am from RegServlet</p><br/>");             out.println("</body>");             out.println("</html>");         }  }  //Web.xml  <web app>‐      <servlet>         <servlet name>Prog4Servlet</servlet name>‐ ‐          <servlet class>mypackage.Prog4Servlet</servlet class>‐ ‐      </servlet>     <servlet>         <servlet name>RegServlet</servlet name>‐ ‐          <servlet class>mypackage.RegServlet</servlet class>‐ ‐      </servlet>     <servlet mapping>‐          <servlet name>Prog4Servlet</servlet name>‐ ‐          <url pattern>/Prog4Servlet</url pattern>‐ ‐      </servlet mapping>‐      <servlet mapping>‐          <servlet name>RegServlet</servlet name>‐ ‐          <url pattern>/RegServlet</url pattern>‐ ‐      </servlet mapping>‐     </web app>‐                         

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 19  

Page 20: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Output:  

  

  

        

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 20  

Page 21: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  5) Write a JAVA Servlet Program to implement and demonstrate get() and Post methods(Using HTTP Servlet Class).  Procedure for Execution.  Step1. Open the NetBean 7.1 Editor >‐  Select File >New‐  Project Step 2. Select Java Web Folder in Categories >‐  Select Web Application option >‐  click Next Step 3. Give the project name and select Main project check box  >click‐  Next.  

  Step 4. Select the Server Tomcat >‐ ‐  Click Next  >‐  Click Finish Step 5. Right Click the webpages folder and select new then select html  >‐  Give the name of HTML file  >‐  Click finish. Step 6. Code the HTML file and save it.  

   

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 21  

Page 22: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Step 7. Right Click on project folder >‐  Select New  >‐  Select Servlet  >‐  Give the name of Servlet and package name >‐  Click next. 

  Step 8. Observe the Configure Servlet Deployment as Servlet Name and URL pattern; it will create the web.xml descriptor file for our Servlet  >‐  Click finish  >‐  Code the Servlet file Step 9. Right click on the HTML file and select run.  Brief Introduction   1. The doGet() method is used to interact with a request sent using the method=”GET” attribute from an HTML form, when passing parameters on the URL like a hyperlink, The parameters values displayed in that url. A doGet() method is limited with 2k of data to be S nt. e 2. The doPost() method is used to interact with a request sent using the method=”POST”. Implicitly sends the request parameter values to the servlet. It supports huge amount of data requests.  Program: //Prog5.html  <html>     <head>         <title>Illustration of Get and Post methods </title>     </head>     <body>         <form name="md1" action="Prog5GetPostServlet" method="post">             POST method Illustration<br><br>             Username <input type="text" name="username">             Password <input type="password" name="password">             <input type="submit" value="submit">          </form>         <form name="md1" action="Prog5GetPostServlet" method="get">             GET method Illustration<br><br>             Username <input type="text" name="username"> 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 22  

Page 23: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T              Password <input type="password" name="password">             <input type="submit" value="submit">          </form>     </body> </html>  //Prog5GetPostServlet.java  package mypackage; 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;  public class Prog5GetPostServlet extends HttpServlet  {  protected  void  doPost(HttpServletRequest  req,HttpServletResponse  r es)  t hrows  S ervletException, IOException     {   PrintWriter out=res.getWriter();   String username=req.getParameter("username");   String password=req.getParameter("password");   if(username.length()==0||password.length()==0)   {       out.println("<script type=text/javascript>");       out.println("alert('userid or password couldnot be blank'");       out.println("</script>");    }   else   {       out.println("<html><body>");       out.println("username="+username);       out.println("password="+password);        out.println("</body></html>");    } }  protected  void  doGet(HttpServletRequest  req,HttpServletResponse  res)  throws  ServletException, IOException     {   PrintWriter out=res.getWriter();   String username=req.getParameter("username");   String password=req.getParameter("password");   if(username.length()==0||password.length()==0)   {       out.println("<script type=text/javascript>");       out.println("alert('userid or password couldnot be blank'");       out.println("</script>");    }   else   { 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 23  

Page 24: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T        out.println("<html><body>");       out.println("username="+username);       out.println("password="+password);        out.println("</body></html>");    }   } } //Web.xml  <web app>‐      <servlet>         <servlet name>Prog5GetPostServlet</servlet name>‐ ‐          <servlet class>mypackage.Prog5GetPostServlet</servlet class>‐ ‐      </servlet>     <servlet mapping>‐          <servlet name>Prog5GetPostServlet</servlet name>‐ ‐          <url pattern>/Prog5GetPostServlet</url pattern>‐ ‐      </servlet mapping>‐  </web app>‐                                   

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 24  

Page 25: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Output:  

  

  

  

          

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                  P a g e  | 25  

Page 26: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  6)  Write  a  JAVA  Servlet  Program  to  implement  sendRedirect()  method(using  HTTP  Servlet Class).  Procedure for Execution.  Step1. Open the NetBean 7.1 Editor >‐  Select File >New‐  Project Step 2. Select Java Web Folder in Categories >‐  Select Web Application option >‐  click Next Step 3. Give the project name and select Main project check box  >click‐  Next.  

  Step 4. Select the Server Tomcat >‐ ‐  Click Next  >‐  Click Finish Step 5. Right Click the webpages folder and select new then select html  >‐  Give the name of HTML file  >‐  Click finish. Step 6. Code the HTML file and save it. 

     

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 26  

Page 27: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Step 7.1. Right Click on project folder >‐  Select New  >‐  Select Servlet  >‐  Give the name of Servlet and package name >‐  Click next  

   Step 7.2. Right Click on project folder >‐  Select New  >‐  Select Servlet  >‐  Give the name of Servlet and package name >‐  Click next  

  Step 8. Observe the Configure Servlet Deployment as Servlet Name and URL pattern; it will create the web.xml descriptor file for our Servlet  >‐  Click finish  >‐  Code the Servlet file Step 9. Right click on the HTML file and select run.  Brief Introduction   sendRedirect():When we want that someone else should handle the response of our servlet, then there we should use sendRedirect() method. In send Redirect whenever the client makes any request it goes to the container, there the container decides whether the concerned servlet can handle the request or not. If not then the servlet decides that the request can be handle by other servlet or jsp. Then the  servlet  calls  the  sendRedirect() method of the response object and sends back the response to the browser along with the status code. 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 27  

Page 28: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Then the browser sees the status code and look for that servlet which can now handle the request. Again the browser makes a new request, but with the name of that servlet which can now handle the request and the result will be displayed to you by the browser. In all this process the client is unaware of the processing.  Program:  //Prog6.html  <html>     <head>         <title> SendRedirectPage </title>     </head>     <body bgcolor="pink">         <form method="post" action="Prog6SendRedirectServlet">             <p>Enter username:<input type="text" name="username" size="20"/> </p>             <p>Enter password:<input type="password" name="password" size="10"/></p>             <p>Enter Phone number:<input type="text" name="phoneno" size="10"/></p>             <p><input type="submit" value="submit"/></p>         </form>     </body> </html>  //Prog6SendRedirectServlet.java  package mypackage; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Prog6SendRedirectServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException  { 

response.setContentType("text/html"); PrintWriter out = response.getWriter(); String username = req.getParameter("username"); String password = req.getParameter("password"); String phoneno = req.getParameter("phoneno"); if((username.equals("Ravi")&& password.equals("Kumar"))||(username.equals("Shashi")&& password.equals("Kumar"))) { 

out.println("<html>"); out.println("<head><title>Program 6 </title></head>"); out.println("<body>"); out.println("<h1>User Information</h1>"); out.println("<br><hr><br>"); out.println("Dear User.<br>"); out.println("Your Information.<br><br>"); out.println("UserName: "+username+"<br>"); out.println("password :"+password+"<br>"); 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 28  

Page 29: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  

out.println("Contact Number:"+phoneno+"<br>"); out.println("</body>"); out.println("</html>"); 

} else { 

response.sendRedirect("validUser"); } 

} } // validUser.java  package mypackage; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class validUser extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { 

PrintWriter out = response.getWriter(); out.println("<h1> <font color = red> u r not a valid user " + " "); out.println("<br><h2><font color = purple>please enter the valid data"); 

} } //Web.xml   <web app>‐      <servlet>         <servlet name>Prog6SendRedirectServlet</servlet name>‐ ‐          <servlet class>mypackage.Prog6SendRedirectServlet</servlet class>‐ ‐      </servlet>     <servlet>         <servlet name>validUser</servlet name>‐ ‐          <servlet class>mypackage.validUser</servlet class>‐ ‐      </servlet>     <servlet mapping>‐          <servlet name>Prog6SendRedirectServlet</servlet name>‐ ‐          <url pattern>/Prog6SendRedirectServlet</url pattern>‐ ‐      </servlet mapping>‐      <servlet mapping>‐          <servlet name>validUser</servlet name>‐ ‐          <url pattern>/validUser</url pattern>‐ ‐      </servlet mapping>‐  </web app>‐      

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 29  

Page 30: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Output:  

  

  

  

        

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 30  

Page 31: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  7) Write a JAVA Servlet Program to implement sessions (Using HTTP Session Interface).  Procedure for Execution.  Step1. Open the NetBean 7.1 Editor >‐  Select File >New‐  Project Step 2. Select Java Web Folder in Categories >‐  Select Web Application option >‐  click Next Step 3. Give the project name and select Main project check box  >click‐  Next.  

  Step 4. Select the Server Tomcat >‐ ‐  Click Next  >‐  Click Finish Step 5. Right Click on project folder >‐  Select New  >‐  Select Servlet  >‐  Give the name of Servlet and package name >‐  Click next  

  Step6:Create the Servlet named SessionTracking.java Step7: Save and compile it. Step8 Right click on the SessionTracking.java file and run it. Step9: Set Servlet Execution URI as /SessionTracking. Press OK. 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 31  

Page 32: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  

  Brief Introduction  1.  Session:  A  Session  refers  to  all  the  request  that  a  single  client  makes  to a server. A session is specific to the user and for each user a new session is created to track all the request from that user. Every user has a separate session and separate session variable is associated with that session. In case of  w eb  a pplications  t he  d efault  t ime out‐   value  for  session  variable  i s  2 0  m inutes,  w hich  c an  b e changed as per the requirement.  2.  Session  ID:  A session ID is an unique identification string usually a long,  random  and  alpha‐numeric string, that is transmitted between the client and the server. Session IDs are usually stored in the cookies, URLs (in case url rewriting) and hidden fields of Web pages.  3. Session Tracking:  HTTP is stateless protocol and it does not maintain the client state. But there exist a mechanism called "Session Tracking" which helps the servers to maintain the state to track the series of requests from the same user across some period of time.  4. Types of Session Tracking: ‐ a) Cookies b) URL rewriting c) Hidden form fields d) SSL Sessions  5. HTTPSession Class:  HttpSession  C lass  p rovides  a   w ay  t o  i dentify  a   u ser  a cross  a cross  multiple  request.  The  servlet container uses HttpSession interface to create a session between an HTTP client and an HTTP server. The session lives only for a specified time period, across more than one connection or page request from the user.  6. Session Tracking in HttpServlet:  In HttpServlet you can use Session Tracking to track the user state.  Session  is  required  if  you  are developing shopping cart application or in any e commerce‐  application.  7. Advantage of Cookies over URL rewriting: Sessions tracking using Cookies are more secure and fast. Session tracking using Cookies can also be used with other mechanism of Session Tracking like url rewriting. Cookies are stored at client side so some clients may disable cookies so we may not sure that the cookies  may  work  or  not.  In  url 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 32  

Page 33: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  rewriting requites large data transfer from and to the server. So, it leads to network traffic and access may be become slow.  8. Track a user session in Servlets: The interface HttpSession can be used to track the session in the Servlet. Following code can be used to create session object in the Servlet: HttpSession session = req.getSession(true);  9. Destroy the session in Servlet: You can call invalidate() method on the session object to destroy the session. e.g.session.invalidate();  Program:  import java.io.IOException; import java.io.PrintWriter; import java.util.Date; 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 sessiontracking extends HttpServlet  {          @Override     protected void doGet(HttpServletRequest request, HttpServletResponse response)             throws ServletException, IOException  {         response.setContentType("text/html;charset=UTF 8");‐          PrintWriter out = response.getWriter();         HttpSession session = request.getSession();         String heading;         Integer accessCount=new Integer(0);         if(session.isNew())         {             heading="welcome,newcomer";         }         else         {             heading="welcome,back";             Integer oldaccesscount=(Integer)session.getAttribute("accessCount");             if(oldaccesscount!=null)             {                 accessCount=new Integer(oldaccesscount.intValue()+1);             }         } 

session.putValue("accessCount",accessCount); out.println("<body bgcolor=\"#df5e6\">\n"); 

       out.println("<h1 align=\"center\">"+heading+"</h1>\n");         out.println("<table border=1 align=center>\n"+"<trbgcolor=\"ffad00\">\n"         +"<th>infotype</th><th>value</th>\n"+"<tr>\n"+"<td>ID\n"         +"<td>"+session.getId()+  "\n"+"<tr>\n"+"<td>creation time\n" 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 33  

Page 34: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T          +"<td>"+new Date(session.getCreationTime()) +"\n"+"<tr>\n"         +"<td>time of cost access\n"+"<td>"+new Date(session.getLastAccessedTime())         +"\n"+"<tr>\n"+"<td>Number of previous Accesses\n"         +"<td>"+accessCount+"\n"+"</body></html>" );               }     @Override     public  void  doPost(HttpServletRequest  req,HttpServletResponse  r es)    t hrows  S ervletException, IOException     {         doGet(req,res);     } } //Web.xml <web app‐  >     <servlet>         <servlet name>sessiontracking</servlet name>‐ ‐          <servlet class>sessiontracking</servlet class>‐ ‐      </servlet>     <servlet mapping>‐          <servlet name>sessiontracking</servlet name>‐ ‐          <url pattern>/sessiontracking</url pattern>‐ ‐      </servlet mapping>‐      <session config>‐          <session timeout>‐              30         </session timeout>‐      </session config>‐  </web app>‐                          

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 34  

Page 35: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Output: 

   After 2 time reloading the page  

                

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 35  

Page 36: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  8) a. Write a JAVA JSP Program to print 10 even and 10 odd number.      b. Write a JAVA JSP Program to implement verification of a particular user login and display a welcome page.  Procedure for Execution. Step 1: Create the new web application and give the name. Step 2: Right click on the web pages folder New select‐ ‐  jsp file. 

 Step 3. Code the jsp file, save and run it by right clicking. Step 4. Create another three jsp page named as forward1.jsp, forward2.jsp, login.jsp in the same project for question 8b. 

    

   

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 36  

Page 37: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  

  Brief Introduction   1. JavaServer Pages : JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web clients in a portable, secure and well defined‐  way. The JavaServer Pages specification extends the Java Servlet API to provide web application developers with a robust framework for creating dynamic web content on the server using HTML, and XML templates, and Java code, which is secure, fast, and independent of server platforms. JSP has been built on top of the Servlet API and utilizes Servlet semantics. JSP has become the preferred request handler and response mechanism. Although JSP technology is going to be a powerful successor to basic Servlets.  2. Servlets are powerful and sometimes they are a bit cumbersome when it comes to generating complex HTML. Most servlets contain a little code that handles application logic and a lot more code that handles output formatting. This can make it difficult to separate and reuse portions of the code when a different output format is needed. For these reasons, web application developers turn towards JSP as their preferred Servlet environment.   3. Life of the the jsp page is just same as the servlet life cycle. After get translated the jsp file is just like a servlet. The life cycle of the jsp page is given below:  jspInit(): This method is the called form the init() method. This method is of interface javax.servlet.jsp.JspPage. We can override this method. This method will be called once when the container loads the servlet for the first time.  _jspService(): This method is called from the servlet's service method. The container passes the Request and Response objects to this method. We can't override this method. It is a method of javax.servlet.jsp.HttpJspPage interface.  jspDestroy: This method is called by the servlet's destroy() method. We can override this method. It is a method of javax.servlet.jsp.JspPage interface.  1. JSP tags can be divided into 4 different types: i. Declarations This tag is used for defining the functions and variables to be used in the JSP. <%! Script code (allow multiple statements) %>  

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 37  

Page 38: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  ii. Scriplets In this tag we can insert any amount of valid java code and these codes are placed in _jspService method by the JSP engine. <% script code (allow multiple statements) %>  iii. Expressions We can use this tag to output any data on the generated page. These data are automatically converted to string and printed on the output stream. <%= script code (allow multiple statements) %>  iv. Directives In the directives we can import packages, define error handling pages or the session information of the JSP page. <%@directive attribute="value" %>  Where directive may be: 1. page: page is used to provide the information about it. Example: <%@page language="java" %> 2. include: include is used to include a file in the JSP page. Example: <%@ include file="/header.jsp" %> 3. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined our own tags). Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %> and attribute may be: 1. language="java" This tells the server that the page is using the java language. Current JSP specification supports only java language. Example: <%@page language="java" %>  2. extends="mypackage.myclass" This attribute is used when we want to extend any class. We can use comma(,) to import more than one packages. Example:  <%@page language="java" import="java.sql.*,mypackage.myclass" %>  3. session="true" When this value is true session data is available to the JSP page otherwise not. By default this value is true. Example: <%@page language="java" session="true" %>  4. errorPage="error.jsp" errorPage is used to handle the un handled‐  exceptions in the page. Example:  <%@page language="java" session="true" errorPage="error.jsp" %>  5. contentType="text/html;charset=ISO 8859 1"‐ ‐   Use this attribute to set the mime type and character set of the JSP. Example: <%@page language="java" session="true" contentType="text/html; charset=ISO88591" %>      

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 38  

Page 39: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Program:  //Oddeven.jsp <html>     <head>         <meta http equiv="Content Type"‐ ‐  content="text/html; charset=UTF 8">‐          <title>Script for even and odd numbers</title>     </head>     <body bgcolor="purple">         <h1>            10 Even and 10 Odd numbers         </h1>         <%             out.print("<br><br><b><u>10 Even numbers between 1 and 20</u></b><br>");             for(int i=1;i<=20;i++)            {                             if((i%2)==0)                                {                                   out.print("<b><br>"+i+"</b>");                                  }             }             out.print("<br><br><b><u>10 Odd numbers between 1 and 20</u></b><br>");             for(int i=1;i<=20;i++)            {                             if((i%2)!=0)                                {                                   out.print("<b><br>"+i+"</b>");                                  }             }                       %>     </body> </html>  //login.jsp  <html>     <head>         <meta http equiv="Content Type"‐ ‐  content="text/html; charset=UTF 8">‐          <title>JSP page</title>     </head>     <body>         <h1>Hello USERS!</h1>         <form method="post" action="forward1.jsp">             <p>please enter your name:                 <input type="text" name="Username">             </p>             <p>Enter the password:                 <input type="password" name="password">             </p>             <p><input type="submit" value="login"></p>         </form> 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 39  

Page 40: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T      </body> </html>  //forward1.jsp  <html>     <head>         <meta http equiv="Content Type"‐ ‐  content="text/html; charset=UTF 8">‐          <title>JSP Page</title>     </head>     <body>         <%          if(request.getParameter("Username").equals("ravikumara")&&   request.getParameter("password").equals("kumararavi"))         {            %>            <jsp:forward page="forward2.jsp"/>            <%          }          else          {          %>          <h3> Invalid userName OR Password</h3>          <%@include file="login.jsp" %>          <% } %>     </body> </html>  //forward2.jsp  <html>     <head>         <meta http equiv="Content Type"‐ ‐  content="text/html; charset=UTF 8">‐          <title>Hello</title>     </head>     <body bgcolor="#ff66f">         <h1>forward action test:Login successful</h1><br>         <h2> welcome to home page Mr/Miss:             <%=request.getParameter("Username")%></h2>     </body> </html>            

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 40  

Page 41: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Output: 

 

 

 

 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 41  

Page 42: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  9)  Write  a  JAVA  JSP  Program  to  get  student  information  through  a  HTML  and  create  a  JAVA Bean Class, populate Bean and display the same information through another JSP.  Procedure for Execution.  1. Create the new project, 

  2. Create StudentInput.html , FirstPage.jsp, SecondPage.jsp files under web pages folder. 

 3. Create the new package named Bean, under this Create the StudentBean.java. 

  

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 42  

Page 43: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  

 4. Right click on the StudentInput.html file to run.  Brief Introduction   Javabean: A Javabean is just a java class with the following requirements. i) It has a public no args‐  constructor ii) It has 'set' and 'get' methods for its properties. iii) It may have any general functions. iv) If required it must be Serializable. However, It is not necessary always that a bean should have properties. If there are no properties, we need not provide 'set' & 'get' methods either. ( Even the no args‐  constructor is provided by the compiler by default!) If the bean uses library classes alone, it is automatically serializable. In that case, it becomes just a class for encapsulating some functionality (ie) business logic.  Program:  //Prog9Input.html <html>      <head> <title>User login Page</title> </head>  <body bgcolor="silver"> <form action="FirstPage.jsp" method=Post>     <center><h1>Welcome to Student Information System</h1></center>     <h2>Please Enter Student Name</h2>     <input type="text" name="sname"><br><br>         Please Enter Student USN&nbsp;&nbsp;&nbsp;     <input type="text" name="usn"><br>         <br>Please Enter Student Marks1     <input type="text" name="m1"><br>         <br>Please Enter Student Marks2     <input type="text" name="m2"><br>         <br>Please Enter Student Marks3     <input type="text" name="m3"><br>         <br> <input type="submit" value="submit"> </form> </body> </html> 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 43  

Page 44: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  //Firstpage.jsp  <jsp:useBean id="StudentBean" scope="request" class="Bean.StudentBean"> <jsp:setProperty name="StudentBean" property="*"/> </jsp:useBean> <html> <body bgcolor="silver"><br> <jsp:forward page="SecondPage.jsp"/> </body></html>  //Secondpage.jsp  <jsp:useBean id="StudentBean" scope="request" class="Bean.StudentBean"> </jsp:useBean> <html> <body bgcolor="silver"> <h1><center> Student Information Retrieval</center></h1> <table border='10' width=300>     <tr><td><h2> Student Name:<jsp:getProperty name="StudentBean" property="sname"/></h2></td></tr> <tr><td><h2> USN:<jsp:getProperty name="StudentBean" property="usn"/></h2></td></tr> <tr><td><h2> Marks1:<jsp:getProperty name="StudentBean" property="m1"/></h2></td></tr> <tr><td><h2>Marks2:<jsp:getProperty name="StudentBean" property="m2"/></h2></td> <tr><td><h2> Marks3:<jsp:getProperty name="StudentBean" property="m3"/></h2></td></tr> </table> </body> </html>  //StudentBean.java  package Bean; import java.io.Serializable; public class StudentBean implements Serializable { 

private String sname; private String usn; private String m1; private String m2; private String m3; public void setsname(String sname) { this.sname=sname;  

} public void setusn(String usn)  

{  this.usn=usn;  

} public void setm1(String m1)  

{  this.m1=m1;  

} public void setm2(String m2)  

{  this.m2=m2;  

} public void setm3(String m3) 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 44  

Page 45: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  

 { this.m3=m3;  

} public String getsname()  

{  return sname;  

} public String getusn()  

{  return usn;  

} public String getm1()  

{  return m1;  

} public String getm2()  

{  return m2;  

} public String getm3()  

{  return m3; 

 } } //web.xml  <web app>‐      <servlet>         <servlet name>StudentBean</servlet name>‐ ‐          <servlet class>Bean.StudentBean</servlet class>‐ ‐      </servlet>     <servlet mapping>‐          <servlet name>StudentBean</servlet name>‐ ‐          <url pattern>/StudentBean</url pattern>‐ ‐      </servlet mapping>‐      <session config>‐          <session timeout>‐              30         </session timeout>‐      </session config>‐  </web app>‐             

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 45  

Page 46: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Output:  

   

                 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 46  

Page 47: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  10) Write a JAVA JSP Program which uses <jsp:plugin> tag to run a applet.  Procedure for Execution.  1. Create a New java web project and give the name as Prog10 

 2. Create the java source file under source package 3. Create the AppletJsp.jsp page under web pages folder.  

  

    

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 47  

Page 48: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  4. Compile the java source file and copy the java class file ButtonMoveApplet.class  file  under  web pages folder. 5. Select – Tools – plugins – Activate all installed plugins. 6. Run the file AppletJsp.jsp file.  Brief Introduction   1. Applet : Applet is java program that can be embedded into HTML pages. Java applets runs on the java enables web browsers such as mozila and internet explorer. Applet is designed to run remotely on the client browser, so there are some restrictions on it. Applet can't access system resources on the local computer. Applets are used to make the web site more dynamic and entertaining.  2. JSPApplet: To use applet in JSP page we can use <jsp:plugin>. By the use of <jsp:plugin> you can include an applet and JavaBean in your JSP page.  Syntax of <jsp:plugin> is : <jsp:plugin type="bean|applet" code="classFile" codebase="classFileDirectory" [ name="instancename" ] [ align="bottom|top|middle|left|right" ] [ height="displayPixels" ] [ width="displayPixels" ] [ jreversion="JREVersion" ] ................. > [<jsp:params> <jsp:param name="parametername" value="parametervalue" /> .......... </jsp:params>] [<jsp:fallback> text message .......... </jsp:fallback>] </jsp:plugin>  Attributes: 1. type: this is the type of object plugin will execute. You have to specify it either bean or applet since it has no default value. 2. code: name of the java class file. You must have to write ".class" with class file name. 3. codebase: absolute or relative path of directory where applet code file exists. 4. name: name of bean or applet instance. 5. align: position of applet or bean display on the browser. 6. height: as its name signifies, height of applet or bean display 7. width: as its name signifies, width of applet or bean display 8. jreversion: version of Java Runtime environment 9. <jsp:params>: name and parameters value passed to applet or bean. 10. <jsp:fallback>: a text message to be displayed if applet plugin cannot be started.    

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 48  

Page 49: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Program: //Applet.jsp  <html> <head> <title>Welcome JSP Applet‐  Page</title> </head> <body> <jsp:plugin type="applet" code="ButtonMoveApplet.class" width="400" height="400"> <jsp:fallback> <p>Unable to load applet</p> </jsp:fallback> </jsp:plugin> </body> </html>  //ButtonMoveApplet.java  import java.awt.*; import java.util.*; import java.applet.*; public class ButtonMoveApplet extends Applet  {     Button move;     Random r;     @Override     public void init()      {         setLayout(null);         move = new Button("Click me");         add(move);         move.reshape(10,10,70,30);         r = new Random();         setBackground(Color.red);         setForeground(Color.yellow);     } @Override public void paint(Graphics g) {     g.drawString("Welcome JSP Applet",100,100);‐  } @Override public boolean action(Event evt, Object whatAction)  {     if (!(evt.target instanceof Button))     return false;     String buttonLabel = (String)whatAction;     if ( buttonLabel == null ? "Click me" == null : buttonLabel.equals("Click me"))      {         move.reshape(Math.abs(r.nextInt())%(size().width 70),‐          Math.abs(r.nextInt())%(size().height 30),70,30);‐          repaint();  

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 49  

Page 50: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T      }     return true; }  }  //web.xml  <web app‐  >     <servlet>         <servlet name>ButtonMoveApplet</servlet name>‐ ‐          <servlet class>ButtonMoveApplet</servlet class>‐ ‐      </servlet>     <servlet mapping>‐          <servlet name>ButtonMoveApplet</servlet name>‐ ‐          <url pattern>/ButtonMoveApplet</url pattern>‐ ‐      </servlet mapping>‐      </web app>‐   Output: 

  

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                                P a g e  | 50  

Page 51: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  11) Write a JAVA JSP Program which implements nested tags and also uses TagSupport Class.  Procedure for Execution.  1. Select New Project  >‐  java web  >‐  web application  >‐  give the name as Program11  >‐  Next  >‐  select tomcat server >‐  next >finish‐  

  2. Create the newjsp.jsp page and edit the code. 

  3. Create the new nested.tld file under /WEB INF/tlds/‐  directory 

  

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 51  

Page 52: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  4. Create the TagHandler Class – NestLevel.java (i.e., java class file) under mypack package. 

  5. Compile the NestLevel.java file and finally 6. Right click on the newjsp.jsp file and click run.  Brief Introduction   JSP Custom Tags : • Provide a mechanism to a Web programmer to reuse and encapsulate complex recurring code in a JSP application. • Provide simplicity and reusability of Java code. • Enable you to perform various functions, such as: 1. Accessing all implicit variables of a JSP page, such as request, response, in, and out. 2. Modifying the response generated by a calling JSP page. 3. Initializing and instantiating a JavaBean component. Types of Custom Tags The various types of custom tags that you can develop in JSP are : • Empty tags: Refer to the custom tags that do not have any attribute or body. The following code snippet shows an empty custom tag: <td:welcome /> • Tags with attributes: Refer to custom tags for which you can define attributes to customize the behavior of the custom tag. The following code snippet shows a custom tag with an attribute color: <td: welcome color=?blue?></td:welcome> • Tags with a body: Refer to the custom tag within which you can define nested custom tags, scripting elements, actions, HTML text, and JSP directives. The following code snippet shows a custom tag that contains a JSP scripting element as its body: <td: welcome> <%=today_date%> </td:welcome> • Nested tags: Refer to the set of custom tags in which one custom tag encloses one or more custom tags. The following code snippet shows a nested custom tag: <td1:ifTag condition ?<%=eval>? > <td2:valueTrue> The expression evaluates to true </td2:valueTrue> </td1:ifTag>/font> 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 52  

Page 53: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Development of Custom Tag : To develop a custom tag, you need to perform following steps: • Include the Tag Library in a JSP page • Develop the Tag Library Descriptor (TLD) file • Develop a tag handler or class file(.java) • Deploy the application Tag Handler File : Build a class that implements the javax.servlet.jsp.tagext tag interface as follows. Compile it and place it under the /WEB INF/classes‐  directory (in the appropriate package structure).  Tag Library Descriptor (TLD) file : Now we need to describe the tag, so create a file called nested.tld and place it under the /WEB INF/tlds‐  directory.  Program:  //newjsp.jsp  <%@taglib uri="/WEB INF/tlds/nested.tld"‐  prefix="x"%> <x:nest> <x:nest> <x:nest/> </x:nest> </x:nest>  //nested.tld  <?xml version="1.0" encoding="UTF 8"?>‐  <taglib version="2.1"> <tlib version>1.0</tlib version>‐ ‐  <short name>nested</short name>‐ ‐  <uri>/WEB INF/tlds/nested</uri>‐  <tag> <name>nest</name> <tag class>mypack.NestLevel</tag class>‐ ‐  </tag> </taglib>  //NestLevelTag.java  package mypack; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.*; public class NestLevel extends TagSupport {     private int nestLevel=0; @Override public int doStartTag() throws JspException { 

nestLevel=0; Tag parent =getParent(); while(parent!=null) 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 53  

Page 54: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  

{ parent=parent.getParent(); nestLevel++; 

} try { 

pageContext.getOut().println("<br> Tag Nested Level: "+nestLevel); } catch(IOException e) { 

throw new JspException("IOException "+e.toString()); } return EVAL_BODY_INCLUDE; 

     } }  Output:  

                          

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 54  

Page 55: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  12) An EJB application that demonstrates Session Bean.  Procedure for Execution.  1.  Select  file  >‐   new  project  >‐   java  EE  >‐   Enterprise  Application  >‐   next  >‐   give  project  name  and project location  >‐  next  >‐  select glassFishServer  >‐  Select all EJBModule, WebApplicationModule and Client module  >‐  finish. 

 

 2. It will create ejb,war and app client‐  with project folder. 3. Right click on project ejb‐  and select new >‐  session bean  >‐  give  EJBName,  location,package  and session type & select both local and remote interface. It will create 3 *.javafiles like projectname.java, local.java and remote.java 

  

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 55  

Page 56: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  4. Right click inside projectname.java page  >‐  click insert code  >‐  add business method  >‐  and define business methods. 

  

  5. Create a servlet that accessed the stateless session beans. 6. Create a servlet by right clicking the war file and select  >‐  new servlet, give name and location  >‐  next  >‐  accept the servletname and URL pattern(s) fields and click finish.  

   

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 56  

Page 57: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  7. Add code to the servlet that accesses the stateless session bean. 8. Right click on the content of servlet session and select insert code then select call Enterprise Bean  >‐  Select sessionBean  >‐  click ok.  

  9. Right click on the  project name war‐   and click run. This opens the index.jsp page , input the values and  submit,  it  will  display  the  result.  Or  extend  the  projectname war‐   >webpages >index.jsp‐ ‐   right click on it and click run.  Brief Introduction   • Session Beans : Performs a task for a client; implements a web service • Stateless • Stateful. • At any given time, only one client has access to the bean instance. • The state of the bean is not persistent, existing only for a short period (perhaps a few hours). • The bean implements a web service.  Program:  //SessionBean.java  package mypack; import javax.ejb.Stateless; @Stateless public class SessionBean implements SessionBeanRemote, SessionBeanLocal {     public int multiplication(int p1, int p2)     {         return p1 * p2;     }        }    

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 57  

Page 58: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  //SessionBeanLocal.java  package mypack; import javax.ejb.Local; @Local public interface SessionBeanLocal  {     int multiplication(int p1, int p2); }  // SessionBeanRemote.java  package mypack; import javax.ejb.Remote; @Remote public interface SessionBeanRemote  {      }  //NewServlet.java  package mypack; import java.io.IOException; import java.io.PrintWriter; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class NewServlet extends HttpServlet  {     @EJB     private SessionBeanLocal sessionBean;     @Override     protected void doPost(HttpServletRequest request, HttpServletResponse response)     throws ServletException, IOException      {         int p1=Integer.parseInt(request.getParameter("n1"));         int p2=Integer.parseInt(request.getParameter("n2"));         response.setContentType("text/html;charset=UTF 8");‐          PrintWriter out = response.getWriter();         try {             out.println("<html>");             out.println("<head>");             out.println("<title>Servlet NewServlet</title>");               out.println("</head>");             out.println("<body>");             out.println("<h1>Multiplication is " +sessionBean.multiplication(p1,p2)+"</h1>");             out.println("</body>");             out.println("</html>");             }  

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 58  

Page 59: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T          finally         {             out.close();         }     }  }  //Index.jsp  <html>     <head>         <meta http equiv="Content Type"‐ ‐  content="text/html; charset=UTF 8">‐          <title>Multiplication of Two Numbers</title>     </head>     <body>         <form action="NewServlet" method="post">             <h1>Multiplication of two numbers,which call stateless business method</h1>             number 1:<input type="text" name="n1"><br><br>             number 2:<input type="text" name="n2"><br><br>             <input type="submit" value="Multiplication">         </form>     </body> </html>  Output:  

   

    

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 59  

Page 60: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  13) An EJB application that demonstrates Entity Bean.  Procedure for Execution.  1.  Select  –  New  Project  –  Java  EE  –  Enterprise  Application  >‐   give  project  name  as  Prog13 >‐   Then select Only EJB & Web application module  >‐  Click Finish. 

 2.  Select  Services  option  in  NetBeans  >‐   Databases  >‐   Java  DB >‐  Right click and start the server  >‐  Right Click on sample >‐  click connect 3. Look into jdbc://localhost:1527/Sample  >‐  Click App >‐  Right Click on Table >Create‐  New table and add columns to table. 

 

 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 60  

Page 61: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  4. Switch to project window  >‐  Right Click prog13 ejb‐   >‐  New >‐  Select Entity Classes from Database  >‐  Select Data Source as jdbc/sample  >‐  Select Empinfo  >‐  add  >‐  next 

 5. Give package name as mypack  >‐  next  >‐  Finish. It creates mapping between table and Entity bean and create Student.java class. 

  6. Right Click on prog13 ejb‐   >‐  New  >‐  Select  >‐  Session Bean for entity classes.... Select available entity  classes  >‐   Select  mypacks.Empinfo  >‐  Add  >‐  Next  >‐  Select local interface  >‐  Finish. It will creates AbstractFacade .java [Abstract class], StudentFacade.java [java class], StudentFacadeLocal.java interface. 

  

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 61  

Page 62: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  

 7. In EmpinfoFacade.java  >‐  Add the following code @Override     public void persist(Object obj)     {         em.persist(obj);     }     public void addsEmp(String eid,String ename)     {         Empinfo obj=new Empinfo();         obj.setEid(eid);         obj.setEname(ename);         persist(obj);     }   8. Right click on program13 war‐   >‐  new  >‐  Servlet  >‐  give the name as studEntity >give‐  package name mypack >next‐   >‐  select deployment descriptor  >‐  finish. 

   

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 62  

Page 63: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  9. The right click on code window  >‐  Select insert code  >‐  call enterprise bean  >‐  Select studentFacade >‐  ok. Observe the code appears inside the servlet as StudentFacadeLocal studentFacade. 

  10. Add the following code try {            empinfoFacade.addsEmp("e100", "ravi");             out.println("<html>");             out.println("<head>");             out.println("<title>Servlet NewServlet</title>");             out.println("</head>");             out.println("<body>");             out.println("<h1>Record inserted successfully" + "</h1>");             out.println("</body>");             out.println("</html>");          }  save it and leave the default additional doPost and doGet methods in the same page as it is. 11. Right click on the war file  >‐  properties  >‐  Select run  >‐  give Relative URL as the /ServletName  >‐  ok. 

 12. Right click on the war file of servlet file and click run.    

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 63  

Page 64: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Brief Introduction   • Entity beans are persistent, • Allow shared access, have primary keys, and can participate in relationships with other entity beans. • With beanmanaged persistence, the entity bean code that you write contains the calls that access the database. • If your bean has containermanaged persistence, the EJB container automatically generates the necessary database access calls. • The code that you write for the entity bean does not include these calls.  Program:  // AbstractFacade.java  package pack; import java.util.List; import javax.persistence.EntityManager; public abstract class AbstractFacade<T>  {     private Class<T> entityClass;     public AbstractFacade(Class<T> entityClass)      {         this.entityClass = entityClass;     }     protected abstract EntityManager getEntityManager();     public void create(T entity)      {         getEntityManager().persist(entity);     }     public void edit(T entity)      {         getEntityManager().merge(entity);     }     public void remove(T entity)      {         getEntityManager().remove(getEntityManager().merge(entity));     }     public T find(Object id)      {         return getEntityManager().find(entityClass, id);     }     public List<T> findAll()      {         javax.persistence.criteria.CriteriaQuery         cq=getEntityManager().getCriteriaBuilder().createQuery();         cq.select(cq.from(entityClass));         return getEntityManager().createQuery(cq).getResultList();     }     public List<T> findRange(int[] range)      {         javax.persistence.criteria.CriteriaQuery 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 64  

Page 65: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T          cq=getEntityManager().getCriteriaBuilder().createQuery();         cq.select(cq.from(entityClass));         javax.persistence.Query q = getEntityManager().createQuery(cq);         q.setMaxResults(range[1] ‐ range[0]);         q.setFirstResult(range[0]);         return q.getResultList();     }     public int count()      {         javax.persistence.criteria.CriteriaQuery         cq=getEntityManager().getCriteriaBuilder().createQuery();         javax.persistence.criteria.Root<T> rt = cq.from(entityClass);         cq.select(getEntityManager().getCriteriaBuilder().count(rt));         javax.persistence.Query q = getEntityManager().createQuery(cq);         return ((Long) q.getSingleResult()).intValue();     } }  // Empinfo.java  package pack; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; @Entity @Table(name = "EMPINFO") @NamedQueries({  @NamedQuery(name = "Empinfo.findAll", query = "SELECT e FROM Empinfo e")}) public class Empinfo implements Serializable  {     private static final long serialVersionUID = 1L;     @Id     @Basic(optional = false)     @Lob     @Column(name = "EID")     private String eid;     @Lob     @Column(name = "ENAME")     private String ename;     @Lob     @Column(name = "CONTACTNO")     private String contactno;     public Empinfo()     {    }     public Empinfo(String eid)  {         this.eid = eid; 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 65  

Page 66: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T      }     public String getEid()     {         return eid;     }     public void setEid(String eid)      {         this.eid = eid;     }     public String getEname()      {         return ename;     }     public void setEname(String ename)      {         this.ename = ename;     }     public String getContactno()      {         return contactno;     }     public void setContactno(String contactno)      {         this.contactno = contactno;     }     @Override     public int hashCode()      {         int hash = 0;         hash += (eid != null ? eid.hashCode() : 0);         return hash;     }     @Override     public boolean equals(Object object)     {             if (!(object instanceof Empinfo))            {             return false;           }          Empinfo other = (Empinfo) object;          if ((this.eid == null && other.eid != null) || (this.eid != null && !this.eid.equals(other.eid)))           {             return false;          }         return true;   }     @Override     public String toString()     {         return "mypack.Empinfo[eid=" + eid + "]";     } } 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 66  

Page 67: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  //EmpinfoFacade.java  package pack; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @Stateless public class EmpinfoFacade extends AbstractFacade<Empinfo> implements EmpinfoFacadeLocal {     @PersistenceContext(unitName = "Prog13 ejbPU")‐      private EntityManager em;   protected EntityManager getEntityManager()     {         return em;     }     public EmpinfoFacade()     {         super(Empinfo.class);     }     @Override     public void persist(Object obj)     {         em.persist(obj);     }     public void addsEmp(String eid,String ename)     {         Empinfo obj=new Empinfo();         obj.setEid(eid);         obj.setEname(ename);         persist(obj);     }    } // EmpinfoFacadeLocal.java  package pack; import java.util.List; import javax.ejb.Local; @Local public interface EmpinfoFacadeLocal {     void create(Empinfo empinfo);     void edit(Empinfo empinfo);     void remove(Empinfo empinfo);     Empinfo find(Object id);     List<Empinfo> findAll();     List<Empinfo> findRange(int[] range);     int count();     public void persist(java.lang.Object obj);     public void addsEmp(java.lang.String eid, java.lang.String ename); }   

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 67  

Page 68: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  //NewServlet.java  package pack; import java.io.IOException; import java.io.PrintWriter; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import pack.EmpinfoFacadeLocal; public class NewServlet extends HttpServlet  {     @EJB     private EmpinfoFacadeLocal empinfoFacade;     protected void processRequest(HttpServletRequest request, HttpServletResponse response)     throws ServletException, IOException  {         response.setContentType("text/html;charset=UTF 8");‐          PrintWriter out = response.getWriter();         try  {            empinfoFacade.addsEmp("e100", "ravi");             out.println("<html>");             out.println("<head>");             out.println("<title>Servlet NewServlet</title>");             out.println("</head>");             out.println("<body>");             out.println("<h1>Record inserted successfully" + "</h1>");             out.println("</body>");             out.println("</html>");          }  

finally  { 

              out.close();           }     } }              

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 68  

Page 69: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Output: 

                 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 69  

Page 70: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  14) An EJB application that demonstrates MDB.  Procedure for Execution.  Step1: Open the NetBeans IDE 6.9.1 switch to Services double click on the databaseÆ select Java DB Æright click on sampleÆ click connect Step2: Select Servers in that GlassFish server Start that. 

  Step3:Right click on the GlassFish Server and select View Admin Console 

  Step4:  Select  Resources  a nd  e xpand  i tÆClick  JMS  Resources  i n  t hat  a gain  C lick Connection Factories  Æ  t hen  c lick New  a nd  g ive  P ool  n ame  l ike jms/mypool  and  Resource  Type  is javax.jms.QueueConnectionFactory and description is mypool and click OK  

 Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 70  

Page 71: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Step5:Click  Destination  ResourcesÆ Click NewÆ  and  give  JNDI  Name  jms/destination, Physical Destination nameÆdestination and Resource TypeÆjavax.jms.Queue and Click OK 

  Step6: Select New project  >‐  JavaEE  >‐  Enterprise Application >‐  click next  >Prog14‐  and Set as Main project  >‐  next  >‐  finish. 

  Step7: Right click on the ÆNewÆMessage Driven Bean‐ ‐ Ægive EJB name ÆCallingmdbÆ package nameÆgoldÆServer DestinationÆjms/destinationÆFinish 

 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 71  

Page 72: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  Step8: Write the below code in Callingmdb file and by clicking on bubble select the appropriate action. public void onMessage(Message message)      {         try        {             System.out.println("My Name Is" + message.getStringProperty("name"));             System.out.println("My Usn Is" + message.getStringProperty("usn"));             System.out.println("The Sem is" + message.getIntProperty("sem"));         }         catch (JMSException ex)         {             Logger.getLogger(Callingmdb.class.getName()).log(Level.SEVERE, null, ex);         }     } 

  Step9: Right click on Prog14warÆNewÆ ServletÆgive class name CallingClient Æ package name Æsilver ÆClick Next and click the check box add information to deployment descriptor(web.xml) and Click Finish 

 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 72  

Page 73: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T   Step10: Right click in first try and catch block(CallingClient.java file) and select insert CodeÆSend JMS Message Æ select Server Destinations:jms/destinationÆConnection Factory:jms/mypool  Æ Click OK and Write the below code in the first try catch‐  block and Override it.         try             {             sendJMSMessageToDestination();             out.println("Your Message has been sent check it the log");             }          catch (JMSException ex)         {             Logger.getLogger(CallingClient.class.getName()).log(Level.SEVERE, null, ex);         }   

   Step11: Write the below code in the sendJMSMessageToDestination() method and Save all the Files. private void sendJMSMessageToDestination() throws JMSException     {         Connection connection = null;         Session session = null;         try {             connection = mypool.createConnection();             session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);             MessageProducer messageProducer = session.createProducer(destination);             Message ms=session.createMessage();             ms.setStringProperty("name","Ravikumara");             ms.setStringProperty("usn","1BY11MCA40");             ms.setIntProperty("sem", 4);             messageProducer.send(ms);         }    

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 73  

Page 74: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T   Brief Introduction   • A messagedriven bean is an enterprise bean that allows J2EE applications to process messages asynchronously. It acts as a JMS message listener, which is similar to an event listener except that it receives messages instead of events.  • The messages may be sent by any J2EE component an‐‐  application client, another enterprise bean, or a Web component or‐‐  by a JMS application or system that does not use J2EE technology.  • Message driven‐  beans currently process only JMS messages, but in the future they may be used to process other kinds of messages.  • A message driven bean’s instances retain no data or conversational state for a specific client, i.e., they are stateless.  • A message driven‐  bean has only a bean class i.e., unlike a session bean, the client’s don’t access message driven‐  beans through interfaces.  • They don’t have the remote or local interfaces that define client access.  • Java Message Service (JMS) is an API for java messaging clients. It provides two models, i. point to point‐ ‐  ii. Publish and subscribe. Program:  //Callingmdb.java package gold; 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; @MessageDriven(mappedName = "jms/destination", activationConfig =   {@ActivationConfigProperty(propertyName="acknowledgeMode",propertyValue="Auto acknowledge‐  "),@ActivationConfigProperty(propertyName="destinationType",propertyValue= "javax.jms.Queue")     }) public class Callingmdb implements MessageListener {     public Callingmdb()     {     }     @Override     public void onMessage(Message message)      {         try {             System.out.println("My Name Is" + message.getStringProperty("name"));             System.out.println("My Usn Is" + message.getStringProperty("usn"));             System.out.println("The Sem is" + message.getIntProperty("sem")); 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 74  

Page 75: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T          }         catch (JMSException ex)         {             Logger.getLogger(Callingmdb.class.getName()).log(Level.SEVERE, null, ex);         }     }      } //CallingClient.java  package silver; 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.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CallingClient extends HttpServlet {     @Resource(name = "jms/destination")     private Queue destination;     @Resource(name = "jms/mypool")     private ConnectionFactory mypool;     protected void processRequest(HttpServletRequest request, HttpServletResponse response)     throws ServletException, IOException     {         response.setContentType("text/html;charset=UTF 8");‐          PrintWriter out = response.getWriter();         try             {             sendJMSMessageToDestination();             out.println("Your Message has been sent check it the log");             }          catch (JMSException ex)         {             Logger.getLogger(CallingClient.class.getName()).log(Level.SEVERE, null, ex);         }         finally         {             out.close();         } 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 75  

Page 76: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T      }  private  Message  createJMSMessageForjmsDestination(Session  session,  Object  messageData)  throws JMSException      {         TextMessage tm = session.createTextMessage();         tm.setText(messageData.toString());         return tm;     }     private void sendJMSMessageToDestination() throws JMSException     {         Connection connection = null;         Session session = null;         try         {             connection = mypool.createConnection();             session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);             MessageProducer messageProducer = session.createProducer(destination);             Message ms=session.createMessage();             ms.setStringProperty("name","Ravikumara");             ms.setStringProperty("usn","1BY11MCA40");             ms.setIntProperty("sem", 4);             messageProducer.send(ms);         }          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();             }         }     } }          

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 76  

Page 77: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T   Output: Right Click on Prog14 war‐ ÆPropertiesÆRunÆRelative pathÆ/CallingClientÆ Ok  Right Click on Prog14 war‐  and Click Run. 

   

    

      

 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 77  

Page 78: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  

Viva Questions: 1. Draw a neat diagram for J2EE architecture 2. Define JDBC, & how many JDBC driver types? 3. List Data types supported by JDBC 4. Which package is used for JDBC program? 5. Define class.forName() method? 6. Write the JDBC Connection code in java? 7. Define Statement Object? 8. How many types of Statement Objects? 9. Define Statement, PreparedStatement and CallableStatement? 10. What do you mean by ResultSet? 11. Define execute(), executeQuery(), and executeUpdate() methods? 12. Define Meta Data in JDBC? 13. How to create index in JDBC program? 14. Write the example query for Existence Test, Membership Test, and Any Test? 15. How Servlets different from CGI? 16. Write the life cycle of Servlet? 17. Which package mandatory for Servlet program? 18. Give the example for deployment descriptor of Servlet? 19. What the HTTP header carries the information along with client request? 20. What is Status code represents? And Define 400, 401, 403, 404, 405, 415, 500, 501, 503, & 505? 21. Define cookie & its types? 22. Write example code for cookie? 23. Define Session? 24. What are different Tracking mechanisms? 25. Define JSP? 26. How JSP different from Servlet? 27. What are Standard JSP tags? 28. Write the example code for JSP include, import, sql, and custom tags? 29. Define Web Server, Application Server? 30. Define JavaBeans? 31. What are the two design patterns in JavaBeans? 32. Define Introspection? 33. Define Customizer? 34. Which package is mandatory for JavaBeans? 35. Write a snippet code to add colour as property to JavaBean? 36. Write the hierarchy of classes for JavaBeans? 37. Which package is mandatory for EJB? 38. Explain bound and constraint properties of JavaBeans? 39. Define EJB? 40. Write the architecture diagram of EJB? 41. Write the entity java bean deployment descriptor? 42. How many environment element of an EJB? 43. What is the Transaction attributes in EJB? 44. Define Session Java Bean? 45. What are the types of Session Beans? 46. Define Entity Java Bean? 47. What are the types of Entity Java Bean? 48. Define Message Driven Bean? 49. How Session Bean is different from Entity Bean and Message Driven‐  Bean? 50. Define the components of EJB jar file?  

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 78  

Page 79: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  51.Use of Class.forName 52.Use of Driver Manager.getconnection 53.Result set 54.Use of next ( ) method in result set 55.Prepared Statement 56.Explain i. Servlets Life Cycle (with diagram) ii. Servlets API 57.Explain  doGet,  doPost  types  in  Servlet,  write  a  program  to  implement  doGet  or  doPost  using servlets 58.Explain different types of JSP Tags 59.List the three kinds of EJB classes. 60. Explain the two important interfaces of EJB. 61. Explain the creation of Session Java Bean. 62. Explain the Entity Java Bean 63. Explain the creation of Message Driven‐  Bean. 64. List some of the applications of java beans. 65. Give an example to Implementing Event Handling with Adapter class 66. Explain the methods, rebind() and lookup() in Naming class? 67. How do you pass data (including JavaBeans) to a JSP from a servlet? 68. What is Servlet chaining? 69. What is the life cycle of a servlet? 70. What is the difference between doPost and doGet methods? 71. What are the steps involved for making a connection with a database or how do you connect to a database? 72. What are drivers available for database connections? 73. What are the three bean times? 74. What are the five features of a JavaBean? 75. What is a property? 76. What is the EventTargetDialog in the BeanBox? 77. Where do the jar files for beans go in the BeanBox? 78. How do we compile and execute a Java class that resides in a package? 79. What goes in a manifest file for a JavaBean? 80. What is the advantage of denormalization? 81. Is the JDBC ODBC‐  Bridge multi threaded?‐  82. What is the fastest type of JDBC driver? 83. What are the different JDB drivers available? 84. What is Connection pooling? 85. What is Connection? 86. What is JDBC? 87. What are the steps required to execute a query in JDBC? 88. What is JDBC Driver ? 89. What is the servlet? 90. What are the JSP atrributes? 91. What is the need of super.init(config) in servlets? 92. How to know whether we have to use jsp or servlet in our project? 93. Can we call destroy() method on servlets from service method? 94. What is the Servlet Interface? 95. What is the difference between GenericServlet and HttpServlet? 96. How we can check in particular page the session will be alive or not? 97. What is the importance of deplo ment d scriptor in servlet? y e98.  When  we  increase  the  buffer  size  in  our  project  using  page  directive  attribute  ‘buffer’  what changes we observe? 99. What is the difference between ServetConfig and ServletContext..? 

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 79  

Page 80: J2EE Lab Manual 2013

J2EE LABORATORY                                                                                                               B M S I T  100. When a servlet accepts a call from a client, it receives two objects. What are they? 101. What are the differences between GET and POST service methods? 102. In which conditions we have to use the ServletContext? 103. What methods will be called in which order?((i.e)service(),doget(),dopost())  

Prepared By: RAVIKUMARA M M [1BY11MCA40]                                                                                               P a g e  | 80