Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses
Showing posts with label J2EE. Show all posts
Showing posts with label J2EE. Show all posts

Java EE

  1. Java Server Pages (JSP) : Advantages over Servlets and other technologies
  2. How to create simple Hello World Servlet application in Java ?
  3. What is a Web Application in Java programming language?
  4. A Simple HTML and JSP Email Subscription List Application
  5. How to get real path for a file in JSP and Servlet ?.
  6. How to use various types of JSP tags in a JSP page ?
  7. How to set and get an attribute to/from request object in JSP and Servlets ?
  8. How to redirect responses to a different JSP or Servlets ?.
  9. How to add and retrieve Sessions in JSP and Servlets using Session Management API ?
  10. How to destroy a session in JSP and Servlets using Session Management API ?
  11. How to expire and destroy Cookies in JSP and Servlets ?
  12. A simple application demonstrating Request, Session, Context differences and usages in JSP and Servlets
  13. How to check whether which Web-Browser have been used to run JSP and Servlets ?.
  14. How to add and retrieve Sessions in JSP and Servlets using Session Management API ?
  15. How to destroy a session in JSP and Servlets using Session Management API ?
  16. How to perform create sql query in JSP and Servlets using JDBC ?
  17. How to perform insert sql query in JSP and Servlets using JDBC ?
  18. How to perform update sql query in JSP and Servlets using JDBC ?
  19. How to create a Filter that adds url and time of request to a database in JSP and Servlets ?.
  20. How to perform delete sql query in JSP and Servlets using JDBC ?
  21. How to create error page in a JSP and Servlet to handle exceptions ?
  22. How to use filters in JSP and Servlets for logging information in ServletContext logs ?
  23. How to include JSP page dynamically into another JSP page?
  24. How to display HTTP Request Headers through a Servlet ?.
  25. How to display Request url Information through a Servlet ?
  26. How to display request parameters in a JSP coming in a request ?.
  27. How to use model / Java / Pojo classes with JSP and Servlets ?.
  28. How to forward a request to a JSP using RequestDispatcher ?.
  29. How to do Session Management in JSP and Servlets using its methods and API ?.
  30. How to forward a request from one Jsp to another Jsp ?.
  31. How to include one JSP into another JSP ?.
  32. How to use Jsp action elements useBean, setProperty and getProperty to add, set and get property of a bean in a JSP page ?.
  33. How to decorate form in a JSP using fieldset and legend tag ?.
  34. How to write a Servlet code to download a Jar or file from the Server at a specified location ?.
  35. How to use Servlets Initialization Parameters through ServletConfig object in Java EE Application ?.
  36. How to use Context Parameters in Servlets through ServletContext object in Java EE Application ?.
  37. "Online Tweeter Enterprise Application" : Creating a JSP page in NetBeans Web module - Part 6
  38. "Online Tweeter Enterprise Application" : Creating a Servlet named DisplayTweets in NetBeans Web module - Part 9
  39. How to use Arithmetic Operations in Expression Language ( el ) in a simple jsp page ?.
  40. "Online Tweeter Enterprise Application" : Creating a Servlet named TweetsSubmit in NetBeans Web module - Part 8
  41. How to use param implicit object in a JSP page ?. 
  42. "Online Tweeter Enterprise Application" : Creating an Enterprise Application with EJB 3.1 in Netbeans - Part 0
  43. "Online Tweeter Enterprise Application" : Creating an Enterprise Application Project in NetBeans - Part 1
  44. "Online Tweeter Enterprise Application" : Creating a Persistence Unit in NetBeans - Part 2
  45. "Online Tweeter Enterprise Application" : Creating an Entity Class in NetBeans EJB module - Part 3
  46. "Online Tweeter Enterprise Application" : Creating a Message-Driven Bean in NetBeans EJB module - Part 4
  47. "Online Tweeter Enterprise Application" : Creating a Stateless Session Bean in NetBeans EJB module - Part 5
  48. "Online Tweeter Enterprise Application" : Creating a JSP page in NetBeans Web module - Part 6
  49. "Online Tweeter Enterprise Application" : Creating a Singleton Session Bean in NetBeans EJB module - Part 7
  50. "Online Tweeter Enterprise Application" : Creating a Servlet named TweetsSubmit in NetBeans Web module - Part 8
  51. "Online Tweeter Enterprise Application" : Creating a Servlet named DisplayTweets in NetBeans Web module - Part 9
  52. "Online Tweeter Enterprise Application" : Building and Running the Enterprise Application - Part 10
  53.  


How to use param implicit object in a JSP page ?.

A simple web application demonstrating how to use param implicit object in a jsp.

1. Create a simple jsp page as "param.jsp".

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form method="post" action="display.jsp">
            <tr>
                <td>Enter Your Name:</td>
                <td><input name="username" type="text"></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="Submit"></td>
            </tr>
        </form>
    </body>
</html>




2. Create a simple jsp page by name "display.jsp"

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        
        <h2>Name entered: ${param.username}</h2>
        
    </body>
</html>



display.jsp page use implicit object called as param to retrieve the form values coming as a post request.

Run param.jsp and enter username and click submit:



On clicking submit the form values passed as username to display.jsp which uses param implicit object to retrieve the value of username as shown below in the fig.



"Online Tweeter Enterprise Application" : Building and Running the Enterprise Application - Part 10

All the source code developed in previous posts is now ready to deploy and run on the Glassfish server.
Lets build the Online Tweeter Enterprise Application, to do so, right-click the Tweeter project and select the option Clean and Build as shown in diagram below:





The clean and build process is shown in the output window of the NetBeans IDE as shown below:













As soon as compilation and build process is done, just right-click tweets.jsp and run the file as shown in fig below:





                         

After running the jsp file, a browser window gets open and tweets.jsp page is displayed on the browser window as shown in the fig below:


                                                                     


Enter the username and tweet you want to publish and click Tweet button. After hitting Tweet button open a different browser window and open the same link and enter different username and tweet as shown below:




The DisplayTweet page gets open showing the two tweets by different users on both the browsers. This time it shows 2 current followers on the same page, that is two different users viewers viewing the page in two different browsers as shown below:





Just click on the link provided in the top right as "Add new tweets" as shown in fig below.




Enter the latest tweet and click Tweet button, the DisplayTweet window gets open showing the lastest tweet as shown below:










That ends our series of developing "Online Tweeter Enterprise Application", will be back with some new and powerful projects soon. Thanks and keep reading the blog.

"Online Tweeter Enterprise Application" : Creating a Servlet named DisplayTweets in NetBeans Web module - Part 9

Lets continue building "Online Tweeter Enterprise Application" in NetBeans. In this section of tutorial, you will create a Servlets in Web module by name "DisplayTweets.java". A Servlet is a server side program which executes at the server producing dynamic content for the web applications.

Step 1: Open "Tweeter-war" project and right click Source Packages and then select New and than Other as shown in fig below:




Step 2: On clicking Other a dialog box appears by name New File. In the Categories: list select Web and in the File Types: select Servlet as shown in fig below.




Step 3: Click

.
New Servlet
dialog box gets open. It prompts us to enter Class Name: , Project: , Location: , Package: and Created File: etc. Enter the values as shown in the fig below.





Step 4: Click

.
yet another New Servlet dialog box gets open. It prompts us to enter values related to Servlet deployment. Do not check "Add information to deployment descriptor (web.xml)". Just enter values as shown in figure below.








and than just click



A new servlet gets created in the source packages by name DisplayTweets.java. It has code which is generated by NetBeans. Just add or remove code given below.




package com.hubberspot.servlets;

import com.hubberspot.ejb.ActiveFollowersOnline;
import com.hubberspot.ejb.Tweet;
import com.hubberspot.ejb.TweetsFinder;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(name = "DisplayTweets", urlPatterns = {"/DisplayTweets"})
public class DisplayTweets extends HttpServlet {

    @EJB
    private TweetsFinder tweetsFinder;
    
    @EJB
    private ActiveFollowersOnline activeFollowersOnline;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");

        request.getSession(true);

        PrintWriter out = response.getWriter();

        try {
            out.println("");
            out.println("");
            out.println("");
            out.println("Latest Tweets");
            out.println("");
            out.println("");
            out.println("");
            out.println("
");
            out.println("");
            out.println("");
            out.println("
");
            out.println("
"); out.println("Latest Tweets"); out.println(""); out.println("Add new tweets"); out.println(" | "); out.println(activeFollowersOnline.getFollowersOnline() + " follower(s) reading tweets."); out.println("
"); out.println("
"); List tweets = tweetsFinder.findAllTweets(); for (Iterator it = tweets.iterator(); it.hasNext();) { Tweet tweet = (Tweet) it.next(); out.println(""); out.println(" "); out.println(""); out.println(" "); out.println(" "); out.println(""); out.println(" "); out.println("
"); out.println("User: " + tweet.getUsername() + ""); out.println("
"); out.println("Tweeted: " + tweet.getTweet() + ""); out.println("
"); out.println("
"); } out.println(""); out.println(""); } 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"; } }

In the next section of this blog (part 10) you will learn how to build and run the application in NetBeans.


How to use Arithmetic Operations in Expression Language ( el ) in a simple jsp page ?.

A simple jsp to demonstrate how to use Arithmetic Operations in Expression Language ( el ).

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body style="background-color: lightblue">
        <h2>Arithmetic Operations with EL !</h2>
        
        <table border="2">
            <thead>
                <tr>
                    <th>Operation</th>
                    <th>EL Expression</th>
                    <th>Result</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Digit</td>
                    <td>\${8}</td>
                    <td>${8}</td>
                </tr>
                <tr>
                    <td>Addition</td>
                    <td>\${4+4}</td>
                    <td>${4+4}</td>
                </tr>
                <tr>
                    <td>Addition</td>
                    <td>\${5.5+4.5}</td>
                    <td>${5.5+4.5}</td>
                </tr>
                <tr>
                    <td>Subtraction</td>
                    <td>\${15-5}</td>
                    <td>${15-5}</td>
                </tr>
                <tr>
                    <td>Division</td>
                    <td>\${20/4}</td>
                    <td>${20/4}</td>
                </tr>
                <tr>
                    <td>Multiplication</td>
                    <td>\${2*4}</td>
                    <td>${2*4}</td>
                </tr>
                <tr>
                    <td>Modulus</td>
                    <td>\${21%4}</td>
                    <td>${21%4}</td>
                </tr>
            </tbody>
        </table>        
    </body>
</html>



Output of the Jsp Page :



"Online Tweeter Enterprise Application" : Creating a Servlet named TweetsSubmit in NetBeans Web module - Part 8

Lets continue building "Online Tweeter Enterprise Application" in NetBeans. In this section of tutorial, you will create a Servlets in Web module by name "TweetsSubmit.java". A Servlet is a server side program which executes at the server producing dynamic content for the web applications.

Step 1: Open "Tweeter-war" project and right click Source Packages and then select New and than Other as shown in fig below:




Step 2: On clicking Other a dialog box appears by name New File. In the Categories: list select Web and in the File Types: select Servlet as shown in fig below.




Step 3: Click

.
New Servlet dialog box gets open. It prompts us to enter Class Name: , Project: , Location: , Package: and Created File: etc. Enter the values as shown in the fig below.





Step 4: Click

.
yet New Servlet dialog box gets open. It prompts us to enter values related to Servlet deployment. Do not check "Add information to deployment descriptor (web.xml)". Just enter values as shown in figure below.





and than just click



A new servlet gets created in the source packages by name TweetsSubmit.java. It has code which is generated by NetBeans. Just add or remove code given below.




package com.hubberspot.servlets;

import com.hubberspot.ejb.Tweet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.jms.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "TweetsSubmit", urlPatterns = {"/TweetsSubmit"})
public class TweetsSubmit extends HttpServlet {

    @Resource(mappedName = "jms/tweetsFactory")
    private ConnectionFactory connectionFactory;
    @Resource(mappedName = "jms/tweets")
    private Queue queue;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/html;charset=UTF-8");
        
        PrintWriter out = response.getWriter();
        
        String username = request.getParameter("txtUsername");
        String tweet = request.getParameter("txtTweet");

        if (username != null && tweet != null) {
            try {

                Connection connection = connectionFactory.createConnection();
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                MessageProducer messageProducer = session.createProducer(queue);

                ObjectMessage objectMessage = session.createObjectMessage();
                
                Tweet newTweet = new Tweet();
                newTweet.setUsername(username);
                newTweet.setTweet(tweet);
                
                objectMessage.setObject(newTweet);
                
                messageProducer.send(objectMessage);
             
                connection.close();
                
                response.sendRedirect("DisplayTweets");

            } catch (JMSException ex) {
                Logger.getLogger(TweetsSubmit.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

    @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";
    }
}



In the next section of this blog (part 9) you will learn how to create a yet another Servlet in NetBeans by name DisplayTweets, for this application in the Web module.


"Online Tweeter Enterprise Application" : Creating a Singleton Session Bean in NetBeans EJB module - Part 7


Lets continue building "Online Tweeter Enterprise Application" in NetBeans. In this section of tutorial, you will create a Singleton Session Bean by name "ActiveFollowersOnline.java". A Singleton Session Bean is a enterprise bean which are instantiated once per application and has lifecycle till application is alive.

Step 1: Open "Tweeter-war" project and right click Source Packages and then select New and than Other as shown in fig below:







Step 2: On clicking Other a dialog box appears by name New File. In the Categories: list select Enterprise JavaBeans and in the File Types: select Session Bean as shown in fig below.







Step 3: Click

.
New Session Bean dialog box gets open. It prompts us to enter EJB Name: , Project: , Location: , Package: , Session Type: and Create Interface: etc. Enter the values as shown in the fig below.



Step 4: Click




 

A new Singleton Session Bean gets created by name "ActiveFollowersOnline.java" in the "Tweeter-war" module in the package provided at the time of creating the bean. It has most of the source code already generated by NetBeans. Kindly add or remove additional code provided below.


package com.hubberspot.ejb;

import javax.ejb.Singleton;
import javax.ejb.LocalBean;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

// @Singleton annotation informs container that
// treat this bean as a Singleton bean.

// @LocalBean annotation informs container that
// this session bean exposes a no-interface view.

// @WebListener annotation informs container that
// this class is a web listener which will listen to 
// various events happening during lifecyle of application
// Here this class listens to Http Session when a session
// is created or destroyed.

// We make class implements HttpSessionListener which has two
// methods sessionCreated() and sessionDestroyed() , which 
// are called by the container whenever a session is created 
// or destroyed

@Singleton
@LocalBean
@WebListener
public class ActiveFollowersOnline implements HttpSessionListener {

    private static int followersOnline = 0;

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        
        System.out.print("Session Created : ");
        followersOnline++;
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        followersOnline--;
    }

    public int getFollowersOnline() {
        return followersOnline;
    }   
    
}




In the next section of this blog (part 8) you will learn how to create a Servlet in NetBeans for this application in the Web module.



"Online Tweeter Enterprise Application" : Creating a JSP page in NetBeans Web module - Part 6

Lets continue building "Online Tweeter Enterprise Application" in NetBeans. In this section of tutorial, you will create a Java Server Pages (JSP) by name "tweets.jsp". A JSP page is like a User Interface for Web Application. Its like a dynamic web page having html with java embedded into it.

Step 1:
Open "Tweeter-war" project and right click Web Pages and then select New and than Other as shown in fig below.





Step 2: On clicking Other a dialog box appears by name New File. In the Categories: list select Web and in the File Types: select JSP as shown in fig below.




Step 3: Click

.
New JSP dialog box gets open. It prompts us to enter values for the File Name: , Project: , Location: , Folder: , Created File: and Options: .Enter the required values as per fig shown below.




Step 4: Click




 

A new jsp page gets created by the name tweets.jsp in the "Tweeter-war" module.Kindly add or remove additional code provided below. 

<%@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>Tweeter</title>
    </head>
    <body>
        <table border="0" bgcolor="aquagreen" cellpadding="0" cellspacing="0" width="60%">
            <tr>
                <td>
                    <table border="0" align="center" cellpadding="0" cellspacing="0" width="100%">
                        <tr>
                            <td valign="middle" align="center" style="padding-right:0px; padding-left:0px; padding-bottom:0px; font:24px/30px Georgia; width:228px; color:#FFFFFF; padding-top:0px; height:37px;">
                                What's happening ?. !!!
                            </td>
                        </tr>
                    </table>                    
                </td>
            </tr>
            <tr align="left" valign="top">
                <td height="20">
                    <hr />
                </td>
            </tr>
            <tr>
                <td>
                    <form name="tweetsForm" action="TweetsSubmit" method="post">
                        <table border="0" cellpadding="0" cellspacing="0" width="100%">
                            <tr>
                                <td align="right" valign="top">
                                    UserName:
                                </td>
                                <td>
                                    <input type="text" name="txtUsername" size="50" maxlength="75"/>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <br/>
                                </td>
                            </tr>
                            <tr>
                                <td align="right" valign="top">
                                    Your Tweet:
                                </td>
                                <td>
                                    <textarea name="txtTweet" cols="38" rows="6"></textarea> 
                                </td>                                    
                            </tr>
                            <tr align="left">
                                <td height="20">
                                    <hr />
                                </td>
                                <td height="20">
                                    <hr />
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2" align="left">
                                    <input type="submit" value="Tweet" />
                                </td>
                            </tr>
                        </table>
                    </form>
                </td>
            </tr>            
        </table>
    </body>
</html>



Output of the jsp on browser window : 


tweets.jsp is a simple web page having few html components which prompts user to enter UserName , Tweet he/she wants to publish and than click on Submit button.  

In the next section of this blog (part 7) you will learn how to create a Singleton Session Bean in NetBeans for this application in the Web module. 

"Online Tweeter Enterprise Application" : Creating a Stateless Session Bean in NetBeans EJB module - Part 5


Lets continue building "Online Tweeter Enterprise Application" in NetBeans. In this section of tutorial, you will create a Stateless Session Bean by name "TweetsFinder.java". A Stateless Session Bean is a enterprise bean that is short - lived object which fulfill single client request and remember nothing about the client in subsequent requests.

Step 1: Open "tweeter-ejb" project and right click Source Packages and then select New and than Other as shown in fig below:










Step 2: On clicking Other a dialog box appears by name New File. In the Categories: list select Enterprise JavaBeans and in the File Types: select Session Bean as shown in fig below.































Step 3: Click

.
New Session Bean dialog box gets open. It prompts us to enter EJB Name: , Project: , Location: , Package: , Session Type: and Create Interface: etc. Enter the values as shown in the fig below.

Step 4: Click




 

A new Stateless Session Bean gets created by name "TweetsFinder.java" in the "tweeter-ejb" module in the package provided at the time of creating the bean. It has most of the source code already generated by NetBeans. Kindly add or remove additional code provided below.


package com.hubberspot.ejb;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

// @Stateless annotation provides container information to
// treat this Java class as a Stateless Session Bean.
@Stateless
public class TweetsFinder {

    // @PersistenceContext injects dependency for the EntityManager
    // by loading persistence.xml
    // EntityManager provides an interface for database persistence
    // such as to persist, merge , load and query objects.
    @PersistenceContext(name = "Tweeter-ejbPU")
    EntityManager tweetsManager;

    // This Stateless Session Bean has only one method
    // findAllTweets(). 
    public List< Tweet > findAllTweets() {

        // Here, it creates CriteriaQuery object
        // from EntityManager by calling its 
        // getCriteriaBuilder().createQuery() which returns 
        // back instance of CriteriaQuery.
        CriteriaQuery criteriaQuery = tweetsManager.getCriteriaBuilder().createQuery();

        // CriteriaQuery has two methods by name select()
        // and from which fetches data from database as 
        // normal SQL select query.        
        criteriaQuery.select(criteriaQuery.from(Tweet.class));

        // Creates a Query instance using criteriaQuery object
        // and EntityManager's createQuery() method.    
        Query query = tweetsManager.createQuery(criteriaQuery);

        // Finally it returns back list of tweets stored in 
        // database.    
        return query.getResultList();

    }
}





Video tutorial to demonstrate How to create a Java EE Stateless Session Bean (EJB) in an Enterprise Application using NetBeans.








In the next section of this blog (part 6) you will learn how to create a JSP page in NetBeans for this application in the Web module.



"Online Tweeter Enterprise Application" : Creating a Message-Driven Bean in NetBeans EJB module - Part 4


Lets continue building "Online Tweeter Enterprise Application" in NetBeans. In this section of tutorial, you will create a Message-Driven Bean by name "ReceiveTweets.java". A Message-Driven Bean is a enterprise bean that acts as a JMS message listener which process message coming on the queue or topic over which it is bound to listen.
In our "Online Tweeter Enterprise Application" it basically processes and stores the tweets sent by user from the servlet to the queue in database.

Step 1: Open "tweeter-ejb" project and right click Source Packages and then select New and than Other as shown in fig below:








Step 2: On clicking Other a dialog box appears by name New File. In the Categories: list select Enterprise JavaBeans and in the File Types: select Message-Driven Bean as shown in fig below.





Step 3: Click

.
New Message-Driven Bean dialog box gets open. It prompts us to enter values for EJB Name: , Project: , Location: , Package: , Project: , Destinations:. Enter the values as per fig below or enter what suits you.






Step 4: Click Add button to add a valid message destination. Add Message Destination dialog box gets open. Enter values for Destination Name: and Destination Type: as shown in fig below.





Step 5: Click



Previously opened New Message-Driven Bean dialog box gets open with the values entered for the Project Destinations: as shown in fig below.








Step 6:  After providing Project Destinations: click




 

A new Message-Driven Bean gets created by name "ReceiveTweets.java" in the "tweeter-ejb" module in the package provided at the time of creating the bean. It has most of the source code already generated by NetBeans. Kindly add or remove additional code provided below.


package com.hubberspot.ejb;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

// @MessageDriven annotation provides information to the container
// that this java class is a Message-Driven Bean. It has few 
// additional info about JNDI name of the destination to which
// this bean is listening.

// @ActivationConfigProperty annotation informs container about 
// the type of destination it is listening and the acknowledge
// mode.

// Message-Driven Bean must implement MessageListener which has a
// method onMessage() which gets triggered as soon as any message
// arrives over the queue.

@MessageDriven(mappedName = "jms/tweets", activationConfig = {
    @ActivationConfigProperty(propertyName = "acknowledgeMode", 
        propertyValue = "Auto-acknowledge"),
    @ActivationConfigProperty(propertyName = "destinationType", 
        propertyValue = "javax.jms.Queue")
})
public class ReceiveTweets implements MessageListener {
    
    // @Resource annotation injects the dependency for the resource
    // we intent to use. 
    
    @Resource
    MessageDrivenContext receiveTweetsContext;
    
    // @PersistenceContext injects dependency for the EntityManager
    // by loading persistence.xml
    // EntityManager provides an interface for database persistence
    // such as to persist, merge , load and query objects.
    
    @PersistenceContext(name="Tweeter-ejbPU")
    EntityManager tweetsManager;
    
    public ReceiveTweets() {
    }
    
    // The Object Message in the form of tweet entered
    // by the user in a Servlet is been persisted to 
    // database by EntityManager's persist() method.
    
    @Override
    public void onMessage(Message message) {
        
        ObjectMessage tweetMessage = null;
        
        if(message instanceof ObjectMessage) {
           
            try {
            
                tweetMessage = (ObjectMessage) message;
                
                Tweet tweet = (Tweet) tweetMessage.getObject();
                
                tweetsManager.persist(tweet);
            
            } catch (JMSException ex) {
           
                Logger.getLogger(ReceiveTweets.class.getName())
                        .log(Level.SEVERE, null, ex);
                receiveTweetsContext.setRollbackOnly();
            }
            
        }
        
    }
}




In the next section of this blog (part 5) you will learn how to create a Stateless Session Bean in NetBeans for this application.



"Online Tweeter Enterprise Application" : Creating an Entity Class in NetBeans EJB module - Part 3


Lets continue building "Online Tweeter Enterprise Application" in NetBeans. In this section of tutorial, you will create an Entity Class by name "Tweet.java". An Entity class is a simple POJO with annotations. It uses annotations like @Entity, @Id ... etc, which makes it persist in database as tables.

Step 1: Open "tweeter-ejb" project and right click Source Packages and then select New and than Other as shown in fig below:





Step 2: On clicking Other a dialog box appears by name New File. In the Categories: list select Persistence and in the File Types: select Entity Class as shown in fig below.




Step 3: Click

.
New Entity Class dialog box gets open. It prompts us to enter values for Class Name: , Project: , Location: , Package: , Created File: , Primary Key Type:. Enter the values as per fig below or enter what suits you.





and than just click
.

In the package provided at the time of creating Entity Class in the tweeter-ejb module Tweet.java gets created. It has most of the source code already generated by NetBeans. Kindly add or remove additional code provided below.

package com.hubberspot.ejb;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

// @Entity annotation is used to make a 
// Java class an Entity

@Entity
public class Tweet implements Serializable {

    private static final long serialVersionUID = 1L;

    // @Id annotation is used over the field which is
    // to be marked as primary key. Each entity class
    // needs to have this primary key.
    
    // @GeneratedValue annotation provides information
    // to the persistence provider to generate a way to
    // uniquely identify each instance of this entity class.
    // In order to do that it uses strategies for creating
    // new and unique id based on the strategy type.
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private String username;
    private String tweet;

    public String getTweet() {
        return tweet;
    }

    public void setTweet(String tweet) {
        this.tweet = tweet;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        
        if (!(object instanceof Tweet)) {
            return false;
        }
        Tweet other = (Tweet) 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 "com.hubberspot.ejb.Tweet[ id=" + id + " ]";
    }
    
}



Tweet.java has few properties such as tweet and username, which will be persisted in the database through getters and setters.

In the next section of this blog (part 4) you will learn how to create a Message Driven Bean in NetBeans for this application.

 
© 2021 Learn Java by Examples Template by Hubberspot