Hot questions for Using Enterprise JavaBeans in jsp

Question:

I use eclipse Neon. I created simple EJB project with follow code:

package com.clientManager;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;

/**
 * Session Bean implementation class ClientManager
 */
@Stateless
@LocalBean
public class ClientManager {

    /**
     * Default constructor. 
     */
    public ClientManager() {
        // TODO Auto-generated constructor stub
    }

    public String test() {
        return "test";
    }
}  

It created automatically and reside in ejbModule folder. It uses EJB 3.2 and successfully deploying on WildFly server:

11:25:50,360 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-3) WFLYSRV0028: Stopped deployment Neoflex.jar (runtime-name: Neoflex.jar) in 9ms
11:25:50,370 WARN  [org.jboss.as.controller] (DeploymentScanner-threads - 2) WFLYCTL0357: Notification of type deployment-undeployed is not described for the resource at the address []
11:25:50,370 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 2) WFLYSRV0009: Undeployed "Neoflex.jar" (runtime-name: "Neoflex.jar")
11:25:55,380 INFO  [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) WFLYDS0004: Found Neoflex.jar in deployment directory. To trigger deployment create a file called Neoflex.jar.dodeploy
11:25:55,380 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-7) WFLYSRV0027: Starting deployment of "Neoflex.jar" (runtime-name: "Neoflex.jar")
11:25:55,400 INFO  [org.jboss.weld.deployer] (MSC service thread 1-6) WFLYWELD0003: Processing weld deployment Neoflex.jar
11:25:55,400 INFO  [org.jboss.as.ejb3.deployment] (MSC service thread 1-6) WFLYEJB0473: JNDI bindings for session bean named 'ClientManager' in deployment unit 'deployment "Neoflex.jar"' are as follows:

    java:global/Neoflex/ClientManager!com.clientManager.ClientManager
    java:app/Neoflex/ClientManager!com.clientManager.ClientManager
    java:module/ClientManager!com.clientManager.ClientManager
    java:global/Neoflex/ClientManager
    java:app/Neoflex/ClientManager
    java:module/ClientManager

11:25:55,523 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 2) WFLYSRV0010: Deployed "Neoflex.jar" (runtime-name : "Neoflex.jar")

Now I created DynamicWebProject for JSP page which will use the EJB:

<%@page import="com.clientManager.*"%>
<%
    ClientManager c = new ClientManager(); 
%>
<%= c.test() %>

I configured in Build Path of JSP project the EJB project (!) Please see screenshot.

When I publish JSP and access to the page (main.jsp), I have:

JBWEB004060: An error occurred at line: 3 in the jsp file: /main.jsp
ClientManager cannot be resolved to a type
1: <%@page import="com.clientManager.*"%>
2: <%
3:  ClientManager c = new ClientManager(); 
4: %>
5: <%= c.test() %>

What is wrong?


Answer:

You shouldn’t directly instantiate the EJB bean rather it lifecycle in managed by the EJB container, the right way of getting the EJB bean handle is via it's look up method.

Make sure you choose the correct look up name, I am using randomly the one from your post Try changing to something like below.

<%
    ClientManager cm;
    cm = (ClientManager) ctx.lookup("java:module/ClientManager");
%>

Question:

What I'm trying to do is to send emails to clients via Gmail automatically as a reminder in a specific time. So I found a tutorial on YouTube: https://www.youtube.com/watch?v=gy2eEZhLihk, I made the same thing, same code but I didn't work.

Here is my code, I'm using eclipse and Glassfish server.

Page1: MailDispatcherServlet

package com.hubberspot.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hubberspot.ejb.MailSenderBean;


/**
 * Servlet implementation class MailDispatcherServlet
 */
@WebServlet("/MailDispatcherServlet")
public class MailDispatcherServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */

@EJB
private MailSenderBean mailSender;

public MailDispatcherServlet() {
    super();
    // TODO Auto-generated constructor stub
}



/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub


    response.setContentType("text/html");
    String toEmail = request.getParameter("Email");
    String subject = request.getParameter("Subject");
    String message = request.getParameter("Message");

    // Properties ...

    String fromEmail = "majjane.ma@gmail.com";
    String username = "majjane.ma";
    String password = "majjane.ma20";



    try (PrintWriter out= response.getWriter()){

        // Call to mail sender bean

        mailSender.sendEmail(fromEmail, username, password, toEmail, subject, message);


        //---------------------------

    out.println("<!Doctype html>");
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Mail Status</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Mail Status !!!</h1>");
    out.println("<b>Mail sent successfully</b><br>");
    out.println("Click <a href='emailClient.jsp'>here</a> to go back !!!");
    out.println("</body>");
    out.println("</html>");

    }
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}

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


    /*response.setContentType("text/html");
    String toEmail = request.getParameter("Email");
    String subject = request.getParameter("Subject");
    String message = request.getParameter("Message");

    // Properties ...

    String fromEmail = "majjane.ma@gmail.com";
    String username = "majjane.ma";
    String password = "Majjane.Ma2";



    try (PrintWriter out= response.getWriter()){

        // Call to mail sender bean




        //---------------------------

    out.println("<!Doctype html>");
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Mail Status</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Mail Status !!!</h1>");
    out.println("<b>Mail sent successfully</b><br>");
    out.println("Click <a href='emailClient.jsp'>here</a> to go back !!!");
    out.println("/body");
    out.println("</html>");

    }
    */

}
}

Page2: MailSenderBean

package com.hubberspot.ejb;

import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ejb.Stateless;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


@Stateless

public class MailSenderBean {


public void sendEmail(String fromEmail,String username, String password, String toEmail, String subject,String message) {

    try {
    Properties props = System.getProperties();
    props.put("mail.smtp.host","smtp.gmail.com");
    props.put("mail.smtp.auth","true");
    props.put("mail.smtp.port","465");
    props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.port","465");
    props.put("mail.smtp.socketFactory.fallback","false");



    Session mailSession = Session.getDefaultInstance(props, null);
    mailSession.setDebug(true);

    Message mailMessage = new MimeMessage(mailSession);


        mailMessage.setFrom(new InternetAddress(fromEmail));
        mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        mailMessage.setContent(message, "text/html");
        mailMessage.setSubject(subject);


        Transport transport = mailSession.getTransport("smtp");
        transport.connect("smtp.gmail.com",username ,password);

        transport.sendMessage(mailMessage, mailMessage.getAllRecipients());



    } catch (Exception ex) {

        Logger.getLogger(MailSenderBean.class.getName()).log(Level.SEVERE, null, ex);

    }


}

}

Page3: emailClient

This page has a form where I enter message, subject and the client adress. These parameters will be sent to the action page "MailDispatcherServlet", the method is Get.

This is what is displayed on my console:

  2015-08-13T10:08:11.264+0100|Infos: DEBUG: setDebug: JavaMail version 1.5.0
  2015-08-13T10:08:11.264+0100|Infos: DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
  2015-08-13T10:08:11.264+0100|Infos: DEBUG SMTP: useEhlo true, useAuth true
  2015-08-13T10:08:11.264+0100|Infos: DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL false
  2015-08-13T10:08:13.441+0100|Grave: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
      javax.net.ssl.SSLHandshakeException:       sun.security.validator.ValidatorException: PKIX path building failed:       sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1963)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:345)
at javax.mail.Service.connect(Service.java:226)
at com.hubberspot.ejb.MailSenderBean.sendEmail(MailSenderBean.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4695)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:630)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4667)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4655)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy222.sendEmail(Unknown Source)
at com.hubberspot.ejb.__EJB31_Generated__MailSenderBean__Intf____Bean__.sendEmail(Unknown Source)
at com.hubberspot.servlet.MailDispatcherServlet.doGet(MailDispatcherServlet.java:61)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:744)
  Caused by: javax.net.ssl.SSLHandshakeException:       sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1884)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1341)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:153)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:528)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:333)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:208)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
... 67 more
  Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1323)
... 78 more
  Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
... 84 more

Please let me know if you need any other details.

Thank you, Benz


Answer:

 Transport transport = mailSession.getTransport("smtps");// change smtp to smtps

and disable your PC antivirus and firewall then try

and turn on 'Access for less secure apps'

https://www.google.com/settings/security/lesssecureapps

then will able to send mail successfully.

Question:

Iam trying to call an ejb from another web-app (especially Servlet) and both hosted on the same JBoss AppServer.

First time it looks well if I invoke ejb-methods with String/integer return-values/types... But if I invoke methods with custom return-types then I will get "IOException marshaling EJB parameters", although the custom class definition is availiable on "WEB-INF/lib/"... I think its a little problem with big effect :-(

ejb project structure: enter image description here web-app project structure enter image description here

remote ejb classes are linked also to web-app

Remote:

package ma.remote;

import javax.ejb.Remote;


@Remote
public interface TestBeanRemote {
    public DataCenter getData();
    public String getStatus();

}

Implementation:

package ma.server;

import javax.ejb.Stateless;
import ma.remote.DataCenter;
import ma.remote.TestBeanRemote;


@Stateless
public class TestBeanImpl implements TestBeanRemote{

    @Override
    public DataCenter getData() {
        return new DataCenter("Lasname", "fistname", "examplestreet. 505", "berlin");
    }

    @Override
    public String getStatus() {
        String ret = "EJB funktioniert";
        System.out.println("public String getStatus():\n" + ret);

        return ret;
    }

}

custom class:

package ma.remote;


public class DataCenter {
    public String Name;
    public String Vorname;
    public String Adresse;
    public String Stadt;

    public DataCenter(String Name, String Vorname, String Adresse, String Stadt)
    {
        this.Name = Name;
        this.Vorname = Vorname;
        this.Adresse = Adresse;
        this.Stadt = Stadt;
    }
}

webapp and ejb is successful deployed on JBoss 7.1

14:09:03,010 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS018565: Replaced deployment "ejb-ejb.jar" with deployment "ejb-ejb.jar"
    14:11:08,472 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-2) JBAS015877: Stopped deployment ejb-ejb.jar in 7ms
    14:11:08,472 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-3) JBAS015876: Starting deployment of "ejb-ejb.jar"
    14:11:08,487 INFO  [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-3) JNDI bindings for session bean named TestBeanImpl in deployment unit deployment "ejb-ejb.jar" are as follows:

        java:global/ejb-ejb/TestBeanImpl!ma.remote.TestBeanRemote
        java:app/ejb-ejb/TestBeanImpl!ma.remote.TestBeanRemote
        java:module/TestBeanImpl!ma.remote.TestBeanRemote
        java:jboss/exported/ejb-ejb/TestBeanImpl!ma.remote.TestBeanRemote
        java:global/ejb-ejb/TestBeanImpl
        java:app/ejb-ejb/TestBeanImpl
        java:module/TestBeanImpl

    14:11:08,534 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS018565: Replaced deployment "ejb-ejb.jar" with deployment "ejb-ejb.jar"
    14:14:54,209 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-7) JBAS015877: Stopped deployment ejb-war.war in 20ms
    14:14:54,209 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-5) JBAS015876: Starting deployment of "ejb-war.war"
    14:14:54,334 INFO  [org.jboss.web] (MSC service thread 1-5) JBAS018210: Registering web context: /ejb-war
    14:14:54,381 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS018565: Replaced deployment "ejb-war.war" with deployment "ejb-war.war"

MyServlet which invokes ejb:

    package ma.remote;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ejbTester extends HttpServlet {


    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ejbTester</title>");
            out.println("</head>");
            out.println("<body>");


            try {
                Hashtable<String, String> jndiProperties = new Hashtable<String, String>();
                jndiProperties.put("java.naming.factory.url.pkgs", "org.jboss.ejb.client.naming");
                InitialContext context = new InitialContext(jndiProperties);
                String viewClassName = TestBeanRemote.class.getName();
                TestBeanRemote fbr = (TestBeanRemote) context.lookup("ejb:ejb-ejb/TestBeanImpl!" + viewClassName);
                //TestBeanRemote fbr = (TestBeanRemote) context.lookup("java:global/ejb-ejb/TestBeanImpl!" + viewClassName);

                //this will be invoked correctly
                String bn = fbr.getStatus();

                // but this one causes an exception!
                DataCenter dc = fbr.getData();
                out.println("DataCenter: " + dc.Name);
                out.println("message" + bn);
            } catch (NamingException e) 
            {
                System.out.println("\n EJB-Exception: \n" + e);
            }
            out.println("</body>");
            out.println("</html>");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

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

}

Exception on calling: localhost:8080/ejb-war/ejbTester :

14:24:50,650 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/ejb-war].[ejbTester]] (http--127.0.0.1-8080-1) Servlet.service() for servlet ejbTester threw exception: java.lang.RuntimeException: IOException marshaling EJB parameters
    at org.jboss.as.ejb3.remote.LocalEjbReceiver.clone(LocalEjbReceiver.java:227) [jboss-as-ejb3-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.ejb3.remote.LocalEjbReceiver.clone(LocalEjbReceiver.java:216) [jboss-as-ejb3-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.ejb3.remote.LocalEjbReceiver.processInvocation(LocalEjbReceiver.java:188) [jboss-as-ejb3-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:179) [jboss-ejb-client-1.0.5.Final.jar:1.0.5.Final]
    at org.jboss.ejb.client.TransactionInterceptor.handleInvocation(TransactionInterceptor.java:43) [jboss-ejb-client-1.0.5.Final.jar:1.0.5.Final]
    at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:181) [jboss-ejb-client-1.0.5.Final.jar:1.0.5.Final]
    at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:128) [jboss-ejb-client-1.0.5.Final.jar:1.0.5.Final]
    at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:181) [jboss-ejb-client-1.0.5.Final.jar:1.0.5.Final]
    at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:136) [jboss-ejb-client-1.0.5.Final.jar:1.0.5.Final]
    at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:121) [jboss-ejb-client-1.0.5.Final.jar:1.0.5.Final]
    at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:104) [jboss-ejb-client-1.0.5.Final.jar:1.0.5.Final]
    at com.sun.proxy.$Proxy18.getData(Unknown Source)
    at ma.servlets.ejbTester.processRequest(ejbTester.java:42) [classes:]
    at ma.servlets.ejbTester.doGet(ejbTester.java:66) [classes:]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:734) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]
    at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
    at java.lang.Thread.run(Thread.java:724) [rt.jar:1.7.0_40]
Caused by: java.io.NotSerializableException: ma.remote.DataCenter
    at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:256)
    at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:135)
    at org.jboss.as.ejb3.remote.LocalEjbReceiver.clone(LocalEjbReceiver.java:225) [jboss-as-ejb3-7.1.1.Final.jar:7.1.1.Final]
    ... 28 more

Do anybody knows what is wrong on my code/structure and can help me?

Thanks!


Answer:

You have defined a Remote EJB, this means you aim to have a distributed system, where you will have to transfer your object over network to a different JVM. So your POJO must be serializable, and so ma.remote.DataCenter must implement Serializable interface.

public class DataCenter implements Serializable {
    /** The serial version UID. */
    private static final long serialVersionUID = 1L;

    // attributes, getters and setters...

}

Question:

I want to pass a value calculated on the client-side, back to the server. Here is my code:

    <script>
        var today = new Date();
        function startTime() {
            document.getElementById('time').innerHTML = today.getTime();
            t = setTimeout(function () {
                startTime()
            }, 1);
        }
        startTime();
    </script>

    <form method="POST" action="../frontier/warehouseops/servlet/TimeCalculator">
        <input type="hidden" name="time" value="time"/>  
        <input type="submit" value="Submit" name="buttonSubmit"/>  
    </form>

What I want to happen is that the value of the javascript variable "time" gets passed to the server. But what is happening, is simply the string "time" is being passed to the server. How do I access the value of a javascript variable and pass it back to the server in a form?


Answer:

instead of:

document.getElementById('time').innerHTML = today.getTime();

try this:

document.getElementsByName("time")[0].value = today.getTime();

Question:

I am new to Servlets and I tried to create a Helper class for Database access. I created this simple class and it works more or less. I can access the Database without any problems inside the "startUp" method, but when I access the methods inside the Servlets "dataSource" is always null. What am I doing wrong?

I am using Netbeans with Glassfish 4.1 and Java 7.

Database.class

@Singleton
@Startup
public class Database {

    @Resource( lookup = "jdbc/resBookStoreMySql" )
    private DataSource dataSource;

    @PostConstruct
    private void startUp() {
        System.err.println("=====================");
        System.err.println(this.dataSource == null); //false
    }

    @Lock( LockType.READ )
    public boolean isPasswordCorrect(String username, String password) {
        boolean isPasswordCorrect = false;
        System.err.println(this.dataSource == null); //true

        // . . . 

        return isPasswordCorrect;
    }

    @Lock(LockType.READ)
    public List<Book> getBooks() {
        List<Book> books = new ArrayList<>();
        System.err.println(this.dataSource == null); //true

        // . . . 

    return books;
    }
}

SomeServlet.jsp:

....
<jsp:useBean id="db" class="at.laubi.servlet.data.Database" scope="page" /> 
....

Answer:

By using useBean you are instantiating new Database object, not injecting it and then @Resource is not processed and that's why dataSource is null.

As other suggested you shouldn't use EJB in jsp directly, but if you have to you need:

  • add @Named("database") to you bean
  • use for example #{database.books} in your JSP to get list of books