EJB cannot be found - java

I'm trying to use JavaBeans or the first time and I'm getting the following
error:
javax.naming.NameNotFoundException: DemoEJB
javax.naming.NamingException: Lookup failed for
'java:global/DemoEJB/ContenedorEJB/BeanStateful!beanssesion.BeanStatefulLocal'
in SerialContext[myEnv={java.naming.factory
I'm using NetBeans with glassfish 4.1 server.
The application is really simple, I have an Enterprise application project where I link an EJB Module (called ContenedorEJB) and a Client (which is a Servlet).
This is the projects structure:
ClienteWeb
Source Packages
-servlets
-ServletEJB.java
ContenedorEJB
-Source Packages
beanssesion
BeanStateful.java
BeanStatefulLocal.java
DemoEJB
-Java EE Modules
ContenedorEJB.jar
ClienteEJB.war
The servlet code is as follows bellow. The only thing I do it's look up the sessionBean,
c.lookup("java:global/DemoEJB/ContenedorEJB/BeanStateful!beanssesion.BeanStatefulLocal");
save it, and then use the implemented methods getValor and setValor just to see if the values I send to the EJB Module are saved. But it gets lost because it can't find the BeanStateful even though it's there.
package servlets;
import beanssesion.BeanStatefulLocal;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
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 ServletEJB extends HttpServlet {
BeanStatefulLocal beanStateful = lookupBeanStatefulLocal();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet ServletEJB</title>");
out.println("</head>");
out.println("<body>");
out.println("Enviamos un valor al EJB Stateful: ");
beanStateful.setValor("Valor desde Servlet");
out.println("Valor devuelto " + beanStateful.getValor());
out.println("</body>");
out.println("</html>");
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
private BeanStatefulLocal lookupBeanStatefulLocal() {
try {
Context c = new InitialContext();
return (BeanStatefulLocal) c.lookup("java:global/DemoEJB/ContenedorEJB/BeanStateful!beanssesion.BeanStatefulLocal");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
}
Anyone can help?

As you are using GlassFish 4.1 you will find life simpler if you put all of your classes (including EJBs) in your web module for the time being.
Secondly you rarely need to use explicit JNDI lookups anymore; use injection instead:
public class ServletEJB extends HttpServlet {
#javax.ejb.EJB
BeanStatefulLocal beanStateful;
...
}
BUT, there is a big problem with using stateful session beans like this. This servlet instance will be shared with all clients and so will the EJB that you are injecting/looking up. This will lead to serious concurrency issues.

Related

Getting Exception in Line 1 of my Servlet when starting it in Netbeans 11.3 [duplicate]

This question already has answers here:
#WebServlet fails in Netbeans 11.0 with java.lang.RuntimeException: com.example.NewServlet.<init>(NewServlet.java:1)
(2 answers)
Closed 2 years ago.
Im using Tomcat 9.0.30 and JDK 8 and Netbeans 11.3.
Somehow all my Web-Applications do not start anymore and I did not change anything. They all throw the same exception
Here I auto-generated a servlet and only forwarded a JSP and it still does not work.
package servlets;
import java.io.IOException;
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 = "ExamController", urlPatterns = {"/ExamController"})
public class ExamController extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.getRequestDispatcher("examView.jsp").forward(request, response);
}
#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";
}
}
When I start this class I get this exception:
I fixed it by downgrading my Netbeans to Version 11.1.
I think that Tomcat 9.0.30 and Netbeans with a version higher than 11.2 are not compatible.

ValidateLogin Internal Error 500

I'm attempting to create a login process using JSPs and linking them to my MySQL database. The issue I have encountered is an internal error (500) in my browser after I click "login".
I have setup my web.xml for the servlet ValidateLogin.java and I know that is not the issue. Can someone please help me here? I'll place down my code below that involves my HtmlServlet Request and Response.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ValidateLogin extends HttpServlet {
Connection connect;
ResultSet result;
String username, password, query;
DatabaseConnection database_connection;
protected void processRequest(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UF-8");
PrintWriter out = response.getWriter();
try {
// Code Here...
#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";
}
}
Nevermind, I worked out the issue...
Change code from to...
//FROM
response.setContentType("text/html;charset=UF-8");
//TO
response.setContentType("text/html");

Why does it take so long to update the HttpServletResponse? (Apache Tomcat)

I'm running Apache Tomcat 8 on Eclipse Mars on Windows 7, and here's my piece of code:
import java.io.IOException;
import java.io.PrintWriter;
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("/Main")
public class Main extends HttpServlet {
private static final long serialVersionUID = 1L;
public Main() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("");
pw.println("");
pw.println("");
pw.println("<h1>Example 0</h1>");
pw.println("");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
It starts tomcat, ok, and "Example 0" can be seen when I access localhost. BUT, if I change the string in the response to "Example 1", it takes around 10 min to change it. I'm a beginner in Servlet / Tomcat development, and I'm failing to grasp the reason why the delay occurs. Why that happens??
Not an answer, but I recommend you code web stuffs with Netbeans, there is no doubt Eclipse is the king, but Netbeans does web stuffs better.

HTTP method GET is not supported by this URL

I like to run a servlet on a tomcat server but it gives the error as above.Also when i put ajax request on the servlet it did not working through index.jsp.Please help me friends.
also explain briefly because I am at the starting level of servlet.
import java.sql.Connection;
java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.jdbc.Driver;
import java.util.Arrays;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySQLAccess extends HttpServlet
{
public void getRows(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException
{
String a="";
PrintWriter out = response.getWriter();
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sankar?" + "user=root");
Statement statement = connection.createStatement();
ResultSet resultSet = statement
.executeQuery("SELECT * FROM sankar.datas");
a=resultSet.getString("name");
}
catch (Exception e)
{
e.printStackTrace();
}
out.println(a);
}
}
In order to accept the GET request, you need to override the doGet method in your MySQLAccess servlet class. Considering the code, you may just have to replace the name of your getRows method to doGet. From javadocs
HttpServlet class provides an abstract class to be subclassed to
create an HTTP servlet suitable for a Web site. A subclass of
HttpServlet must override at least one method, usually one of these:
doGet, if the servlet supports HTTP GET requests
doPost, for HTTP POST requests
doPut, for HTTP PUT requests
doDelete, for HTTP DELETE requests
You need the doGet-Method like so:
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// your code
}
This method is called from the server (tomcat container more specifically) when a GET request is sent to the servlet.
If you wish to use POST you need to implement the doPost(...)method, btw.

Communication between two web application in same server

All,
I have 2 web applications, Web1 and Web2, deployed on my tomcat server. I want classes in Web1 to call methods on classes in Web2. One way to do this is using webservice. Is there any other way similar to calling a method on class on same web application ?.
Thanks.
Yes. It is possible. It tried for same servlet container by using
getServletContext().getContext() method.
First you need to make changes in below file
(Windows) C:\Program Files\Apache Software Foundation\Tomcat 7.0\conf\context.xml
Set value of crossContext to true.
context.xml
<Context crossContext="true">
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
</Context>
Please note that crossContext="true".
Suppose you have two web applications with name InterServletComm1 and InterServletComm2
having servlets Servlet1 and Servlet1 in each web application respectively. Then the code in each servlets goes as follows:
Servlet1.java
package interServletComm1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Servlet1
*/
#WebServlet("/Servlet1")
public class Servlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Servlet1() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
request.setAttribute("name", "WebApp1");
ServletContext context = getServletContext().getContext("/InterServletComm2");
RequestDispatcher rd = context.getRequestDispatcher("/Servlet2");
rd.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Servlet2.java
package interServletComm2;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Servlet2
*/
#WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Servlet2() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String name = (String) request.getAttribute("name");
pw.println("This is web application 2.");
pw.println("<br>The value received from web application one is: " + name);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Above code sends attribute name from InterServletComm1 and it is received in InterServletComm2.
Please let me know if this answer is not clear.
Just searched around some articles and the above scenario is certainly possible using CrossContext switching in Tomcat.
Set the following element in context.xml in <Context crossContext="true">
And then getServletContext().getContext("/Web2");.
Haven't tried yet, though.
Yes you can do it using javax.servlet.ServletContext and javax.servlet.RequestDispatcher API's. Here it is how it can be done from Web1:
ServletContext otherContext = servletContext.getContex("/Web2");
RequestDispatcher dispathcer = otherContext.getRequestDispatcher("/a/b.jsp");
dispatcher.forward(request, response);
//or
dispatcher.include(request, response);
Package the classes you want to share between web applications into a separate jar. Put them under common/lib so that the common classloader will load the classes and would be available to both web applications. Then expose the instance in web2 using jndi, look up them from web1 and invoke the methods.
Pretty much it is not that simple. You can share and import classes from your app1 into app2, but maybe they're all linked with other classes. So the idea is not so good except of small services like beans which are used to make calculations for example. There is a reason ppl are using web services so much ;).

Categories

Resources