New to EJB, please help:
To verify my EJB on local, I tried create a test.jsp that calls the EJB like this:
<%# page import="com.web.ejb.service.ContentInfo" %>
<% ContentInfo ci = ContentInfo.getContentById("123"); %>
When run the jsp, got error "Only a type can be imported. com.web.ejb.service.ContentInfo resolves to a package".
Then I replaced the import with
<jsp:useBean id="ContentInfo" class="com.web.ejb.service.ContentInfo" />
but got "ContentInfo cannot be resolved to a type."
Thanks for your help.
From the error message, seems like com.web.ejb.service.ContentInfo is not your class name. Maybe you made a typo ?
If you want to test an EJB more thoroughly, you can use OpenEJB to replicate the functionalities of an EJB server, in case of units tests for example.
First check whether the class name is correct and it is available in the above mentioned package. After that try this:
<%# page import="<package>.<YourBusinessInterface>, javax.naming.*"%>
<%!
try {
InitialContext ic = new InitialContext();
<YourBusinessInterface> obj = (<YourBusinessInterface>)
ic.lookup(<YourBusinessInterface>.class.getName());
} catch (Exception ex) {
// exception code here
}
%>
<html>
<body>
<% obj.callBusinessMethod(); %>
</body>
</html>
This link http://docs.oracle.com/javaee/5/tutorial/doc/bnbnp.html might help you. :)
Related
My aim is to import my class file in my index.jsp and reading over the internet I learned I'm supposed to use JavaBeans.
So here is my class file placed in WEB-INF/classes/jBean/Bucket.class -
package jBean;
import java.sql.* ;
import java.math.* ;
public class Bucket implements java.io.Serializable{
public static void main(String[] args){
Bucket obj = new Bucket();
obj.DBConn();
}
public static void DBConn(){
try{
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/studentfeedback","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next())
System.out.println(rs.getInt("Roll_No")+" "+rs.getString("Name")+" "+rs.getString("Pass"));
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
And here is my index.jsp where I want to import the class file -
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<jsp:useBean id="jBean" class="jBean.Bucket" scope="session" />
</body>
</html>
Doing this I get this error message on executing index.jsp file
java.lang.ClassNotFoundException: org.apache.jsp.index_jsp
So, my query is how shall I import the class file, Bucket.java?
And is there any other way to import the file to index.jsp other than using javBeans?
Please help me with this as I can't find what I'm looking for. Maybe cause I might not be asking the right thing.
All I want to do is import the class file Bucket.java to the index.jsp
May God help the helping soul.
Did you observed your project folder structure.
The classes referenced by the jsp must be in the classpath.
And the classpath includes WEB-INF/classes.
The location of the jsp is of no importance.
question regarding jsp page import and <jsp:useBean id
Now I am working with one of old site that was written using JSP. I see that everywhere in the code used
import ConnectionPool.ConnectionPool;
And I see that CLASSPATH set as:
classpath=%classpath%;C:\j2sdkee1.3\lib\j2ee.jar;C:\Working\Application\MyApp\Bean;
Could you please help understand me where I can search ConnectionPool.class?
May be in C:\Working\Application\MyApp\Bean or in my application directory?
Example of using ConnectionPool in JSP:
<code>
<%# page import="ConnectionPool.ConnectionPool;" %>
<%
application.removeAttribute("MYAPP_POOL");
ConnectionPool pool = new ConnectionPool();
pool.setDriver("sun.jdbc.odbc.JdbcOdbcDriver");
pool.setURL("jdbc:odbc:myapp");
pool.setUsername("Username");
pool.setPassword("Password");
pool.setSize(20);
pool.initializePool();
application.setAttribute("MYAPP_POOL",pool);
%>
</code>
I'm going through this Spring tutorial online form springsource.org.
http://static.springsource.org/docs/Spring-MVC-step-by-step/part2.html
In Chapter 2, at the end, it has you add a bean to prefix and suffix /WEB-INF/jsp/ and .jsp to responses.
The code so far should basically load index.jsp when you go to localhost:8080/springapp/ which will redirect to localhost:8080/springapp/hello.htm which creates an instance of the HelloController which should in theory send you over to /WEB-INF/jsp/hello.jsp. When I added the prefix/suffix bean and changed all my references to just "hello" instead of the fully pathed jsp file, I started getting the following error:
message Handler processing failed; nested exception is
java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/fmt/LocalizationContext
I've tried going back through the samples several times and checking for typo's and I still can't find the problem. Any tips or pointers?
index.jsp (in the root of the webapp:
<%# include file="/WEB-INF/jsp/include.jsp" %>
<%-- Redirected because we can't set the welcome page to a virtual URL. --%>
<c:redirect url="/hello.htm" />
HelloController.java (minus the imports and package:
public class HelloController implements Controller {
protected final Log logger = LogFactory.getLog(getClass());
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String now = (new Date()).toString();
logger.info("Returning hello view with " + now);
return new ModelAndView("hello", "now", now);
}
}
My hello.jsp file:
<%# include file="/WEB-INF/jsp/include.jsp" %>
<!DOCTYPE html>
<html>
<head>
<title>Hello :: Spring Application</title>
</head>
<body>
<h1>Hello - Spring Application</h1>
<p>Greetings, it is now <c:out value="${now}" /></p>
</body>
</html>
It seems like you are missing the JSTL jar here. Try downloading it and place it in your classpath to see if it works: Where can I download JSTL jar
It seems certain required jar(s) are missing from classpath.
Make sure you have servlet-api-2.x.jar jsp-api-2.x.jar and jstl-1.x.jar on classpath
Please make sure the jstl.jar file is located in your WEB-INF/lib folder.
As a matter of fact, here is what is stated in the tutorial that you linked. I guess you missed this step:
We will be using the JSP Standard Tag Library (JSTL), so let's start
by copying the JSTL files we need to our 'WEB-INF/lib' directory. Copy
jstl.jar from the 'spring-framework-2.5/lib/j2ee' directory and
standard.jar from the 'spring-framework-2.5/lib/jakarta-taglibs'
directory to the 'springapp/war/WEB-INF/lib' directory.
I'm using Liferay but I guess it's more of a Spring question.
In Liferay, I'm in a JSP with :
<%#page import="com.liferay.portal.kernel.bean.PortletBeanLocatorUtil" %>
<c:set var="testUtil" value='<%= PortletBeanLocatorUtil.locate("another-web-app-portlet", "com.mycompany.test.Test") %>' />
In the JSP, I can write this JSTL code and this works :
${testUtil.test}
But I can't do this :
<% TestUtil test = PortletBeanLocatorUtil.locate("another-web-app-portlet", "com.mycompany.test.Test"); %>
Because it won't compile of course. TestUtil is not visible to this webapp (and I can't make it visible).
The question is :
How can I call a method in a scriplet on my bean found with BeanLocator?
I would like to do something like :
<% PortletBeanLocatorUtil.locate("another-web-app-portlet", "com.mycompany.test.Test").myMethod("my param value"); %>
How about using Reflection
import java.lang.reflect.*;
<%
//getMethod expects method name along with the type of arguments - in this example it's expecting single parameter of type String
Method m = PortletBeanLocatorUtil.locate("another-web-app-portlet").getClass().getMethod("myMethod", String.Class ...)
m.invoke(PortletBeanLocatorUtil.locate("another-web-app-portlet"), new Object[] { new String("blah") });
%>
I've got a .jsp file that is working fine. It's maybe a bit special in that it is calling a factory (ArticlesFactory) that returns a singleton (but that is a detail) of class Articles (it does so by automatically fetching shared Google Docs that are transformed to html and then stored into ".../text/en" but that is a detail too).
The following is working fine: it does exactly what I need, it fetches the articles automatically and I can access my Articles instance fine.
<%# page pageEncoding="UTF-8" contentType="text/html;charset=utf-8" %>
<%# page import="com.domain.projectname.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en">
<head></head>
<body>
<% Articles articles = ArticlesFactory.create( getServletContext().getRealPath( "text/en" )); %>
We have <%= articles.getNbItems()%>
</body>
</html>
However, I must transform it to some notation I don't know nor understand, I'm not even sure what the name for that is and obviously I've got some issue.
I don't know if it's a namespace issue or if there's a problem with the ArticlesFactory factory's static factory method creating the Articles singleton:
<?xml version="1.0" encoding="UTF-8"?>
<jsp:root version="2.0" xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:c="urn:jsptld:http://java.sun.com/jsp/jstl/core">
<jsp:directive.page import="com.domain.project.ArticlesFactory"/>
<jsp:directive.page contentType="text/html; charset=UTF-8" />
We have ${variable.nbItems} <!-- What to put here !? -->
</jsp:root>
I tried many things and couldn't figure it out.
Basically I need to:
- call the static create method from the ArticlesFactory class
- by passing it the result of getServletContext().getRealPath( "text/en" ))
(which should give back an Articles instance)
then I want to put the result of getNbItems() in a variable that I want to display
Note that I don't want to have to call getServletContext from any servlet/dispatcher: I want to do it just like in the first working example (ie directly from inside the .jsp).
You're basically looking for "JSP in XML syntax". Most is already explained in this (old) tutorial. You yet have to replace <% %> by <jsp:scriptlet> and <%= %> by <jsp:expression>.
The xmlns:c namespace is by the way unnecessary here, unless you'd like to use any of the JSTL core tags.
The Expression Language (those ${} things) which is explained in this (also old) tutorial is by the way a separate subject. It only acts on objects in the page, request, session or application scope. In scriptlets however, variables are only defined in local scopes (methodlocal actually), those aren't available in EL. You would need to do the following in the scriptlet to make it available in EL:
pageContext.setAttribute("articles", articles); // Put in page scope (recommended).
request.setAttribute("articles", articles); // Or in request scope. Also accessible by any include files.
session.setAttribute("articles", articles); // Or in session scope. Accessible by all requests in same session.
application.setAttribute("articles", articles); // Or in application scope. Accessible by all sessions.
This way it's available by ${articles} in EL.