Can servlet access Serializable Bean ?
This is my bean below.. My jsp pages can access this bean but my servlet cannot... Do I need to make remove the Serializable interface that I am implementing right now so servlet can access ? Can serlvet access beans ?
import java.io.*;
import java.sql.*;
import javax.sql.*;
import java.util.*;
* Re-usable database connection class
public class ConnectDB implements Serializable{
// setup connection values to the database
static final String DB_DRIVER = "";
static final String myURL = "";
static final String USERNAME = "";
static final String PASSWORD = "";
static Connection con = null;
public ConnectDB(){}
/* Returns a connection the file that calls the method*/
public static Connection getConnection()
try
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("......");
catch (Exception e)
e.printStackTrace();
finally
return con;
/*Closes Connections*/
public static void closeConnection(Connection con)
try
if (con != null)
con.commit();
con.close();
catch (Exception e)
e.printStackTrace();
}
A Servlet is just a Java class and so can access beans. Also, a JSP is translated to a servlet before execution so you already have a servlet accessing the bean.
Can you post relevant code and error message?
Similar Messages
-
Can't access a Bean from a JSP page !
Hello everybody,
I work with Oracle 8i 8.1.7, it means Oracle HTTP Server + Oracle JSP 1.1.0.0.0. But i don't use the Oracle Servlet Engine.
In this context, i try to load ` JSP page, which instantiate a Bean. But it is impossible to access to this bean !...
1) In jserv.properties file, i have mentionned the CLASSPATH to beans directory, as said in the OracleJSP documentation :
wrapper.classpath=D:\...\myBeansDirectory\
2) i have copied the .class file of my bean in the bean directory ...
So did i forget something ?
Seeking desperatly help !
Thanks.Hi,
Did you restart the HTTP listener after adding the CLASSPATH to the jserv.properties file? The change in jserv.properties (and in any other configuration files) will take effect only after the listener is restarted.
Good luck,
Srinivas. -
Client can't access Serializable classes on Server
Hi there, i have created a very simple client server model and had it running fine. I then added a new serializable class to the server and return it in a new method. Now when i try to run that method on the client side it complains it cannot find my new serializable class ("no class def found exception: rmi/server/ServerObject.class"). This is how it's setup at the moment:
Server
-ServerFront extends Remote
-Server implements ServerFront
-ServerObject implements Serializable
The server binds itself to the registry as such:
ServerFront engine = new Server();
String name = "Server";
ServerFront stub = (ServerFront)UnicastRemoteObject.exportObject(engine, 0);
Registry registry = LocateRegistry.getRegistry();
registry.rebind(name, stub);The ServerObject class looks like this:
public class ServerObject implements Serializable
private static final long serialVersionUID = 10L;
//methods
}The ServerFront interface has a method as such:
ServerObject getServerObject () throws RemoteException; Client
-Client
The client gets a reference to the server as follows:
String name = "Server";
Registry registry = LocateRegistry.getRegistry("127.0.0.1");
server = (ServerFront)registry.lookup(name);Then tries to run the getServerObject() method:
ServerObject = server.getServerObject();I run the client and server from jar files using the following commands:
start java -Djava.rmi.server.codebase="http://www.xenwars.com/Server.jar" -Djava.security.policy=security.policy -jar Server.jar
java -Djava.security.policy=security.policy -jar Client.jar"security.policy" allows all access, and the codebase URL points to my webserver where i uploaded an identical copy of the Server jar file that i'm trying to run.
So... i've read all the Sun documentation and such and i'm massively confused why my client isn't simply downloading the serializable class as it's supposed to. Any help is massively appreciated, thanks :D
Edited by: Aldarn on Feb 8, 2009 10:03 AM
Edited by: Aldarn on Feb 8, 2009 10:05 AMBy a mirrored interface i mean i just created an interface based off my existing serializable classes, i.e. copied the method constructors into an interface class and made the serializable class implement that interface.
I think that must have been the problem then, that i wasn't giving the client an interface to the serializable classes on the server that it was attempting to download. I thought by using RMI on a serializable class it would just download that class when it needs it and so wouldn't need an interface pre-defining it.
Thanks for the help! I'm now working on a system with 3 servers and one client, where two servers have various methods implemented and the third one acts as a bridge between the other two servers and the client - so the client only has to deal with one server. It's working fine but it's pretty annoying having to mirror all the methods from both servers' interface classes in the server that acts as a bridge's interface class - is there any way that the bridge server can inherit the other two servers interfaces into its own so i don't need to make loads of duplicate "shell" methods like this:
// second server
public ArrayList<Thing> getAllThings ()
return things;
// bridge server
private SecondServerFront secondServer; // reference loaded in constructor
public ArrayList<Thing> getAllThings () throws RemoteException
return secondServer.getAllThings();
} -
hi all,
i wanna discuss some this. can i serialize a servlet.
thanks
RaviOff course you can, the only thing you should ask youself is wheather it makes sense or not to do it.
MeTitus -
Accessing Managed Bean Variables in Entity Impl Class
How can I access managed bean variables in the entity Impl class .
While inserting a new record in DB , i want to set few entity properties values . The values of those properties are available in the managed bean .
How can i access those values from Managed Bean and set them the entity Impl class to override the create method.
Or is there any better recommended approaches ?
Jdev - 11.1.1.5>
While inserting a new record in DB , i want to set few entity properties values .
>
you can user CreateWithparams
http://www.oracle.com/technetwork/developer-tools/adf/learnmore/13-create-with-params-169140.pdf
http://andrejusb.blogspot.com/2011/02/createwithparams-operation-for-oracle.html -
Accessing managed-bean in a JSP (portal theme).
I have a tricky situation where I need to access a managed-bean outside a JSF jsr 168 api portlet. Now I need to reference the bean in the themes jsp (just fyi themes loosely relate to JSP's which control the look and feel, navigation within portal page). I was thinking of a way to set a managed-bean variable in the jsp before the portlet where the managed-bean is declared. Is this possible ? Any ideas ?
You can just access managed beans using JSTL EL.${myBean}or if you strictly want to specify the scope, e.g. session scope${sessionScope.myBean}where "myBean" is the managed bean name. Keep in mind that you cannot use this in input elements, but only in output elements. If you want to use this in input elements, then you should be using JSF components with deferred EL #{myBean.input} and so on.
-
Accessing Managed Beans from Code
Hi,
How can I access managed beans from my code? I am too new to JSF to know if what I am doing is right from a design perspective. But what I am trying to do is to use Actions as sort of a Web Facade that aggregates state from other beans (all of them Managed beans right now) to build up state that is necessary for displaying pages.
Thanks for you help
SuhailJust answering my own question. The answer was given in a different thread (http://forum.java.sun.com/thread.jsp?forum=427&thread=427057&message=1901909#1901909) . JSF has provided various Factories (look at the FactoryFinder API) that allow one I presume to access the internal state of a FacesContext. One of the factory is ApplicationFactory. This factory from what I can make out essentially gives you access to everything (actionlisteners, navigationhanlder,components etc) in you application. My original question was about accessing something (for some reason) named ValueBinding. I can access the managed beans declared in my faces-config.xml by invoking getValue(facesContext). I can naturally also set the value of a bean by invoking setValue(...). I just needed the getValue and it seems to work.
Ofcourse keep in mind that the underlying managed bean will not necessarily be initialized when you access it so test for nullness. As a general rule I think its best not to create the beans but access them using this facility. After all its not for nothing these are called Managed Beans.
Now if only the faces implementation would persist the changes to Navigation hanlders that one makes in the code ;-) -
I can't access able to compile the servlet that access EJB methods
Hello,
i have written i servlet (TestServlet.java) to access the ejb(SignOn) method(validateUser(userId,Password)) but i can't compile this servlet.it shows this type error.can anybody help me to do it complete.i have written the ejb & servlet in (d:\ejb\src\demo).
D:\riazejb\src\demo>javac TestServlet.java
TestServlet.java:15: cannot find symbol
symbol : class SignOnHome
location: class demo.TestServlet
SignOnHome signOnHome;
^
TestServlet.java:16: cannot find symbol
symbol : class SignOn
location: class demo.TestServlet
SignOn signOn;
^
TestServlet.java:23: cannot find symbol
symbol : class SignOnHome
location: class demo.TestServlet
signOnHome = (SignOnHome)PortableRemoteObject.narrow(objref,SignOnHome.c
lass);
My servlet code is
package demo;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import javax.naming.*;
import javax.ejb.*;
import demo.*;
import javax.rmi.PortableRemoteObject;
public class TestServlet extends HttpServlet {
SignOnHome signOnHome;
SignOn signOn;
public void init(ServletConfig config) throws ServletException {
//Look up home interface
try {
InitialContext ctx = new InitialContext();
Object objref = ctx.lookup("demo/SignOn");
signOnHome = (SignOnHome)PortableRemoteObject.narrow(objref,SignOnHome.class);
} catch (Exception NamingException) {
NamingException.printStackTrace();
public void doGet (HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
PrintWriter out;
response.setContentType("text/html");
String title = "EJB Example";
out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello World Servlet!</title>");
out.println("</head>");
out.println("<body>");
out.println("<p align=\"center\"><font size=\"4\" color=\"#000080\">Servlet Calling Session Bean</font></p>");
try{
// MyTestSession beanRemote;
SignOn signOn;
signOn = (SignOn)signOnHome.create();
out.println("<p align=\"center\"> Message from Session Bean is: <b>" + signOn.validateUser(student,password) + "</b></p>");
signOn.remove();
}catch(Exception CreateException){
CreateException.printStackTrace();
out.println("<p align=\"center\"><a href=\"javascript:history.back()\">Go to Home</a></p>");
out.println("</body>");
out.println("</html>");
out.close();
public void destroy() {
System.out.println("Destroy");
Thanks in advance.
RiazHave you added the EJB client JAR to classpath for compilation?
java -classpath "%CLASSPATH%;<<EJBCLient JAR path>> *.java -
Hi,
I know I can use
<jsp:useBean>to create and access named Bean objects in my application from JSP. But I would like to create a named Bean object from a servlet and store it in the session scope, so that my JSPs can access this later.
How do I instantiate a named bean in a servlet?
Thanks!MyBean myBean = new MyBean();
session.setAttribute("myBean", myBean);
Now you can access the bean in a JSP using:
<jsp:useBean id="myBean" scope="session" class="MyBean" /> -
I hv err on accessing my bean class to a servlet class, plz guide me.
the error is "import com.Bean" is not exit, and can not access "Bean.class".
in this case, your compiler is not lying to you. the class com.Bean doesn't exist
-
Running netscape servlet access a weblogic deployed bean
I an having problems creating the initialcontext object when tring to access a
bean deployed in
Weblogic6.0 from a servlet running in netscape Iplanet server. Has anyone every
got this to work?
Is this a valid configuration or does the servlet have to be running in the weblogic
server.
Thanks DougI an having problems creating the initialcontext object when tring to access a
bean deployed in
Weblogic6.0 from a servlet running in netscape Iplanet server. Has anyone every
got this to work?
Is this a valid configuration or does the servlet have to be running in the weblogic
server.
Thanks Doug -
Can the servlet access ejb by ejb's local home?
if yes, what is required?
I have a similar problem. I have a ServiceLocator that looks up HomeInterfaces (Local and Remote) for SEJB's and EEJB's. But it only works for RemoteHomeInterfaces. My guess is that you can only access these local interfaces if you're in the same VM. JBoss uses another VM than your client. I'm still looking for a solutions for my problem but i'm not sure if it's worth it.
-
NON-transactional session bean access entity bean
We are currently profiling our product using Borland OptmizeIt tool, and we
found some interesting issues. Due to our design, we have many session beans which
are non transactional, and these session beans will access entity beans to do
the reading operations, such as getWeight, getRate, since it's read only, there
is no need to do transaction commit stuff which really takes time, this could
be seen through the profile. I know weblogic support readonly entity bean, but
it seems that it only has benefit on ejbLoad call, my test program shows that
weblogic still creates local transaction even I specified it as transaction not
supported, and Transaction.commit() will always be called in postInvoke(), from
the profile, we got that for a single method call, such as getRate(), 80% time
spent on postInvoke(), any suggestion on this? BTW, most of our entity beans are
using Exclusive lock, that's the reason that we use non-transactional session
bean to avoid dead lock problem.
ThanksSlava,
Thanks for the link, actually I read it before, and following is what I extracted
it from the doc:
<weblogic-doc>
Do not set db-is-shared to "false" if you set the entity bean's concurrency
strategy to the "Database" option. If you do, WebLogic Server will ignore the
db-is-shared setting.
</weblogic-doc>
Thanks
"Slava Imeshev" <[email protected]> wrote:
Hi Jinsong,
You may want to read this to get more detailed explanation
on db-is-shared (cache-between-transactions for 7.0):
http://e-docs.bea.com/wls/docs61/ejb/EJB_environment.html#1127563
Let me know if you have any questions.
Regards,
Slava Imeshev
"Jinsong HU" <[email protected]> wrote in message
news:[email protected]...
Thanks.
But it's still not clear to me in db-is-shared setting, if I specifiedentity
lock as database lock, I assumed db-is-shared is useless, because foreach
new
transaction, entity bean will reload data anyway. Correct me if I amwrong.
Jinsong
"Slava Imeshev" <[email protected]> wrote:
Jinsong,
See my answers inline.
"Jinsong Hu" <[email protected]> wrote in message
news:[email protected]...
Hi Slava,
Thanks for your reply, actually, I agree with you, we need to
review
our db
schema and seperate business logic to avoid db lock. I can not say,guys,
we need
to change this and that, since it's a big application and developedsince
EJB1.0
spec, I think they are afraid to do such a big change.Total rewrite is the worst thing that can happen to an app. The
better aproach would be identifying the most critical piece and
make a surgery on it.
Following are questions in my mind:
(1) I think there should be many companies using weblogic serverto
develop
large enterprise applications, I am just wondering what's the maintransaction/lock
mechanism that is used? Transional session / database lock,
db-is-shared
entity
I can't say for the whole community, as for my experience the standard
usage patthern is session fasades calling Entity EJBs while having
Required TX attribute plus plain transacted JDBC calls for bulk
reads or inserts.
is the dominant one? It seems that if you speficy database lock,
the
db-is-shared
should be true, right?Basically it's not true. One will need db-is-shared only if thereare
changes
to the database done from outside of the app server.
(2) For RO bean, if I specify read-idle-timeout to 0, it shouldonly
load
once at the first use time, right?I assume read-timeout-seconds was meant. That's right, but if
an application constantly reads new RO data, RO beans will be
constantly dropped from cache and new ones will be loaded.
You may want to looks at server console to see if there's a lot
of passivation for RO beans.
(3) For clustering part, have anyone use it in real enterpriseapplication?
My concern, since database lock is the only way to choose, how aboutthe
affect
of ejbLoad to performance, since most transactions are short live,if high
volume
transactions are in processing, I am just scared to death about
the
ejbLoad overhead.
ejbLoad is a part of bean's lifecycle, how would you be scared ofit?
If ejbLoads take too much time, it could be a good idea to profile
used SQLs. Right index optimization can make huge difference.
Also you may want cosider using CMP beans to let weblogic
take care about load optimization.
(4) If using Optimization lock, all the ejbStore need to do
version
check
or timestamp check, right? How about this overhead?As for optimistic concurrency, it performs quite well as you can
use lighter isolation levels.
HTH,
Slava Imeshev
"Jinsong Hu" <[email protected]> wrote in message
news:[email protected]...
We are using Exclusive Lock for entity bean, because of we do
not
want
to
load
data in each new transaction. If we use Database lock, that means
we
dedicate
data access calls to database, if database deadlock happens,
it's
hard
to
detect,
while using Exclusive lock, we could detect this dead lock in
container
level.
The problem is, using Exclusive concurrency mode you serialize
access to data represented by the bean. This aproach has negative
effect on ablity of application to process concurrent requests.As
a
result the app may have performance problems under load.
Actually, at the beginnning, we did use database lock and usingtransactional
The fact that you had database deadlocking issues tells that
application logic / database schema may need some review.
Normally to avoid deadlocking it's good to group database
operations mixing in updattes and inserts into one place so
that db locking sequence is not spreaded in time. Moving to
forced serialized data access just hides design/implementation
problems.
session bean, but the database dead lock and frequent ejbLoad
really
kill
us,
so we decided to move to use Exclusive lock and to avoid dead
lock,
we
change
some session bean to non-transactional.Making session beans non-transactions makes container
creating short-living transactions for each call to entity bean
methods. It's a costly process and it puts additional load to
both container and database.
We could use ReadOnly lock for some entity beans, but since weblogicserver will
always create local transaction for entity bean, and we found
transaction
commit
is expensive, I am arguing why do we need create container leveltransaction for
read only bean.First, read-only beans still need to load data. Also, you may seeRO
beans
contanly loading data if db-is-shared set to true. Other reason
can
be
that
RO semantics is not applicable the data presented by RO bean (forinstance,
you have a reporting engine that constantly produces "RO" data,
while
application-consumer of that data retrieves only new data and neverasks
for "old" data). RO beans are good when there is a relatively stable
data
accessed repeatedly for read only access.
You may want to tell us more about your app, we may be of help.
Regards,
Slava Imeshev
I will post the performance data, let's see how costful
transaction.commit
is.
"Cameron Purdy" <[email protected]> wrote:
We are currently profiling our product using Borland
OptmizeIt
tool,
and we
found some interesting issues. Due to our design, we have
many
session
beans which
are non transactional, and these session beans will access
entity
beans
to
do
the reading operations, such as getWeight, getRate, since
it's
read
only,
there
is no need to do transaction commit stuff which really takes
time,
this
could
be seen through the profile. I know weblogic support readonly
entity
bean,
but
it seems that it only has benefit on ejbLoad call, my test
program
shows
that
weblogic still creates local transaction even I specified
it
as
transaction not
supported, and Transaction.commit() will always be called
in
postInvoke(),
from
the profile, we got that for a single method call, such as
getRate(),
80%
time
spent on postInvoke(), any suggestion on this? BTW, most of
our
entity
beans are
using Exclusive lock, that's the reason that we use
non-transactional
session
bean to avoid dead lock problem.I am worried that you have made some decisions based on an improper
understand of what WebLogic is doing.
First, you say "non transactional", but from your description
you
should
have those marked as tx REQUIRED to avoid multiple transactions
(since
non-transactional just means that the database operation becomesits
own
little transaction).
Second, you say you are using exclusive lock, which you shouldonly
use
if
you are absolutely sure that you need it, (and note that it
does
not
work in
a cluster).
Peace,
Cameron Purdy
Tangosol, Inc.
http://www.tangosol.com/coherence.jsp
Tangosol Coherence: Clustered Replicated Cache for Weblogic
"Jinsong Hu" <[email protected]> wrote in message
news:[email protected]...
> -
I am trying to access a java bean through a servlet..
the bean is defined in the package com.mycomp
when i use this bean using test.jsp it works fine it finds the package com.mycomp.. but when i am using the Servlet it cannot find the package...when i am trying to compile the servlet it says it cannot resolve the symbol class ConnectionBean
it cannot find the package com.mycomp
your help will be appreciatied....
here is the structure of files:
tomcat
webapps
myapp
jsp
-test.jsp
WEB-INF
classes
-PropertyServlet.java
-PropertyServlet.class
-ConnectionBean.java
com
mycomp
-ConnectionBean.class
I have tried importing in the servlet import com.mycomp.*; but i still get an error com.mycomp not found...
I have also tried importing the class itself by import com.mycomp.ConnectionBean;
I still get the package com.mycomp not found;
is there any xml file or anything that i need to edit so servlets can read the packages located in classes folder?me also same problem...
this class path is included in server itself..
or we can set during compiling time...
then this is my compile.bat file please check
set classpath=%CLASSPATH%; ./WEB-INF/classes;
@echo off
javac -d ./WEB-INF/classes/ ./dev/beans/*.java
javac -d ./WEB-INF/classes/ ./dev/ContentManagement/beans/*.java
javac -d ./WEB-INF/classes/ ./dev/servlets/*.java
and my servlet file like this below..
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.deploy.servlet.*;
public class ControlServlet extends HttpServlet
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Testing");
/* if (request.getParameter("pageName")=="CEOSpeak")
CEOBean CB = new CEOBean();
if (request.getParameter("actionType")=="add")
else if (request.getParameter("actionType")=="edit")
else if (request.getParameter("actionType")=="delete")
if(CB.deleteCEO(request.getParameter("CEOId")))
response.sendRedirect("CEO_Speaks.jsp"); -
My question is about high level design. I've written some JSP pages and some very simple JavaBeans that work on Tomcat.
Now I'm trying to design a Database access layer
I want to have a connection pool class and some other business logic classes communicating with each other.
How can I start a bean and keep it running and how do I access its methods from other beans?
Is this even feasible?
if I declare the scope of the bean as the application would I have to put it in all the pages of the web site or not?
Also, should I just forget about JavaBeans and do Servlets? Maybe EJB is better for this?
Please provide some examples in your answer if possible.
Thanks,
David AMy question is about high level design. I've written
some JSP pages and some very simple JavaBeans that
work on Tomcat.
Now I'm trying to design a Database access layerThe design and implementation of a persistence layer has nothing at to do with how the data is eventually displayed. Persistence is the same whether you use a Web or a Swing interface, so the question about Tomcat is moot.
I'd look at Martin Fowler's "Patterns of Enterprise Application Architecture" for its chapter on persistence or the Hibernate object/relational mapping tool.
I want to have a connection pool class and some other
business logic classes communicating with each other.Personally, I prefer to let Tomcat handle the database connection pool. I use the Commons DBCP class and configure my connections that way. Then I have my Java code do a JNDI lookup to access them, do the required database operation, and then close the connection to return it to the pool.
How can I start a bean and keep it running and how do I access its methods from other beans?
Is this even feasible? I'm not sure I know what you mean by "start a bean and keep it running". HTTP is a request/response, stateless protocol. You should think about operations as being initiated by a request and then going out of scope once the response is generated, much like the protocol itself. You don't keep a bean running in that case.
if I declare the scope of the bean as the application would I have to put it in all the pages of the web
site or not?You have to <jsp:useBean> in every page that needs it. Whether or not application scope is really appropriate or necessary is another matter.
Also, should I just forget about JavaBeans and do Servlets? You can and should use JSP for View, a servlet as your front controller, and JavaBeans to do the work in the back. It's not an either/or question. You really should be using all three.
Maybe EJB is better for this?You use EJBs if you have a highly transactional, distributed, clustered application. If none of those things apply to you, there's no reason why you must use EJBs.
Have a look at the Struts and Spring frameworks.
Maybe you are looking for
-
Help! Using multiple ipods on same account - for education
Hi, I'm a primary school teacher and have just purchased 5 ipods to use with Year 2 students in the classroom. Is there any way of syncing the songs and/or short movies to all 5 ipods? I don't mind paying for these things once but not 5 times each ti
-
Hi everyone, My logic in prepareForDML() updates some attributes (shown in the snippet below) based on whether an insert or update is taking place. But, when I delete a line, I get the following error: JBO-27101: Attempt to access dead entity in EO.
-
Importing Audio from a DVD Concert
I want to import the audio from a DVD concet into iTunes. I've tried MactheRipper and MAC3dec to do the conversion but the main concert file was 1 hour and 15 minutes long and it only imported the intro which lasted about 45 seconds. What I'd really
-
SDO_TOPO_MAP.GET_EDGE_ADDITIONS
Before any topo manipulation I have... SQL> select count(*), max(edge_id) from mgf_test_edge$; COUNT(*) MAX(EDGE_ID) 19844 19844 I create and load a topo_map... SQL> EXECUTE sdo_topo_map.create_topo_map('MGF_TEST', 'my_topo_map_cache'); PL/SQL proced
-
Refreshing Webservices in Search (caching problem?)
Hi, I've developed some EJBs and deployed them to the WAS. I then created a WSIL Destination in NWA. In Visual Composer I see the methods in my Search Pane no prolem. I have since added 2 new methods to my service, deployed them, and tested them in W