You are on page 1of 63

MASTER OF COMPUTER APPLICATIONS

IV SEMESTER 10MCA46 Scheme J2EE Laboratory

Compiled by Harish G.M. and Manju G

R.V.College of Engineering

Dept. of MCA

CONTENTS
SL. No.
1 VTU List of programs

Description

Page No.
4

Introduction to J2EE

6
3 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).

Write a JAVA Servlet Program to implement a dynamic HTML using Servlet (user name and password 14 should be accepted using HTML and displayed using a Servlet).

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).

17 19

Write a JAVA Servlet Program to implement RequestDispatcher object (use include() and forward() methods).

Write a JAVA Servlet Program to implement and demonstrate get() and Post methods(Using HTTP Servlet Class).

22

Write a JAVA Servlet Program to implement sendRedirect() method(using HTTP Servlet Class).

25 27

Write a JAVA Servlet Program to implement sessions (Using HTTP

Session Interface).

10

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.

30

R.V.College of Engineering

Dept. of MCA

11

Write a JAVA JSP Program to get student information through a HTML and create a JAVA Bean Class, 34 populate Bean and display the same information through another JSP.

12

Write a JSP Program which uses <jsp:plugin> tag to run a applet.

37

13

Write a JSP Program which implements nested tags and also uses TagSupport Class.

39

14

An EJB application that demonstrates Session Bean.

42

15

An EJB application that demonstrates Entity Bean.

48

16

An EJB application that demonstrates MDB.

54

17

Viva questions and extra programs

60

18

J2EE Lab Cycles

62

R.V.College of Engineering

Dept. of MCA

R.V.College of Engineering

Dept. of MCA

Dos and Donts in the Laboratory

DO .. Come prepared to the Lab. Submit your Records to the Lecturer and sign in the Log Book on entering the Lab. Follow the Lab cycles as instructed by the Department. Violating the same will result in deduction of marks. Use the same login (if any) assigned to you. Put the chairs back to its position before you leave. Backlog exercises to be executed after completing regular exercises. Keep your premises clean. DONT .. Move around in the lab during the lab session. Tamper System Files or Try to access the Server. Write Data Sheets or Records in the Lab Change the system assigned to you without the notice of the Lab Staff. Write on the table or mouse pads. Teaching your friends during lab sessions.

R.V.College of Engineering

Dept. of MCA

Introduction to J2EE
J2EE (Java 2 Platform, Enterprise Edition) is a Java platform designed for the mainframe-scale computing typical of large enterprises. Sun Microsystems (together with industry partners such as IBM) designed J2EE to simplify application development in a thin client tiered environment. J2EE simplifies application development and decreases the need for programming and programmer training by creating standardized, reusable modular components and by enabling the tier to handle many aspects of programming automatically. J2EE includes many components of the Java 2 Platform, Standard Edition (J2SE):

The Java Development Kit (JDK) is included as the core language package. Write Once Run Anywhere technology is included to ensure portability. Support is provided for Common Object Request Broker Architecture (CORBA), a predecessor of Enterprise JavaBeans (EJB), so that Java objects can communicate with CORBA objects both locally and over a network through its interface broker. Java Database Connectivity 2.0 (JDBC), the Java equivalent to Open Database Connectivity (ODBC), is included as the standard interface for Java databases. A security model is included to protect data both locally and in Web-based applications.

J2EE also includes a number of components added to the J2SE model, such as the following:

Full support is included for Enterprise JavaBeans. EJB is a server-based technology for the delivery of program components in an enterprise environment. It supports the Extensible Markup Language (XML) and has enhanced deployment and security features. The Java servlet API (application programming interface) enhances consistency for developers without requiring a graphical user interface (GUI). Java Server Pages (JSP) is the Java equivalent to Microsoft's Active Server Pages (ASP) and is used for dynamic Web-enabled data access and manipulation.

The J2EE architecture consists of four major elements:


The J2EE Application Programming Model is the standard programming model used to facilitate the development of multi-tier, thin client applications. The J2EE Platform includes necessary policies and APIs such as the Java servlets and Java Message Service (JMS). The J2EE Compatibility Test Suite ensures that J2EE products are compatible with the platform standards. The J2EE Reference Implementation explains J2EE capabilities and provides its operational definition.

R.V.College of Engineering

Dept. of MCA

Solutions

R.V.College of Engineering

Dept. of MCA

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). JDBC drivers are divided into four types or levels. Each type defines a JDBC driver implementation with increasingly higher levels of platform independence, performance, and deployment administration. The four types are: Type 1: JDBC-ODBC Bridge Type 2: Native-API/partly Java driver Type 3: Net-protocol/all-Java driver Type 4: Native-protocol/all-Java driver

In this program we have used Type 4 driver(MySqlconnector 5.1 for MySql Server) The native-protocol/all-Java driver (JDBC driver type 4) converts JDBC calls into the vendor-specific database management system (DBMS) protocol so that client applications can communicate directly with the database server. Level 4 drivers are completely implemented in Java to achieve platform independence and eliminate deployment administration issues. The PreparedStatement object represents the precompiled SQL statement. Whenever, the SQL statement is precompiled then it stored in the PreparedStatement object which executes the statement many times and it reduces the time duration of execution. The PreparedStatement uses the '?' with SQL statement that provides the facility for setting an appropriate conditions in it Program: import java.sql.*; import java.util.Scanner; public class student { Connection con; public void insert(String name,String usn,String pass) { try { connectdb(); PreparedStatement pre = con.prepareStatement("insert into student(name,usn,result) values(?,?,?)"); pre.setString(1,name); pre.setString(2,usn); pre.setString(3,pass); int rs =pre.executeUpdate(); if(rs==1) { System.out.println("RESULT UPDATED"); con.close();

R.V.College of Engineering } else {

Dept. of MCA

System.out.println("UPDATION FAILED"); con.close(); } } catch(Exception e) { e.printStackTrace(); } } public void select (String usn) { try { connectdb(); PreparedStatement pre = con.prepareStatement("select * from student where usn =?"); pre.setString(1,usn); ResultSet rs = pre.executeQuery(); if(rs.next()) { System.out.println("Name= "+rs.getString(1)); System.out.println("USN= "+rs.getString(2)); System.out.println("Result= "+rs.getString(3)); con.close(); } else { System.out.println("SELECTION FAILED"); con.close(); } } catch(Exception e) { e.printStackTrace(); } } public void viewall () { try {

R.V.College of Engineering

Dept. of MCA

connectdb(); PreparedStatement pre = con.prepareStatement("select * from student"); ResultSet rs = pre.executeQuery(); while(rs.next()) { System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)); } con.close(); } catch(Exception e) { e.printStackTrace(); } } public void delete (String usn) { try { connectdb(); PreparedStatement pre = con.prepareStatement("delete from student where usn =?"); pre.setString(1,usn); int rs = pre.executeUpdate(); if(rs==1) { System.out.println("RECORD UPDATED"); con.close(); } else { System.out.println("UPDATION FAILED"); con.close(); } } catch(Exception e) { e.printStackTrace(); } } public void update(String name,String usn,String pass) {

10

R.V.College of Engineering

Dept. of MCA

try { connectdb(); PreparedStatement pre = con.prepareStatement("update student set name = ?,result = ? where usn = ? "); pre.setString(1,name); pre.setString(2,pass); pre.setString(3,usn); int rs =pre.executeUpdate(); if(rs==1) { System.out.println("RESULT UPDATED"); con.close(); } else { System.out.println("UPDATION FAILED"); con.close(); } } catch(Exception e) { e.printStackTrace(); } } public void connectdb() { try { Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc","root","harish"); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { student sdb = new student(); String n,p,u; while(true) { System.out.println("1 to insert data");

11

R.V.College of Engineering

Dept. of MCA

System.out.println("2 to select data"); System.out.println("3 to update data"); System.out.println("4 to delete data"); System.out.println("5 to view all"); Scanner s = new Scanner(System.in); switch(s.nextInt()) { case 1: System.out.println("Enter name"); n=s.next(); System.out.println("Enter USN"); u=s.next(); System.out.println("pass/fail"); p=s.next(); sdb.insert(n,u,p); break; case 2: System.out.println("Enter USN to search"); u=s.next(); sdb.select(u); break; case 3: System.out.println("Enter name"); n=s.next(); System.out.println("Enter USN"); u=s.next(); System.out.println("pass/fail"); p=s.next(); sdb.update(n,u,p); break; case 4: System.out.println("Enter USN to Delete"); u=s.next(); sdb.delete(u); break; case 5: System.out.println("*************FILE CONTENT******************"); sdb.viewall(); break; default: System.exit(0); } } }

12

R.V.College of Engineering } Test Data:

Dept. of MCA

set CLASSPATH for mysqlconnector.jar file in .bashrc file. harish@harish-laptop:~/lab$ javac student.java harish@harish-laptop:~/lab$ java student 1 to insert data 2 to select data 3 to update data 4 to delete data 5 to view all

13

R.V.College of Engineering

Dept. of MCA

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). A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes. The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods. The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps. 1. If an instance of the servlet does not exist, the Web container a. Loads the servlet class. b. Creates an instance of the servlet class. c. Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet. 2. Invokes the service method, passing a request and response object. Service methods are discussed in the section Writing Service Methods. If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy method. Finalization is discussed in Finalizing a Servlet. Program: //post.java import java.io.*; import java.util.*; import javax.servlet.*; public class post extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException,IOException { PrintWriter pw = response.getWriter(); Enumeration e = request.getParameterNames(); while(e.hasMoreElements() ) { String pname=(String)e.nextElement();

14

R.V.College of Engineering pw.print(pname);

Dept. of MCA

String pvalue=request.getParameter(pname); pw.println(pvalue); } pw.close(); } } post.html <html> <body> <center> <form name="form1" method ="post" action="http://localhost:8080/examples/servlets/servlet/post"> <table> <tr> <td><B>Username</td> <td><input type=textbox name="username"></td> </tr> <tr> <td><B>Password</td> <td><input type=textbox name="password"></td> </tr> </table> <input type=submit value="submit"> </form> </body> </html> Test Data: assuming tomcat6 + sun-6-jdk is installed properly if installed from synaptic package manager tocat6 is installed as below /usr/share/tomcat6 /usr/share/tomcat6-examples 15

R.V.College of Engineering

Dept. of MCA

in tomcat6-examples/examples/WEB-INF/classes$ place the <post.java> and <post.class> in the WEB-INF directory place the post.html file in /usr/share/tomcat6-examples/examples/servlets directory assuming Tomcat is running on port 8080 request as below http://localhost:8080/examples/servlets/servlet/post u will get output as password username harish hari

16

R.V.College of Engineering

Dept. of MCA

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). The doGet and doPost methods are called in response to an HTTP GET and an HTTP POST respectively which are submission methods used in an HTML FORM. On an HTTP GET the form data is part of the URL whereas on an HTTP POST the form data appears in the message body. You should always have one method call the other in your servlet as processing the form data in a servlet is consistent regardless of the submission method. doGet(): The doGet() method of the Servlet is automatically called when a client invokes a Servlet by clicking on a link. The doGet() method is called by the service() method when it receives a GET request. This method is called when a user clicks on a link, enters a URL into the browsers address bar, or submits an HTML form with METHOD=GET specified in the FORM tag. doPost(): The doPost() method of the Servlet is invoked when the browser sends an HTTP request using the post() method. For example, if a user is going to call a Servlet by clicking on a link, the doGet() method is used. If the user is filling out a form and sends the data to the server, the doPost() method is used. The doGet() and doPost() methods are part of the HTTP protocol. Both methods are called by the default (superclass) implementation of service in the HttpServlet base class. Program: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class FileDownloads extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException { PrintWriter out = res.getWriter(); out.println("<html><head>Download a File Example</head></html>"); out.println("<pre><a href=DS.java> click here to download DS.java file </a><br> "); out.println("<pre><a href=SS.java> click here to download SS.java file </a> "); out.println("<pre><a href=askmeabtfreesoftware.png> click here to download askmeabtfreesoftware.png file </a><br> "); out.println("<pre><a href=fsfhead.pdf> click here to download fsfhead.pdf file </a> "); out.println("<pre><a href=pigeon.jpg> click here to download pigeon.jpg file </a><br> "); out.println("<pre><a href=stallman.jpg> click here to download stallman.jpg file </a> "); } } the hyper links that are given in the above program are pointing to those files that are present in the main directory that is here /usr/share/tomcat6-examples/examples make entries in the web.xml file

17

R.V.College of Engineering

Dept. of MCA

<servlet> <servlet-ame>FileDownloads</servlet-name> <servlet-class>FileDownloads</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileDownloads</servlet-name> <url-pattern>/FileDownloads</url-pattern> </servlet-mapping> Test Data: When tomcat is running request for the servlet at http://localhost:8080/examples for FileDownloads i.e http://localhost:8080/examples/FileDownloads you will get links to several files on the page which when clicked opens corresponding files in the browser if the supportting plugin is present else external application will be used like evince for pdf files (in my case as i had not installed pdf plugins for browser) .

18

R.V.College of Engineering

Dept. of MCA

4. Write a JAVA Servlet Program to implement RequestDispatcher object (use include() and forward() methods). RequestDispatcher Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name. This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource.

forward
void forward(ServletRequest request, ServletResponse response) throws ServletException,
IOException

Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. This method allows one servlet to do preliminary processing of a request and another resource to generate the response. For a RequestDispatcher obtained via getRequestDispatcher(), the ServletRequest object has its path elements and parameters adjusted to match the path of the target resource. include void include(ServletRequest request, ServletResponse response) throws ServletException,
IOException

Includes the content of a resource (servlet, JSP page, HTML file) in the response. In essence, this method enables programmatic server-side includes. The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored. Program: import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

19

R.V.College of Engineering

Dept. of MCA

public class MultipleInclude extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Multiple Includes</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello from Level 1</h1>"); out.println("This text is displayed at Level 1."); RequestDispatcher dispatcher = request.getRequestDispatcher("/ Level4"); dispatcher.include(request, response); out.println("</body>"); out.println("</html>"); out.close(); } } <!-- web.xml --> <servlet> <servlet-name>MultipleInclude</servlet-name> <servlet-class>MultipleInclude</servlet-class> </servlet> <servlet-mapping> <servlet-name>MultipleInclude</servlet-name> <url-pattern>/MultipleInclude</url-pattern> </servlet-mapping> <servlet> <servlet-name>Level4</servlet-name> <servlet-class>Level4</servlet-class> 20

R.V.College of Engineering </servlet> <servlet-mapping>

Dept. of MCA

<servlet-name>Level4</servlet-name> <url-pattern>/Level4</url-pattern> </servlet-mapping> // here is another servlet import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Level4 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { java.io.PrintWriter out = response.getWriter(); out.println("<h4>Hello from another doGet</h4>"); out.println("Hello from another doGet."); } } Test Data: http://localhost:8080/examples/MultipleInclude Hello from Level 1 This text is displayed at Level 1. Hello from another doGet Hello from another doGet. http://localhost:8080/examples/Level4 Hello from another doGet Hello from another doGet. dispatcher.include(request, response); so MultipleInclude collects response from the Level4

21

R.V.College of Engineering

Dept. of MCA

5.

Write a JAVA Servlet Program to implement and demonstrate get() and Post methods(Using HTTP Servlet Class).

The doGet and doPost methods are called in response to an HTTP GET and an HTTP POST respectively which are submission methods used in an HTML FORM. On an HTTP GET the form data is part of the URL whereas on an HTTP POST the form data appears in the message body. You should always have one method call the other in your servlet as processing the form data in a servlet is consistent regardless of the submission method. doGet(): The doGet() method of the Servlet is automatically called when a client invokes a Servlet by clicking on a link. The doGet() method is called by the service() method when it receives a GET request. This method is called when a user clicks on a link, enters a URL into the browsers address bar, or submits an HTML form with METHOD=GET specified in the FORM tag. doPost(): The doPost() method of the Servlet is invoked when the browser sends an HTTP request using the post() method. For example, if a user is going to call a Servlet by clicking on a link, the doGet() method is used. If the user is filling out a form and sends the data to the server, the doPost() method is used. The doGet() and doPost() methods are part of the HTTP protocol. Both methods are called by the default (superclass) implementation of service in the HttpServlet base class. Program: <html> <body> <center> <form name="form1" method=post action="http://localhost:8080/examples/servlets/servlet/colorpost" > <B>color:</B> <select name="color"size="1"> <option value="red">red</option> <option value="green">green</option> <option value="blue">blue</option> </select> <br><br> <input type=submit value="submit"> </form> </body> </html> import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class colorpost extends HttpServlet {

22

R.V.College of Engineering

Dept. of MCA

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { String color=request.getParameter("color"); response.setContentType("text/html"); PrintWriter pw=response.getWriter(); pw.println("the selected color is:"); pw.println(color); pw.close(); } } Test Data: after appropriate entries in file:///usr/share/tomcat6examples/examples/servlets/colorpost.html while request is done http://localhost:8080/examples/servlets/servlet/colorpost respose will have this on addressbar and out put is the selected color is: green if green was selected from the options. -------------configuration entries have to be made in web.xml as done in previous example -------------using GET import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class color extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { String color=request.getParameter("color"); response.setContentType("text/html"); PrintWriter pw=response.getWriter(); pw.println("the selected color is:"); pw.println(color); pw.close(); } } <html>

23

R.V.College of Engineering

Dept. of MCA

<body> <center> <form name="form1" action="http://localhost:8080/examples/servlets/servlet/color"> <B>color:</B> <select name="color"size="1"> <option value="red">red</option> <option value="green">green</option> <option value="blue">blue</option> </select> <br><br> <input type=submit value="submit"> </form> </body> </html> Test Data: http://localhost:8080/examples/servlets/servlet/color?color=red http://localhost:8080/examples/servlets/servlet/color?color=black ( manually on the address bar whatever it is given then the servlet will respond accordingly ,othersie also color.html will give a chance to see the effect .

24

R.V.College of Engineering

Dept. of MCA

6. Write a JAVA Servlet Program to implement sendRedirect() method(using HTTP Servlet Class). sendRedirect() method is a method of HttpServletResponse interface. When a client sends a request for a particular page to a server and server sees that this request is can't be performed by this page, then it sends a error code to the browser specifying that the request can't be performed by this page. Along with the error code it also gives the address of the page which will be able to perform the request of the client. In sendRedirect() the object of request will be generated again with the location of page which will perform the request of the client. Program: //DS.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class DS extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException { PrintWriter out = res.getWriter(); out.println("<html><head>SendRedirect() Example</head></html>"); out.println("<body><center><font color=red size = 34>MyWeb </ font>"); out.println("<pre><a href=SS>Search</a> <a href=DS>greetings</a> </pre>"); out.println("<table border = 1, width = 100 >"); out.println("<tr><th>SNO</th><th>B.name</th><th>Quality</th></tr>" ); out.println("<tr><td>1</td><td>J2SE</td><td>10</td></tr>"); out.println("<tr><td>2</td><td>J2EE</td><td>10</td></tr>"); out.println("</table></center></body></body>"); } } //SS.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class SS extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException { res.sendRedirect("http://localhost:8080/examples/jsp/index.html" 25

R.V.College of Engineering ); } } Test Data:

Dept. of MCA

harish@harish-laptop:~/home/rvcemca/Documents/java/lab-4sem/servlets javac -cp /home/rvcemca/netbeans-6.5/ide10/modules/ext/mysql-connector-java-5.1.6bin.jar DD.java javac -cp /home/rvcemca/netbeans-6.5/ide10/modules/ext/mysql-connector-java-5.1.6bin.jar SS.java place the DD.java,DD.class,SS.java,SS.class files in the directory /usr/share/tomcat6-examples/examples/WEB-INF/classes from the browser http://localhost:8080/examples/DS you will reach a page there click on two links provided named search and greetings and Search will take you to http://localhost:8080/examples/jsp/index.html and greetings will redirect to the same page where you were there.

26

R.V.College of Engineering

Dept. of MCA

7. Write a JAVA Servlet Program to implement sessions (Using HTTP Session Interface). The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. A session usually corresponds to one user, who may visit a site many times. The server can maintain a session in many ways such as using cookies or rewriting URLs. This interface allows servlets to View and manipulate information about a session, such as the session identifier, creation time, and last accessed time Bind objects to sessions, allowing user information to persist across multiple user connections Methods Object getAttribute(String name)Returns the object bound with the specified name in this session, or null if no object is bound under the name. Enumeration getAttributeNames() Returns an Enumeration of String objects containing the names of all the objects bound to this session. long getCreationTime() Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. String getId() Returns a string containing the unique identifier assigned to this session. long getLastAccessedTime() Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container received the request. int getMaxInactiveInterval()Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. ServletContext getServletContext() Returns the ServletContext to which this session belongs. HttpSessionContext getSessionContext() Deprecated. As of Version 2.1, this method is deprecated and has no replacement. It will be removed in a future version of the Java Servlet API. isNew() Returns true if the client does not yet know about the session or if the client chooses not to join the session. void setAttribute(String name, Object value) Binds an object to this session, using the name specified. void setMaxInactiveInterval(int interval) Specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

27

R.V.College of Engineering Program: import java.io.PrintWriter; import java.io.IOException; import java.util.Date;

Dept. of MCA

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 SessionTracker extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); HttpSession session = req.getSession(true); Integer count = (Integer) session.getAttribute("count"); if (count == null) { count = new Integer(1);} else {count = new Integer(count.intValue() + 1); } session.setAttribute("count", count); out.println("<html><head><title>SessionSnoop</title></head>"); out.println("<body><h1>Session Details</h1>"); out.println("You've visited this page " + count + ((count.intValue()== 1) ? " time." : " times.") + "<br/>"); out.println("<h3>Details of this session:</h3>"); out.println("Session id: " + session.getId() + "<br/>"); out.println("New session: " + session.isNew() + "<br/>"); out.println("Timeout: " + session.getMaxInactiveInterval() + "<br/>"); out.println("Creation time: " + new Date(session.getCreationTime()) + "<br/>"); out.println("Last access time: " + new Date(session.getLastAccessedTime()) + "<br/>"); out.println("</body></html>"); 28

R.V.College of Engineering } } Test Data:

Dept. of MCA

http://localhost:8080/examples/SessionTracker refresh the page you should see that the counter will be incremented and will show the number of times the page is visited .

29

R.V.College of Engineering

Dept. of MCA

8 a. Write a JAVA JSP Program to print 10 even and 10 odd number. In JSP tags can be devided into 4 different types. These are: 1. Directives In the directives we can import packages, define error handling pages or the session information of the JSP page. <%@ page optional attribute ... %> 2. Declarations This tag is used for defining the functions and variables to be used in the JSP. <%! %> 3. 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. <% %> 4. 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. <%= %> Program: EvenOdd.jsp <html> <head> <title>Scriptlet for Even odd nos print</title> </head> <body> <h1>10 Even and 10 odd numbers</h1> <% out.print("<b>10 Even numbers starting from 1 are</><br>"); for (int i=1;i <= 20; i++){ if(i%2==0 ) { out.print("<br><b> " + i + "</b>"); } } out.print("<br><br><b> 10 Odd Nos starting from 1are </b><br>"); for (int i=1;i <= 20; i++){ if(i%2!=0 ) { out.print("<br><b> " + i + "</b>"); } } 30

R.V.College of Engineering %> </body> </html> Test Data:

Dept. of MCA

copy the EvenOdd.jsp file to /usr/share/tomcat6-examples/examples/jsp directory , and then from the browser give the following request http://localhost:8080/examples/jsp/EvenOdd.jsp you will see the output as 10 Even and 10 odd numbers ( The out put will be not as below, the numbers will be displayed one below the other , for simplicity i have placed the numbers one beside the other with a tab space) 10 Even numbers starting from 1 are 2 4 6 8 10 12 14 16 18 20 10 Odd Numbers starting from 1 are 1 3 5 7 9 11 13 15 17 19

31

R.V.College of Engineering

Dept. of MCA

8 b. Write a JAVA JSP Program to implement verification of a particular user login and display a welcome page. <jsp:include> : to include pages at request time , JSP content cannot affect main page: only output of included JSP page is used <%@include> : (the include directive) to include files at page translation time, To reuse JSP content in multiple pages, where JSP content affects main page RequestDispatcher .forward/include : Is used when we want to forward request from server to server there is no client interaction. response.sendRedirect() : In this case client is involved, first request is forwarded to client and then new request is generated from client side. In this case Header value is set by server to tell the client browser to generate new request. Program: indexforward.html <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="forward.jsp"> <p>please enter your username: <input type="text" name="username"> <br>and password: <input type="password" name="password"> </p> <p><input type="submit" value="login"></p> </form> </body> </html> forward.jsp <% if (request.getParameter("username").equals("Richard")){ if(request.getParameter("password").equals("MStallman")) { %> <jsp:forward page="forward2.jsp" /> <% } %> <% }else { %> <%@ include file="indexforward.html" %> <% } %> forward2.jsp <html>

32

R.V.College of Engineering

Dept. of MCA

<head> <title></title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> </head> <body> <h1>Forward action test :Login Successful</h1> <%= request.getParameter("username") %> </body> </html> Test Data: Save all the files in a directory ( i have used 13b) and then copy that directory to /usr/share/tomcat6-examples/examples/jsp directory, Start tomcat server, request as below http://localhost:8080/examples/jsp/13b/indexforward.html on successfull login from the jsp file below http://localhost:8080/examples/jsp/13b/forward.jsp you will get a welcome message with the username .

33

R.V.College of Engineering

Dept. of MCA

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. A Javabean is just a java class with the following requirements. It has a public no-args constructor It has 'set' and 'get' methods for its properties. It may have any general functions. 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. Such a bean , may or may not have a visual representation Java Beans are reusable components. They are used to separate Business logic from the Presentation logic. Internally, a bean is just an instance of a class. JSP?s provide three basic tags for working with Beans. <jsp:useBean id=?bean name? class=?bean class? scope = ?page | request | session | application ?/> bean name = the name that refers to the bean. Bean class = name of the java class that defines the bean. <jsp:setProperty name = ?id? property = ?someProperty? value = ?someValue? /> id = the name of the bean as specified in the useBean tag. property = name of the property to be passed to the bean. value = value of that particular property . Program: package beans; public class Student { public String name; public int usn; public String deparment; public void setname(String e) {name = e;} 34

R.V.College of Engineering public String getname() {return name;} public void setusn(int u) {usn=u;} public String getusn() {return usn;} public void setdepartment(String d) {department = d;} public String getdepartment() {return department;} } Test Data:

Dept. of MCA

Note: Before compiling create a directory called beans in /usr/share/tomcat6-examples/examples/WEB-INF/classes so that after compilation the Student.class file has to place there StudInfo.html <html> <head><title> employee information </title></head> <body> <form action ="first.jsp" method = "post"> USN : <input type = "text" name = "usn"/><br> Name : <input type = "text" name ="name"/><br> Department: <input type = "text" name ="department"/><br> <input type ="submit" value ="show"/> </form> </body> </html> first.jsp <html> <body> <jsp:useBean id=stu scope="request" class="beans.Student"/> <jsp:setProperty name="stu" property="*"/> 35

R.V.College of Engineering <jsp:forward page="display.jsp"/> </body> </html>

Dept. of MCA

display.jsp <html> <body> <jsp:useBean id="stu" scope="request" class="beans.Student"/> Emp Name <jsp:getProperty name="stu" property="name"/><br> Emp USN <jsp:getProperty name="stu" property="usn"/><br> Emp Department <%out.print(stu.getdepartment());%> </body> </html> Test Data: after copyting the Employee.class file in /usr/share/tomcat6-examples/examples/WEB-INF/classes/beans/ directory place the rest of the files (EmpInfo.html,first.jsp and display.jsp) in the directory /usr/share/tomcat6-xamples/examples/jsp then if tomcat is running access the file http://localhost:8080/examples/jsp/Studentinfo.html you will be propmpted to enter the details of Student after clicking on submit button you will see the ouput as Name a USN 1 Department MCA http://localhost:8080/examples/jsp/first.jsp .

36

R.V.College of Engineering

Dept. of MCA

10. Write a JAVA JSP Program which uses <jsp:plugin> tag to run a applet. The <jsp:plugin> is used to display an object, especially an applet or a Bean on the client browser. When the Jsp file is translated and compiled, the <jsp:plugin> is replaced by either an <object> or <embed> element, it is based on the browser version. Some of the attributes of <jsp: plugin> are defined below: type = "bean |applet" :- This type of object will be executed by the plug-in. It must be either bean or an applet. code = "ClassFileName" :- It is the name of the java class file which will be executed by the plug-in. The use .class extension is a must. codebase = "ClassFileDirectoryName" :- It is the name of the directory that contains the java class file, that will be executed by the plug-in. Syntax: <jsp: plugin type = "bean |applet" code = "ClassFileName" codeBase = "ClassFileDirectoryName" Program: import java.awt.*; import java.applet.*; applet.java public class applet extends Applet { int x1=0, y1=100, x2, y2; public void init() { setBackground ( Color.red ); } public void paint(Graphics g) { if(x1 > 300) x1=0; g.fillOval(x1, y1, 30, 30); x1++; try{ Thread.sleep(100); } catch(Exception e){}

37

R.V.College of Engineering repaint(); } }

Dept. of MCA

<html> <title> Plugin example </title> <body bgcolor="white"> <h3> Applet : </h3> <jsp:plugin type="applet" code="applet.class" codebase="applet" width="300" height="400" > <jsp:fallback> Plugin tag OBJECT or EMBED not supported by browser. </jsp:fallback> </jsp:plugin> <p> <h4> <font color=red> Jsp plugin example </font> </h4> </body> </html> Test Data: http://localhost:8080/examples/lab/appletjsp.jsp

38

R.V.College of Engineering

Dept. of MCA

11.Write a JAVA JSP Program which implements nested tags and also uses TagSupport Class. 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: Program: tagsupport.jsp <%@ taglib uri="/WEB-INF/tld/test.tld" prefix="custom"%> <custom:parent country="India"> <custom:child country="India">I am in india</custom:child> <custom:child country="US">I am in US</custom:child> <custom:child country="UK">I am in UK</custom:child> </custom:parent> test.tld (should be placed in /apache-tomcat-6.0.32/webapps/examples/WEB-INF/tld) <?xml version="1.0" encoding="ISO-8859-1" ?> <taglib xmlns="http://www.java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

39

R.V.College of Engineering

Dept. of MCA

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web- jsptaglibrary_2_0.xsd" version="2.0"> <tlibversion>1.2</tlibversion> <tag> <name>parent</name> <tagclass>tag.ParentTagHandler</tagclass> <bodycontent>jsp</bodycontent> <attribute> <name>country</name> <required>true</required> </attribute> </tag> <tag> <name>child</name> <tagclass>tag.ChildTagHandler</tagclass> <bodycontent>jsp</bodycontent> <attribute> <name>country</name> <required>true</required> </attribute> </tag> </taglib> ChildTagHandler.java (should be placed in /apache-tomcat-6.0.32 /webapps / examples/WEBINF/classes/tag , where tag is a package) package tag; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.Tag; import javax.servlet.jsp.tagext.TagSupport; public class ChildTagHandler extends TagSupport { public Tag parent; private String country; public int doStartTag() throws JspException { ParentTagHandler parentTag = (ParentTagHandler) parent; if (getCountry().equals(parentTag.getCountry())) { return EVAL_BODY_INCLUDE; } return SKIP_BODY; } public void setParent(Tag parent) { this.parent = parent; } public String getCountry() { return country;

40

R.V.College of Engineering

Dept. of MCA

} public void setCountry(String country) { this.country = country; } } ParentTagHandler.java (should be placed in /apache-tomcat-6.0.32 /webapps / examples/WEB-INF/classes/tag , where tag is a package) package tag; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; public class ParentTagHandler extends TagSupport { private String country; public int doStartTag() throws JspException { return EVAL_BODY_INCLUDE; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } }

Test Data: http://localhost:8080/examples/lab/tagsupport.jsp I am in india

41

R.V.College of Engineering

Dept. of MCA

12.An EJB application that demonstrates Session Bean. A session bean encapsulates business logic that can be invoked programmatically by a client over local, remote, or web service client views. To access an application that is deployed on the server, the client invokes the session beans methods. The session bean performs work for its client, shielding it from complexity by executing business tasks inside the server. A session bean is not persistent. (That is, its data is not saved to a database.) Types of Session Beans Session beans are of three types: stateful, stateless, and singleton. Stateful Session Beans The state of an object consists of the values of its instance variables. In a stateful session bean, the instance variables represent the state of a unique client/bean session. Because the client interacts (talks) with its bean, this state is often called the conversational state. As its name suggests, a session bean is similar to an interactive session. A session bean is not shared; it can have only one client, in the same way that an interactive session can have only one user. When the client terminates, its session bean appears to terminate and is no longer associated with the client. The state is retained for the duration of the client/bean session. If the client removes the bean, the session ends and the state disappears. This transient nature of the state is not a problem, however, because when the conversation between the client and the bean ends, there is no need to retain the state. Stateless Session Beans A stateless session bean does not maintain a conversational state with the client. When a client invokes the methods of a stateless bean, the beans instance variables may contain a state specific to that client but only for the duration of the invocation. When the method is finished, the clientspecific state should not be retained. Clients may, however, change the state of instance variables in pooled stateless beans, and this state is held over to the next invocation of the pooled stateless bean. Except during method invocation, all instances of a stateless bean are equivalent, allowing the EJB container to assign an instance to any client. That is, the state of a stateless session bean should apply across all clients. Because they can support multiple clients, stateless session beans can offer better scalability for applications that require large numbers of clients. Typically, an application requires fewer stateless session beans than stateful session beans to support the same number of clients. A stateless session bean can implement a web service, but a stateful session bean cannot. When to Use Session Beans Stateful session beans are appropriate if any of the following conditions are true. The beans state represents the interaction between the bean and a specific client.

42

R.V.College of Engineering

Dept. of MCA

The bean needs to hold information about the client across method invocations. The bean mediates between the client and the other components of the application, presenting a simplified view to the client. Behind the scenes, the bean manages the work flow of several enterprise beans. To improve performance, you might choose a stateless session bean if it has any of these traits. The beans state has no data for a specific client. In a single method invocation, the bean performs a generic task for all clients. For example, you might use a stateless session bean to send an email that confirms an online order. The bean implements a web service. Program: TestEJBBean.java (Session Bean) package stateless; import javax.ejb.Stateless; /** * * @author harish */ @Stateless public class TestEJBBean implements TestEJBRemote, TestEJBLocal { public String getMessage() { return "hello"; } public double add(double a, double b) { return (a+b); } public double sub(double a, double b) { return (a-b); } public double multi(double a, double b) { return (a*b); } } TestEJBLocal.java (Local Interface of the session bean)

43

R.V.College of Engineering package stateless; import javax.ejb.Local; /** * * @author harish */ @Local public interface TestEJBLocal { String getMessage(); double add(double a, double b); double sub(double a, double b); double multi(double a, double b); }

Dept. of MCA

TestEJBLocal.java (Remote Interface of the session bean) package stateless; import javax.ejb.Remote; /** * * @author harish */ @Remote public interface TestEJBRemote { String getMessage(); double add(double a, double b); double sub(double a, double b); double multi(double a, double b); } TestServlet.java (Servlet) package servlets; 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;

44

R.V.College of Engineering

Dept. of MCA

import javax.servlet.http.HttpServletResponse; import stateless.TestEJBRemote; /** * * @author harish */ public class TestServlet extends HttpServlet { @EJB private TestEJBRemote testEJBBean; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { double result= 0.0; String s1 = request.getParameter("num1"); String s2 = request.getParameter("num2"); String s3 = request.getParameter("group1"); if(s3.equals("add")) { result = testEJBBean.add(Double.valueOf(s1),Double.valueOf(s2)); } if(s3.equals("multi")) { result = testEJBBean.multi(Double.valueOf(s1),Double.valueOf(s2)); } if(s3.equals("sub")) { result = testEJBBean.sub(Double.valueOf(s1),Double.valueOf(s2)); } out.println("<html>"); out.println("<head>"); out.println("<title>Servlet TestServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("Result =" + result); out.println("<h1>Servlet TestServlet at " + request.getContextPath () + "</h1>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } }

45

R.V.College of Engineering

Dept. of MCA

@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Short description"; }// </editor-fold> } index.jsp <%-Document : index Created on : 19 Jan, 2012, 10:56:57 AM Author : harish --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body bgcolor="pink"> <h1>Calculator</h1> <hr> <form action="TestServlet"> <p>Enter first value: <input type="text" name="num1" size="25"></p> <br> <p>Enter second value: <input type="text" name="num2" size="25"></p>

46

R.V.College of Engineering

Dept. of MCA

<br> <b>Seclect your choice:</b><br> <input type="radio" name="group1" value ="add">Addition<br> <input type="radio" name="group1" value ="sub">Subtraction<br> <input type="radio" name="group1" value ="multi">Multiplication<br> <p> <input type="submit" value="Submit"> <input type="reset" value="Reset"></p> </form> </body> </html> Test Data: Code is developed using netbeans 6.7 IDE and deployed using Glassfish v2 application server http://localhost:8080/Test-war/ Calculator Enter first value: Enter second value: Seclect your choice: Addition Subtraction Multiplication SUBMIT CLEAR

47

R.V.College of Engineering

Dept. of MCA

13 An EJB application that demonstrates Entity Bean. An Entity Bean An entity bean is an object representation of persistent data maintained in a permanent data store such as a database. A primary key identifies each instance of an entity bean. Entity beans are transactional and are recoverable in the event of a system crash. Entity beans are representations of explicit data or collections of data, such as a row in a relational database. Entity bean methods provide procedures for acting on the data representation of the bean. An entity bean is persistent and survives as long as its data remains in the database. An entity bean can be created in two ways: by direct action of the client in which a create() method is called on the beans home interface, or by some other action that adds data to the database that the bean type represents. In fact, in an environment with legacy data, entity objects may exist before an EJB is even deployed. An entity bean can implement either bean-managed or container-managed persistence. In the case of bean-managed persistence, the implementer of an entity bean stores and retrieves the information managed by the bean through direct database calls. The bean may utilize either Java Database Connectivity (JDBC) or SQL-Java (SQLJ) for this method. (Session beans may also access the data they manage using JDBC or SQLJ.) A disadvantage to this approach is that it makes it more difficult to adapt bean-managed persistence to alternative data sources. In the case of container-managed persistence, the container provider may implement access to the database using standard APIs. The container provider can offer tools to map instance variables of an entity bean to calls to an underlying database. This approach makes it easier to use entity beans with different databases. Program: Emp.java (Entity Class) package server; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; /** * * @author harish */ @Entity 48

R.V.College of Engineering

Dept. of MCA

@Table(name = "emp") @NamedQueries({@NamedQuery(name = "Emp.findAll", query = "SELECT e FROM Emp e"), @NamedQuery(name = "Emp.findById", query = "SELECT e FROM Emp e WHERE e.id = :id"), @NamedQuery(name = "Emp.findByName", query = "SELECT e FROM Emp e WHERE e.name = :name")}) public class Emp implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "ID") private Integer id; @Column(name = "Name") private String name; public Emp() { } public Emp(Integer id) { this.id = id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set 49

R.V.College of Engineering

Dept. of MCA

if (!(object instanceof Emp)) { return false; } Emp other = (Emp) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "server.Emp[id=" + id + "]"; } } EntitySessionBean.java (session bean) package server; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author harish */ @Stateless public class EntitySessionBean implements EntitySessionRemote, EntitySessionLocal { @PersistenceContext private EntityManager em; public void persist(Object object) { em.persist(object); } public void addEmp(int id, String name) { Emp e = new Emp(); e.setId(id); e.setName(name); persist(e); } Local Interface for EntitySessionBean

50

R.V.College of Engineering

Dept. of MCA

package server; import javax.ejb.Local; /** * * @author harish */ @Local public interface EntitySessionLocal { void addEmp(int id, String name); } Remote Interface for EntitySessionBean package server; import javax.ejb.Remote; /** * * @author harish */ @Remote public interface EntitySessionRemote { void addEmp(int id, String name); } NewServlet.java (Servlet which will interact with Session Bean) package servlets; 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 server.EntitySessionRemote; /** * * @author harish */ public class NewServlet extends HttpServlet { @EJB private EntitySessionRemote entitySessionBean; 51

R.V.College of Engineering

Dept. of MCA

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { entitySessionBean.addEmp(Integer.parseInt(request.getParameter("id")),request.getPara meter("name")); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet NewServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1> Data base Updated </h1>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Short description"; }// </editor-fold> } index.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 52

R.V.College of Engineering

Dept. of MCA

"http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Employee Detail</title> </head> <body> <form action="NewServlet" method="get"> <h1> Servlet EJB Session Entity Bean </h1> EMP ID : <input type="text" size="3" name="id" > <br> EMP NAME: <input type="text" size="15" name="name"> <br> <input type="submit" name="post" value="post"> <input type="reset" name="clear" value="clear"> </form> </body> </html> Test Data: Code is developed using netbeans 6.7 IDE and deployed using Glassfish v2 application server http://localhost:8080/EntityTest-war/
Servlet EJB Session Entity Bean

EMP ID : 1 EMP NAME: harish SUBMIT CLEAR

14. An EJB application that demonstrates MDB. 53

R.V.College of Engineering

Dept. of MCA

A message-driven bean is an enterprise bean that allows Java EE applications to process messages asynchronously. This type of bean normally acts as a JMS message listener, which is similar to an event listener but receives JMS messages instead of events. The messages can be sent by any Java EE component (an application client, another enterprise bean, or a web component) or by a JMS application or system that does not use Java EE technology. Messagedriven beans can process JMS messages or other kinds of messages. What Makes Message-Driven Beans Different from Session Beans? The most visible difference between message-driven beans and session beans is that clients do not access message-driven beans through interfaces. Interfaces are described in the section Accessing Enterprise Beans. Unlike a session bean, a message-driven bean has only a bean class. In several respects, a message-driven bean resembles a stateless session bean. A message-driven beans instances retain no data or conversational state for a specific client. All instances of a message-driven bean are equivalent, allowing the EJB container to assign a message to any message-driven bean instance. The container can pool these instances to allow streams of messages to be processed concurrently. A single message-driven bean can process messages from multiple clients. The instance variables of the message-driven bean instance can contain some state across the handling of client messages, such as a JMS API connection, an open database connection, or an object reference to an enterprise bean object. Client components do not locate message-driven beans and invoke methods directly on them. Instead, a client accesses a message-driven bean through, for example, JMS by sending messages to the message destination for which the message-driven bean class is the MessageListener. You assign a message-driven beans destination during deployment by using GlassFish Server resources. Message-driven beans have the following characteristics. They execute upon receipt of a single client message. They are invoked asynchronously. They are relatively short-lived. They do not represent directly shared data in the database, but they can access and update this data. They can be transaction-aware. They are stateless. When a message arrives, the container calls the message-driven beans onMessage method to process the message. The onMessage method normally casts the message to one of the five JMS message types and handles it in accordance with the applications business logic. The onMessage method can call helper methods or can invoke a session bean to process the information in the message or to store it in a database. 54

R.V.College of Engineering

Dept. of MCA

A message can be delivered to a message-driven bean within a transaction context, so all operations within the onMessage method are part of a single transaction. If message processing is rolled back, the message will be redelivered. When to Use Message-Driven Beans Session beans allow you to send JMS messages and to receive them synchronously but not asynchronously. To avoid tying up server resources, do not to use blocking synchronous receives in a server-side component; in general, JMS messages should not be sent or received synchronously. To receive messages asynchronously, use a message-driven bean. In this example, we are going to implement a Message-driven bean application named "massage" that has the following components: A client application that sends several messages to a queue: MessageClient A message-driven bean that asynchronously receives and processes the messages that are sent to the queue: MessageBean Program: package mdb; import javax.jms.*; import javax.naming.*; import java.text.*; import javax.annotation.*; @Resource(mappedName="jms/Queue") class MessageConn{ private static Queue queue = null; QueueConnectionFactory factory = null; QueueConnection connection = null; QueueSender sender = null; QueueSession session = null; public MessageConn(){ try { //client creates the connection, session, and message sender: connection = factory.createQueueConnection(); session = connection.createQueueSession(false,

55

R.V.College of Engineering

Dept. of MCA

QueueSession.AUTO_ACKNOWLEDGE); sender = session.createSender(queue); //create and set a message to send TextMessage msg = session.createTextMessage(); for (int i = 0; i < 5; i++) { msg.setText("This is my sent message " + (i + 1)); //finally client sends messages //asynchronously to the queue sender.send(msg); } System.out.println("Sending message"); session.close (); } catch (Exception e) { e.printStackTrace (); } } } public class MessageClient{ public static void main(String[] args){ MessageConn msgcon = new MessageConn(); } } For Web-client: In a Web-client application "jms/Queue" and ConnectionFactory" argument are used in the JNDI lookup. Both are logical JNDI names, and use the outbound connectivity provided by the JMS resource adapter. Make the JNDI lookup to use a Web Service shown as. InitialContext ctx = new InitialContext(); queue = (Queue) ctx.lookup("jms/Queue"); QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup("ConnectionFactory"); connection = factory.createQueueConnection(); session = cnn.createQueueSession(false,

56

R.V.College of Engineering

Dept. of MCA

QueueSession.AUTO_ACKNOWLEDGE); The MessageBean class demonstrates the following requirements to its implementation: package mdb; import javax.ejb.*; import javax.ejb.MessageDriven; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.ObjectMessage; import java.text.*; import javax.naming.*; import java.util.logging.Logger; @MessageDriven(mappedName="jms/Queue") public class MessageBean implements MessageListener { @Resource private MessageDrivenContext mdc; private static final Logger logger; public void onMessage(Message msg) { TextMessage tmsg = null; try { tmsg = (TextMessage) msg; logger.info("MESSAGE BEAN: Message received: " + tmsg.getText( )); System.out.println ("The onMessage() is called"); } catch (JMSException e) { e.printStackTrace( ); mdc.setRollbackOnly( ); } catch (Throwable th) { th.printStackTrace(); } } public void ejbRemove( )throws EJBException{ loger.fine("ejbRemove()"); } } Test data: In the server log file, the following lines should be displayed, wrapped in logging information:

57

R.V.College of Engineering

Dept. of MCA

MESSAGE BEAN: Message received: This is my sent message 1 MESSAGE BEAN: Message received: This is my sent message2 MESSAGE BEAN: Message received: This is my sent message 3 MESSAGE BEAN: Message received: This is my sent message 4

58

R.V.College of Engineering

Dept. of MCA

Viva questions & extra programs

59

R.V.College of Engineering

Dept. of MCA

VIVA- QUESTIONS
1.Use of Class.forName 2.Use of Driver Manager.getconnection 3.Result set 4.Use of next ( ) method in result set 5.Prepared Statement 6.Explain i. Servlets Life Cycle (with diagram) ii. Servlets API 7.Explain doGet, doPost types in Servlet, write a program to implement doGet or doPost using servlets 8.Explain different types of JSP Tags 9.List the three kinds of EJB classes. 10. Explain the two important interfaces of EJB. 11. Explain the creation of Session Java Bean. 12. Explain the Entity Java Bean 13. Explain the creation of Message-Driven Bean. 14. List some of the applications of java beans. 15. Give an example to Implementing Event Handling with Adapter class 16. Explain the methods, rebind() and lookup() in Naming class? 17. How do you pass data (including JavaBeans) to a JSP from a servlet? 18. What is Servlet chaining? 19. What is the life cycle of a servlet? 20. What is the difference between doPost and doGet methods? 21. What are the steps involved for making a connection with a database or how do you connect to a database? 22. What are drivers available for database connections? 23. What are the three bean times? 24. What are the five features of a JavaBean? 25. What is a property? 26. What is the EventTargetDialog in the BeanBox? 27. Where do the jar files for beans go in the BeanBox? 28. How do we compile and execute a Java class that resides in a package? 29. What goes in a manifest file for a JavaBean? 30. What is the advantage of denormalization? 31. Is the JDBC-ODBC Bridge multi-threaded? 32. What is the fastest type of JDBC driver? 33. What are the different JDB drivers available? 34. What is Connection pooling? 35. What is Connection? 36. What is JDBC? 37. What are the steps required to execute a query in JDBC? 38. What is JDBC Driver ? 39. What is the servlet? 40. What are the JSP atrributes?

60

R.V.College of Engineering

Dept. of MCA

41. What is the need of super.init(config) in servlets? 42. How to know whether we have to use jsp or servlet in our project? 43. Can we call destroy() method on servlets from service method? 44. What is the Servlet Interface? 45. What is the difference between GenericServlet and HttpServlet? 46. How we can check in particular page the session will be alive or not? 47. What is the importance of deployment descriptor in servlet? 48. When we increase the buffer size in our project using page directive attribute buffer what changes we observe? 49. What is the difference between ServetConfig and ServletContext..? 50. When a servlet accepts a call from a client, it receives two objects. What are they? 51. What are the differences between GET and POST service methods? 52. In which conditions we have to use the ServletContext? 53. What methods will be called in which order?((i.e)service(),doget(),dopost())

Extra Programs 111Write a JSP Program Which Authenticate The user from DataBase and Redirect to another 1. JSP page 2. Write A JSP program to demonstrate Declarative tag Write A JSP program that Calls Servlet to perform Calculator operations(addition, sub, 3. multiplication) for two argument send by JSP Write an EJB application that demonstrates Session Bean for shopping cart. 4.

61

R.V.College of Engineering

Dept. of MCA

J2EE Lab Cycle For the semester Subject Code: 10MCA46 Hours/Week: 3 Total Hours: 42 I.A Marks: 50 Exam Hours: 03 Exam Marks: 50

Lab Program number with the question Cycle 1 a.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). 2 a.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). b.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) 3 a.Write a JAVA Servlet Program to implement RequestDispatcher object (use include() and forward() methods). b.Write a JAVA Servlet Program to implement and demonstrate get() and Post methods(Using HTTP Servlet Class). 4 a.Write a JAVA Servlet Program to implement sendRedirect() method(using HTTP Servlet Class). b.Write a JAVA Servlet Program to implement sessions (Using HTTP Session Interface). 5 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. 6 a.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. b.Write a JAVA JSP Program which uses <jsp:plugin> tag to run a applet. 7 a.Write a JAVA JSP Program which implements nested tags and also uses TagSupport Class. 8 a.An EJB application that demonstrates Session Bean. 9 a.An EJB application that demonstrates Entity Bean. 10 a.An EJB application that demonstrates MDB.

62

R.V.College of Engineering

Dept. of MCA

Procedures for record Writing Left Side of the record: 1. Steps for the program. 2. Output of the program. 3. Verified Data Sheet to be stucked Right Side of the record: 1. Program source code should be written. Lab evaluation procedure Lab exercise evaluation Program Execution 7 Marks Viva 3 Marks Internal Evaluation Lab 20 Marks 30 Marks - Lab Records - Internals

(Manju G) Faculty Sec A: Feb 2012

(Harish G.M) Faculty Sec B: Feb 2012

Director MCA

63

You might also like