You are on page 1of 48

J2EE LABORATORY [10MCA46]

J2EE Laboratory Subject Code: 10MCA46 Hours/Week: 3 Total Hours: 42 I.A Marks: Exam Hours: Exam Marks: 50 03 50

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). 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). 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) 4. Write a JAVA Servlet Program to implement RequestDispatcher object (use include() and forward() methods). 5. Write a JAVA Servlet Program to implement and demonstrate get() and Post methods(Using HTTP Servlet Class). 6. Write a JAVA Servlet Program to implement sendRedirect() method(using HTTP Servlet Class). 7. Write a JAVA Servlet Program to implement sessions (Using HTTP Session Interface).

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. 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. 10. Write a JAVA JSP Program which uses <jsp:plugin> tag to run a applet. 11. Write a JAVA JSP Program whch implements nested tags and also uses TagSupport Class. 12. An EJB application that demonstrates Session Bean. 13. An EJB application that demonstrates Entity Bean. 14. An EJB application that demonstrates MDB.

Department of MCA/Sir MVIT/Bangalore

J2EE LABORATORY [10MCA46]


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). SOURCE CODE: JDBCDemo.java import java.sql.*; import java.io.*; class JDBCDemo { public static void main(String args[]) { Connection con=null; Statement st=null; PreparedStatement pst=null; ResultSet rs=null; String str=null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:vas","",""); } catch(ClassNotFoundException e) { System.out.println("\nUnable to load JDBC/ODBC Bridge Driver"+e); System.exit(1); } catch(SQLException e) { System.out.println("Cannot able to connect with database"+e); } try { BufferedReader bufRead = new BufferedReader(new InputStreamReader(System.in)) ; while(true) { try{ System.out.println("\nSTUDENT INFORMATION MANAGEMENT SYSTEM"); System.out.println("\n1.Insert Info \n2.Query \n3.Updation \n4.Exit"); System.out.print("\nEnter your choice : "); int ch=Integer.parseInt(bufRead.readLine()); switch(ch) { case 1: System.out.println("\nEnter the student usn, name, branch,age and percentage\n"); String usn=bufRead.readLine(); String name=bufRead.readLine(); String branch=bufRead.readLine(); int age=Integer.parseInt(bufRead.readLine());

Department of MCA/Sir MVIT/Bangalore

J2EE LABORATORY [10MCA46]


float per=Float.parseFloat(bufRead.readLine()); pst=con.prepareStatement("insert into student values(?,?,?,?,?)"); pst.setString(1,usn); pst.setString(2,name); pst.setString(3,branch); pst.setInt(4,age); pst.setFloat(5,per); pst.execute(); break; case 2: System.out.println("\nEnter the query to be executed\n"); str=bufRead.readLine(); st=con.createStatement(); rs=st.executeQuery(str); ResultSetMetaData rmd=rs.getMetaData(); int col=rmd.getColumnCount(); int count=1; boolean b=rs.next(); if(!b) { System.out.println("No Data Found"); } else { do { System.out.print("RECORD " +(count++)+" => "); for(int i=0;i<col;i++) System.out.print(rs.getString(i+1)+"\t"); System.out.println(); }while(rs.next()); } break; case 3: System.out.println("\nEnter the query for updation"); str=bufRead.readLine(); st=con.createStatement(); int r=st.executeUpdate(str); if(r==0) System.out.println("\nNo rows Updated"); else System.out.println("\nYour upddation has been done successfully"); break; case 4: con.close(); System.exit(0); break; } } catch(SQLException e) { System.out.println(e); } catch(Exception e) {

Department of MCA/Sir MVIT/Bangalore

J2EE LABORATORY [10MCA46]


System.out.println(e); } } } catch(Exception e) { System.out.println(e); } } }

OUTPUT

Department of MCA/Sir MVIT/Bangalore

J2EE LABORATORY [10MCA46]

Department of MCA/Sir MVIT/Bangalore

J2EE LABORATORY [10MCA46]

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).
SOURCE CODE: Login.html <html> <head> <title>Login Page</title> </head> <body> <center><h1>Login Page</h1></center> <b>Please enter your username and password <form action="Login" method="POST"> <p><b>Username :<input type="text" name="username" length=40> <p><b>Password :<input type="password" name="pass" length=40> <p> <input type="submit" value="Submit"> </form> </body> </html> Login.java import javax.servlet.http.*; import java.io.*; public class Login extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse response) { String username=request.getParameter("username"); String pass=request.getParameter("pass"); try { response.setContentType("text/html"); PrintWriter writer=response.getWriter(); writer.println("<html><body>"); writer.println("<h4>Thank you, "+username+".You are now logged into the system.</h4>"); writer.println("<br><B>User Information"); writer.println("<br><br><B>UserName: "+username); writer.println("<br><B>Password: "+pass); writer.println("</body></html>"); writer.close(); }catch(Exception e){ e.printStackTrace(); } } }

Department of MCA/Sir MVIT/Bangalore

J2EE LABORATORY [10MCA46]

OUTPUT

Department of MCA/Sir MVIT/Bangalore

J2EE LABORATORY [10MCA46]

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)

SOURCE CODE: Download.html <html> <body> <h1>The SQL Tutorial</h1> <h3> <a href="http://localhost:8080/PROG3/DownloadServlet">Click here to Learn SQL</a> </h3> </body> </html> DownloadServlet.java import javax.servlet.http.*; import javax.servlet.*; import java.io.*; public class DownloadServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException { response.setContentType("application/msword"); response.setHeader("ContentDisposition","attachment;filename=SQL.doc"); ServletOutputStream output=response.getOutputStream(); FileInputStream file=new FileInputStream("F:\\SQL.doc"); int c=0; while((c=file.read())!=-1) { output.write(c); } output.flush(); output.close(); file.close(); } }

Department of MCA/Sir MVIT/Bangalore

J2EE LABORATORY [10MCA46]

OUTPUT

Department of MCA/Sir MVIT/Bangalore

J2EE LABORATORY [10MCA46]

4.

WRITE A JAVA SERVLET PROGRAM TO IMPLEMENT REQUESTDISPATCHER OBJECT (USE include() AND forward() METHODS).

SOURCE CODE: IFDemo.html <html> <head> <title>include and forward Demo</title> </head> <body> <center><h1>include forward Demo</h1></center> <b>Please enter mode of operation <form action="/PROG4/IFDemo"> <p><input type="text" name="mode" length=40> <p> <input type="submit" value="Submit"> <input type="reset" value="Clear"> </form> </body> </html> IFDemo.java import javax.servlet.http.*; import javax.servlet.*; import java.io.*; public class IFDemo extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) { String mode=request.getParameter("mode"); try { response.setContentType("text/html"); PrintWriter out = response.getWriter(); RequestDispatcher rd=null; if(mode.equals("forward")) { request.setAttribute("mode","Forward Response...."); rd=request.getRequestDispatcher("ForwardDemo"); rd.forward(request,response); } else if(mode.equals("include")) { request.setAttribute("mode","Include Response..."); out.println("<html>"); out.println("<head>"); out.println("<title>Includes Demo</title>"); out.println("</head>");

Department of MCA/Sir MVIT/Bangalore

10

J2EE LABORATORY [10MCA46]


out.println("<body>"); out.println("<h1>Hello from Level 1</h1>"); out.println("This text is displayed at Level 1."); rd = request.getRequestDispatcher("IncludeDemo"); rd.include(request, response); out.println("</body>"); out.println("</html>"); out.close(); } else { out.println("<h3> Enter only include or forward</h3>"); out.close(); } }catch(Exception e){ e.printStackTrace(); } } } ForwardDemo.java import javax.servlet.http.*; import java.io.*; public class ForwardDemo extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) { try { response.setContentType("text/html"); PrintWriter writer=response.getWriter(); String mode=(String)request.getAttribute("mode"); writer.println("Another doGet "); writer.println(mode); writer.close(); }catch(Exception e){ e.printStackTrace(); } } } IncludeDemo.java import javax.servlet.http.*; import java.io.*; public class IncludeDemo extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) { try {

Department of MCA/Sir MVIT/Bangalore

11

J2EE LABORATORY [10MCA46]


response.setContentType("text/html"); PrintWriter writer=response.getWriter(); String mode=(String)request.getAttribute("mode"); writer.println("<br><b>This is another text of "+mode); writer.close(); }catch(Exception e){ e.printStackTrace(); } } }

OUTPUT

Department of MCA/Sir MVIT/Bangalore

12

J2EE LABORATORY [10MCA46]

Department of MCA/Sir MVIT/Bangalore

13

J2EE LABORATORY [10MCA46]

5.

WRITE A JAVA SERVLET PROGRAM TO IMPLEMENT AND DEMONSTRATE GET AND POST METHODS(USING HTTP SERVLET CLASS).

SOURCE CODE: Get.html <html><head><title>Demonstration of Get and Post Method</title><head> <body bgcolor="pink"> <center> <form action="http://localhost:8080/PROG5/getpost"> <p><b>Press submit button to call Get method</b></p><br> <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> Post.html <html><head><title>Demonstration of Get and Post Method</title><head> <body bgcolor="pink"> <center> <form action="http://localhost:8080/PROG5/getpost" method="post"> <p><b>Press submit button to call Post method</b></p><br> <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> getpost.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class getpost extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response)

Department of MCA/Sir MVIT/Bangalore

14

J2EE LABORATORY [10MCA46]


throws ServletException,IOException { String color=request.getParameter("color"); response.setContentType("text/html"); PrintWriter pw=response.getWriter(); pw.println("<b>Hello from Post method</b><br><br>"); pw.println("You have selected" + " " + color + " " + "color"); pw.close(); } 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("<b>Hello from Get method</b><br><br>"); pw.println("You have selected" + " " + color + " " + "color"); pw.close(); } }

OUTPUT

Department of MCA/Sir MVIT/Bangalore

15

J2EE LABORATORY [10MCA46]

Department of MCA/Sir MVIT/Bangalore

16

J2EE LABORATORY [10MCA46]

6.

WRITE A JAVA SERVLET PROGRAM TO IMPLEMENT sendRedirect() METHOD(USING HTTP SERVLET CLASS).

SOURCE CODE SendRedirect.html <html> <head> <title>Redirecting the page</title> </head> <body> <form action = "SendRedirect" method = "post"> <b>Enter your name -----: <input type = "text" name = "username"><br> <b>Enter your password : <input type = "password" name = "password"><br> <input type = "submit" value = "SUBMIT"> <input type = "reset" value = "RESET"> </form> </body> </html> SendRedirect.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class SendRedirect extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String name = request.getParameter("username"); String password = request.getParameter("password"); if(name.equals("vit") && password.equals("vit")) { response.sendRedirect("ValidUser"); } else { pw.println("<h3>Invalid UserName or Password ...."); } } } ValidUser.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class ValidUser extends HttpServlet {

Department of MCA/Sir MVIT/Bangalore

17

J2EE LABORATORY [10MCA46]

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<center><h1>Welcome to Sir MVIT Home Page</h1></center>"); pw.close(); } }

OUTPUT

Department of MCA/Sir MVIT/Bangalore

18

J2EE LABORATORY [10MCA46]

7.

WRITE A JAVA SERVLET PROGRAM TO IMPLEMENT SESSIONS (USING HTTP SESSION INTERFACE).

SOURCE CODE ShowSession.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ShowSession extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { res.setContentType("text/html"); PrintWriter pw=res.getWriter(); String title="Session Tracking Example"; HttpSession session=req.getSession(true); String heading; Integer ac=(Integer)session.getAttribute("ac"); if(ac==null) { ac=new Integer(0); heading ="welcome,Newcomer"; } else { heading="Welcome back"; ac=new Integer(ac.intValue()+1); } session.setAttribute("ac",ac); pw.println("<html><head><title>"+title+"</title></head>"); pw.println(heading+"<br>"); pw.println("sessionID = "+session.getId()+"<br>"); pw.println("ac = "+ac+"<br>"); pw.close(); } }

Department of MCA/Sir MVIT/Bangalore

19

J2EE LABORATORY [10MCA46]

OUTPUT

Department of MCA/Sir MVIT/Bangalore

20

J2EE LABORATORY [10MCA46]

8.

a. WRITE A JAVA JSP PROGRAM TO PRINT 10 EVEN AND 10 ODD NUMBER.

SOURCE CODE EvenOdd.jsp <html> <head> <title> JSP Program </title> </head> <body> <br> <h1>Ten Odd Numbers</h1><br> <% for(int i=1;i<=20;i++) if(i%2!=0) { %> <b><font size="4"><%=i%></font></b> &nbsp;&nbsp;&nbsp;&nbsp; <% } %> <br><br> <h1>Ten Even Numbers</h1><br> <% for(int i=1;i<=20;i++) if(i%2==0) { %> <b><font size="4"><%=i%></font></b> &nbsp;&nbsp;&nbsp;&nbsp; <% } %> </body> </html>

Department of MCA/Sir MVIT/Bangalore

21

J2EE LABORATORY [10MCA46]

OUTPUT

Department of MCA/Sir MVIT/Bangalore

22

J2EE LABORATORY [10MCA46]

B.

WRITE A JAVA JSP PROGRAM TO IMPLEMENT VERIFICATION OF A PARTICULAR USER LOGIN AND DISPLAY A WELCOME PAGE.

SOURCE CODE Login.jsp <html> <head> <title>Login Page</title> </head> <body bgcolor="#fffff"> <form action="Validation.jsp"> <table border="0"> <tr> <td> User id :</td><td><input type="text" name="uname"/><br> </td> </tr> <tr> <td> password :</td><td><input type="password" name="password"/><br> </td> </tr> <tr> <td align="center"> <input type="submit" value="submit"> <input type="reset" value="reset"> </td> </tr> </table> </form> </body> </html> Validation.jsp <html> <body> <%! String uid="vas";%> <%! String pass="mvit";%> <%! String id,password; %> <% id=request.getParameter("uname"); %> <% password=request.getParameter("password"); %> <% if(uid.equals(id) && pass.equals(password)) { %> <jsp:forward page="Welcome.jsp"/> <% } else

{ %> <jsp:forward page="Error.jsp"/>

Department of MCA/Sir MVIT/Bangalore

23

J2EE LABORATORY [10MCA46]


<% } %> </body> </html> Welcome.jsp <body><center><h1> Welcome to Home Page</h1></center></body> Error.jsp <body> <h1>Invalid Entry ....</h1> <a href="http://localhost:8080/PROG8B/">< BACK</a> </body>

Department of MCA/Sir MVIT/Bangalore

24

J2EE LABORATORY [10MCA46]

OUTPUT

Department of MCA/Sir MVIT/Bangalore

25

J2EE LABORATORY [10MCA46]

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.

SOURCE CODE Registration.html <html> <head> <title>Registration Page</title> </head> <body> <h1>Registration Page</h1> <form action="StuInfo.jsp" method="post"> <table> <tr> <td align="right">First name : </td> <td align="left"><input type="text" name="firstName" length="30" /></td> </tr> <tr> <td align="right">Surname :</td> <td align="left"><input type="text" name="surname" length="30" /></td> </tr> <tr> <td align="right">USN :</td> <td align="left"><input type="text" name="usn" length="30" /></td> </tr> <tr> <td align="right">Course :</td> <td align="left"><input type="text" name="course" length="30" /></td> </tr> <tr> <td align="right">Sem :</td> <td align="left"><input type="text" name="sem" length="30" /></td> </tr> <tr> <td align="right">Age :</td> <td align="left"><input type="text" name="age" length="30" /></td> </tr> <tr> <td align="right">Address :</td> <td align="left"><input type="text" name="address" length="30" /></td>

Department of MCA/Sir MVIT/Bangalore

26

J2EE LABORATORY [10MCA46]


</tr> </table>

<p><input type="submit" value="Submit"/> <input type="reset" value="Reset"/></p> </form> </body> </html>

StuInfo.jsp <html> <head> <title>Register User</title> </head> <body> <jsp:useBean id="stud" scope="session" class="mvit.Student"> <jsp:setProperty name="stud" property="*"/> </jsp:useBean> <h3>These are the values you submitted </h3> <p>Your first name is <%= stud.getFirstName() %>.</p> <p>Your last name is <jsp:getProperty name="stud" property="surname"/>.</p> <p>Your user USN is <jsp:getProperty name="stud" property="usn"/>.</p> <p>Your Selected Course is <jsp:getProperty name="stud" property="course"/>.</p> <p>Your Sem is <jsp:getProperty name="stud" property="sem"/>.</p> <p>Your age is <jsp:getProperty name="stud" property="age"/>.</p> <p>Your Address is <jsp:getProperty name="stud" property="address"/>.</p> </body> </html> Student.java package mvit; public class Student { private String firstName; private String surname; private String usn; private String course; private int sem; private int age; private String address; private long contact; public String getFirstName() {

Department of MCA/Sir MVIT/Bangalore

27

J2EE LABORATORY [10MCA46]


return firstName; } public void setFirstName(String newFirstName) { this.firstName=newFirstName; } public String getSurname() { return surname; } public void setSurname(String newSurName) { this.surname=newSurName; } public String getUsn() { return usn; } public void setUsn(String newUsn) { this.usn=newUsn; } public String getCourse() { return course; } public void setCourse(String newCourse) { this.course=newCourse; } public int getAge() { return age; } public void setAge(int newAge) { this.age=newAge; } public int getSem() { return sem; } public void setSem(int newSem) { this.sem=newSem; } public String getAddress() { return address; } public void setAddress(String newAddress){ }}

this.address=newAddress;

Department of MCA/Sir MVIT/Bangalore

28

J2EE LABORATORY [10MCA46]

OUTPUT

Department of MCA/Sir MVIT/Bangalore

29

J2EE LABORATORY [10MCA46]

10. WRITE A JAVA JSP PROGRAM WHICH USES <JSP:PLUGIN> TAG TO RUN A APPLET.
SOURCE CODE AppJsp.jsp <%@ page language="java" %> <html> <head> <title>Welcome JSP-Applet Page</title> </head> <body> <jsp:plugin type="applet" code="AppJspDemo.class" width="400" height="400"> <jsp:fallback> <p>Unable to load applet</p> </jsp:fallback> </jsp:plugin> </body> </html> AppJspDemo.java import java.io.*; import java.awt.*; import java.util.*; import java.applet.*; import java.awt.event.*; public class AppJspDemo extends Applet { public void init() { setBackground(Color.blue); setForeground(Color.yellow); } public void paint(Graphics g){ g.drawString("Welcome JSP-Applet",100,100); } }

Department of MCA/Sir MVIT/Bangalore

30

J2EE LABORATORY [10MCA46]

OUTPUT

Department of MCA/Sir MVIT/Bangalore

31

J2EE LABORATORY [10MCA46]

11. WRITE A JAVA JSP PROGRAM WHCH IMPLEMENTS NESTED TAGS AND ALSO USES TAGSUPPORT CLASS.
SOURCE CODE Nested.jsp <%@taglib uri="/WEB-INF/tlds/nested.tld" prefix="mine"%> <mine:nest> <mine:nest> <mine:nest/> </mine:nest> </mine:nest>

Nested.tld <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>mine</short-name> <description>simple library.Author Rod Johnson</description> <tag> <name>nest</name> <tag-class>com.NestedLevelTag</tag-class> <body-content>JSP</body-content> <description> Hi </description> </tag> </taglib> NestedLevelTag.java package com; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.Tag; import javax.servlet.jsp.tagext.TagSupport; public class NestedLevelTag extends TagSupport{ private int nestLevel=0; public int doStartTag() throws JspException { nestLevel=0; Tag parent=getParent(); while(parent!=null) { parent=parent.getParent(); nestLevel++; }

try{ pageContext.getOut().println("<br> Tag nested level: "+nestLevel);

Department of MCA/Sir MVIT/Bangalore

32

J2EE LABORATORY [10MCA46]


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

OUTPUT

Department of MCA/Sir MVIT/Bangalore

33

J2EE LABORATORY [10MCA46]

12. AN EJB APPLICATION THAT DEMONSTRATES SESSION BEAN.


SOURCE CODE: CallServlet.html <html> <head> <title>Login Page</title> </head> <body> <h1>Arithmetic Operation</h1> <form action="CallSession" method="POST"> <p><b>Enter value for A :<input type="text" name="num1"/></b></p> <p><b>Enter value for B :<input type="text" name="num2"/></b></p> <p><b><input type="submit" value="Perform Operation"></b></p> </form> </body> </html>

CallSession.java package com; import import import import import import import java.io.IOException; java.io.PrintWriter; javax.ejb.EJB; javax.servlet.ServletException; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse;

public class CallSession extends HttpServlet { @EJB private SessionBeanDemoLocal sessionBeanDemo;

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); int a,b; a=Integer.parseInt(request.getParameter("num1")); b= Integer.parseInt(request.getParameter("num2")); try { out.println("<html>"); out.println("<head>");

Department of MCA/Sir MVIT/Bangalore

34

J2EE LABORATORY [10MCA46]


out.println("<title>Arithmetic Operation</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Arithmetic Operation</h1>"); out.println("<h2>A = "+a+" B= "+b+"</h2>"); out.println("<pre><h2>Addition(A+B) ="+ sessionBeanDemo.add(a,b) + "</h2>"); out.println("<h2>Subtraction(A-B) = " + sessionBeanDemo.sub(a, b) + "</h2>"); out.println("<h2>Multiplication(A*B) = " + sessionBeanDemo.mul(a, b) + "</h2>"); out.println("<h2>Division(A/B) = " + sessionBeanDemo.div(a, b) + "</h2></pre>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }

Department of MCA/Sir MVIT/Bangalore

35

J2EE LABORATORY [10MCA46]


/** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }

SessionBeanDemo.java package com; import javax.ejb.Stateless; /** * * @author VASANTH */ @Stateless public class SessionBeanDemo implements SessionBeanDemoLocal { @Override public int add(int a, int b) { return a+b; } @Override public int sub(int a, int b) { return a-b; } @Override public int mul(int a, int b) { return a*b; } @Override public int div(int a, int b) { return a/b; }

Department of MCA/Sir MVIT/Bangalore

36

J2EE LABORATORY [10MCA46]


SessionBeanDemoLocal.java package com; import javax.ejb.Local; @Local public interface SessionBeanDemoLocal { int add(int a, int b); int sub(int a, int b); int mul(int a, int b); int div(int a, int b); }

Department of MCA/Sir MVIT/Bangalore

37

J2EE LABORATORY [10MCA46]

OUTPUT

Department of MCA/Sir MVIT/Bangalore

38

J2EE LABORATORY [10MCA46]

13. AN EJB APPLICATION THAT DEMONSTRATES ENTITY BEAN.


SOURCE CODE: CallServlet.html <html> <head> <title>Login Page</title> </head> <body> <h1>ENTER STUDENT INFORMATION </h1> <form action="CallEntity" method="POST"> <p><b>USN ---------- :<input type="text" name="usn"/></b></p> <p><b>NAME ------ :<input type="text" name="name"/></b></p> <p><b>BRANCH -- :<input type="text" name="course"/></b></p> <p><b><input type="submit" value="Insert Student Info"></b></p> </form> </body> </html> CallEntity.java package com; import import import import import import import java.io.IOException; java.io.PrintWriter; javax.ejb.EJB; javax.servlet.ServletException; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse;

public class CallEntity extends HttpServlet { @EJB private StudentFacadeLocal studentFacade; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String usn,name,course; usn=request.getParameter("usn"); name=request.getParameter("name"); course=request.getParameter("course"); studentFacade.addStu(usn,name,course); try { out.println("<html>");

Department of MCA/Sir MVIT/Bangalore

39

J2EE LABORATORY [10MCA46]


out.println("<head>"); out.println("<title>Servlet CallEntity</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Student record sucessfully stored ....</h1>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description";

Department of MCA/Sir MVIT/Bangalore

40

J2EE LABORATORY [10MCA46]


}// </editor-fold> }

Student.java package com; import import import import import java.io.Serializable; javax.persistence.*; javax.validation.constraints.NotNull; javax.validation.constraints.Size; javax.xml.bind.annotation.XmlRootElement;

@Entity @Table(name = "STUDENT") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Student.findAll", query = "SELECT s FROM Student s"), @NamedQuery(name = "Student.findByUsn", query = "SELECT s FROM Student s WHERE s.usn = :usn"), @NamedQuery(name = "Student.findByName", query = "SELECT s FROM Student s WHERE s.name = :name"), @NamedQuery(name = "Student.findByCourse", query = "SELECT s FROM Student s WHERE s.course = :course")}) public class Student implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Size(min = 1, max = 20) @Column(name = "USN") private String usn; @Size(max = 20) @Column(name = "NAME") private String name; @Size(max = 20) @Column(name = "COURSE") private String course; public Student() { } public Student(String usn) { this.usn = usn; } public String getUsn() { return usn; } public void setUsn(String usn) { this.usn = usn; }

Department of MCA/Sir MVIT/Bangalore

41

J2EE LABORATORY [10MCA46]

public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCourse() { return course; } public void setCourse(String course) { this.course = course; } @Override public int hashCode() { int hash = 0; hash += (usn != null ? usn.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 if (!(object instanceof Student)) { return false; } Student other = (Student) object; if ((this.usn == null && other.usn != null) || (this.usn != null && !this.usn.equals(other.usn))) { return false; } return true; } @Override public String toString() { return "com.Student[ usn=" + usn + " ]"; } }

StudentFacade.java package com; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext;

Department of MCA/Sir MVIT/Bangalore

42

J2EE LABORATORY [10MCA46]


@Stateless public class StudentFacade extends AbstractFacade<Student> implements StudentFacadeLocal { @PersistenceContext(unitName = "EntityBeanDemo-ejbPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public StudentFacade() { super(Student.class); } @Override public void persist(Object object) { em.persist(object); } @Override public void addStu(String usn, String name, String course) { Student obj=new Student(); obj.setUsn(usn); obj.setName(name); obj.setCourse(course); persist(obj); } }

StudentFacadeLocal.java package com; import java.util.List; import javax.ejb.Local; @Local public interface StudentFacadeLocal { void create(Student student); void edit(Student student); void remove(Student student); Student find(Object id); List<Student> findAll(); List<Student> findRange(int[] range);

Department of MCA/Sir MVIT/Bangalore

43

J2EE LABORATORY [10MCA46]


int count(); void addStu(String usn, String name, String course); public void persist(java.lang.Object object); }

AbstractFacade.java package com; 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 cq = getEntityManager().getCriteriaBuilder().createQuery(); cq.select(cq.from(entityClass)); javax.persistence.Query q = getEntityManager().createQuery(cq);

Department of MCA/Sir MVIT/Bangalore

44

J2EE LABORATORY [10MCA46]


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(); } }

OUTPUT

Department of MCA/Sir MVIT/Bangalore

45

J2EE LABORATORY [10MCA46]

Department of MCA/Sir MVIT/Bangalore

46

J2EE LABORATORY [10MCA46]

14. AN EJB APPLICATION THAT DEMONSTRATES MDB.


SOURCE CODE:

HelloBean.java package hello; 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; /** * * @author VASANTH */ @MessageDriven(mappedName = "jms/hello", activationConfig = { @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"), @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") }) public class HelloBean implements MessageListener { public HelloBean() { } @Override public void onMessage(Message message) { try { System.out.println("Hello "+message.getStringProperty("name")); } catch (JMSException ex) { Logger.getLogger(HelloBean.class.getName()).log(Level.SEVERE, null, ex); } } } Main.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mdbclient;
Department of MCA/Sir MVIT/Bangalore 47

J2EE LABORATORY [10MCA46]

import javax.annotation.Resource; import javax.jms.*; /** * * @author VASANTH */ public class Main { @Resource(mappedName = "jms/hello") private static Queue hello; @Resource(mappedName = "jms/helloFactory") private static ConnectionFactory helloFactory; /** * @param args the command line arguments */ public static void main(String[] args) throws JMSException { // TODO code application logic here Connection connection = helloFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(hello); Message message=session.createMessage(); message.setStringProperty("name", "Vikram"); messageProducer.send(message); System.exit(0); } } OUTPUT

Department of MCA/Sir MVIT/Bangalore

48

You might also like