Give all servlet capabilities to a normal java class
am new to servlets, i have one servlet class only, say index.java, in this servlet i have overridden its doGet/doPost where in those methods i just
create an instance of a normal java class say MyClass, am looking to make MyClass to have same capabilities like my index servlet, in other words
am wondering what parameters i need to pass to the MyClass constructor so that MyClass can do all what the index servlet does?
for the time been i am passing the HttpServletRequest and HttpServletResponse, but later i have a situation that i needed to know the path for a file
where i found that i should use ServletContext.getRealPath, so i found that extra ServletContext that should be passed to MyClass, so what exactly i need
to pass to MyClass so that it has all servlet functionalities?
Dariyoosh wrote:
akkadation wrote:
am wondering what parameters i need to pass to the MyClass constructor so that MyClass can do all what the index servlet does?so that MyClass can do all what the index servlet does = MyClass is also a servlet (maybe even the same servlet)There is one instance of the servlet which is created once, after that there are threads launched for different sessions, therefore this may not be thread-safe for what you want to do.
You may want to review your application architecture.isnt the servlet thread-safe in its nature?
Similar Messages
-
In terms of scalabilty, will static method in normal java class better than
You only have one copy of the static method in memory, but you have a few copy of the stateless session bean, plus the overhead of those session bean.So isn't static method of normal java class more scalable than stateless session bean.
Then you have to take care of transaction management, connection pooling, etc other ejb services all by your self.
In fact stateless session beans acts more like a static class. They do not get destroyed when remove() method is called on client stub. Similarly they are not always gets created whenever someone calls create() method on home interface!! (Again it's specific to appserver implementation)
Thx. -
Call Bean from normal java class
Dear Friends,
Is it ok to call an entity bean or session bean frm normal Java class.
(Java class is in the same application as the beans).
Is there a special way to lookup the beans from normal java classes.
Thanking You,
Chamal.it is ok and very commonly done.
Note that the simple java program must be running in the same local network. You cannot have the java program and EJBs distributed over internet. (I m not certain of it, but mostly I shoudl be correct. If you have the resources, try it out and let me know)
In most of the cases, EJBs are called by
1. A servlet
2. Another EJB
3. a simple java program.
In the first 2 cases, you can go for Local Interfaces (more so in the second case than the first). The reason being that the the client and server will be in the same JVM (typically the Application server). Thus, in the first case, if the Web container and the ejb container are in the same app server, EJBs can be local.
However, in the third case, it is unlikey that you will have the client runnng and the same jvm as the server, because the app server has its own jvm.
sample code (this method is being called from the main method of a simple java program. it is self explanatory):
public void processRequestForSessionBean()
System.out.println("REQUEST RECEIVED");
try
Hashtable nameHashtable = new Hashtable();
nameHashtable.put( Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory" );
nameHashtable.put( Context.PROVIDER_URL, "t3://localhost:7001" );
InitialContext context = new InitialContext(nameHashtable);
System.out.println("created initial context");
Object lookupObject = context.lookup("CustomerBean");
System.out.println("Got the lookup object");
CustomerDataHome home = (CustomerDataHome) PortableRemoteObject.narrow(lookupObject,
Class.forName("com.shiv.business.CustomerDataHome"));
System.out.println("Home interface");
customerData = home.create();
System.out.println("Remote Interface");
addDataToSB(customerData);
ArrayList namesList = customerData.getNames();
System.out.println(namesList.toString());
//customerData.remove();
catch (Exception exception)
System.out.println("FATAL ERRORS");
exception.printStackTrace();
} -
Using normal java classes to access database
Dear friends,
Is it a good practice to make database calls from a normal java class within J2EE environment.
What I meant by a normal java class is a class which is not an enterprise bean.
Best Regards,
Chamal.it is quite normal.
If you make your own DAOs, it may not be efficient/generic.
JSP/Servlets can use Hibernate (which is a set of POJOs) to access DB. Thus you have a J2EE environment using a very matured DB access methodoloy, and doing away with Enterprise bean.
regards -
Access a normal java class from EJB
how can i access normal java class from an EJB.
I do not want to write the business logic inside the EJB. How can I achieve this.There's no special API for doing this. Just use normal java. E.g.
@Stateless
public class FooBean implements Foo {
public void foo() {
// access non-EJB utility class Bar
Bar b = new Bar();
b.bar();
} -
User Defined Function is not recognizing java class in IR.
Hi All,
i have written one normal java class, and i imported that java class into IR using imported Archive as a .jar file,
it will add just two values .
now in message mapping i created one user defined function in that
iam trying to call this java class. while testing it is showing error as cannot resolve symbol java class name
so experts please help me in this or it would be appreciate if any one will provide
step by step process of one java class and one USD just to add two numbers.
thanks in advance,
jasmine .Hi,
The steps are as follows:
1) Create a java file with .java extension.
2)Compile it to create a .class file.
3) Create a zip file for this .class file using any compressed archive program(ex-winrar)
4) Upload this zip file as an imported archive ,save and activate.
When you go to this archive,below , you can see your .class file with the older path,for below ex:
ObjRecord.class jxl/biff/drawing/
you have to give following entry in imports section:
jxl.biff.drawing.ObjRecord;
Please try this and let us know if this works.
Thanks.
Regards,
Shweta -
Communication between 2 servlets/java classes.
Hi,
Ive a problem. Not sure if its a simple one.
I have a web app with servlets (say Servlet1, Servlet2, etc.) in it. I use a SQL query in Servlet1 and fetch an employees information (say empinfo) from the database. This is a string value. Now, I need to pass this empinfo to Servlet2.
I might sound dumb till here but please continue till the end to know what I still have to say
1. I tried using getters and setters. Servlet2 has the empinfo value I need. This is the first time Servlet2 is accessed.
2. But, think that Servlet1 is transferring the control to an html page. And, this html page submits its parameters (say manager) to Servlet2. And, when this html passes its control to Servlet2, the empinfo value I need is gone because I used empinfo as a class member/global.
3. So, when the control enters the Servlet2 the second time everything is lost and this is when I need the empinfo value.
4. I cannot make the empinfo value in Servlet2 static because it keeps changing.
Note: I tried with all these: httpsession, reflection, etc. but nothing seems to fulfill my task.
Actually, Servlet2 lets the users to download the empinfo when a link on the html page (which sends the parameters to this servlet) is clicked.
I used httpsession to store this empinfo in Servlet1 and used to grab the value in Servlet2.
Then, I ran this app on my localhost. Then:
Step1: I opened up one browser and when I clicked the link on html, I checked the empinfo value. It was fine.
Step2: I opened up another browser and when clicked the link on html, I checked the empinfo value. It worked again.
Step3: Now, I went back to the html page in the browser1 and clicked the link and checked to see the empinfo value and now it has the value of that in browser2.
The empinfo always had the latest value. Previous values are overwritten.
If I could find a way to cache the Servlet1 object to use it in Servlet2 then I think my job is half done because even if I let Servlet2 keep a reference of the Servlet1, the html page is ruining the desired result.
If anyone can let me know how to do this with normal Java classes even that works for me.
Thanks in advance.Thanks for the reply.
Actually, when I used the session the IE browser behaved properly and its the FireFox that was weird.
I think this is because Firefox uses single cookie for many instances of itself.
Thanks again. -
Calling Servlet from Java-Class
Hi,
I have a normal java-class that is working with request/response Objects. From within this class I want to call a local servlet, let it do some work with the request and the response and then return it to the class.
I guess the RequestDispatcher can only be called from within a Servlet, but my class is not a servlet.
The getServlet()-method is not working any more.
Maybe somebody has an idea.
Thanks a lot,
MatthiasHi,
I have a normal java-class that is working with
request/response Objects. From within this class I
want to call a local servlet, let it do some work with
the request and the response and then return it to the
class.
I guess the RequestDispatcher can only be called from
within a Servlet, but my class is not a servlet.
The getServlet()-method is not working any more.
Maybe somebody has an idea.
Thanks a lot,
MatthiasThis is not very pretty, so I think you should redessign, but you can open a URLConnection from your class pointing to the URL of the servlet. As far as I know you can't invoke a servlet directly, because you can't get a reference to it, it can only be invoked by the container... -
Creating an application module in a Java class
Hi everyone,
I'm trying to create an application module from a normal Java class where I don't have access to any HttpSession objects.
I tried to use the method in the documentation
appMod = Configuration.createRootApplicationModule(
"full.class.Name",
"ConfigurationName");
It's not working though, complaining that it can not find the configuration file which it's trying to locate at full/class/common/bc4j.xcfg.
This file exists at the same path in the BC4J project which this project has a dependency on in the Project Settings dialog.
Is this the right way to create an application module? Can someone please provide a reference to an example.
ThanksThanks Frank, but this example is about a stand-alone application, my problem occurs with an application hosted on the application server.
I did more experiments and came up with some ideas but unfortunately, I hit a dead end.
I thought that in order to work around the fact that I cannot set the class loader of the timer, I could change the class loader of the running thread before I create the timer as follows:
Thread.currentThread().setContextClassLoader(
this.getClass().getClassLoader());
I thought this would give me a SecurityException for sure, but strangely enough it worked perfectly.
Now, all I needed was to move this code from the JSP to my listener. Unfortunately, it didn't work in the listener, also a test that I did in the JSP to make sure that the classloader before and after the above statment is different, showed that in the listener, the classloader of the thread is the same as the one used to load the listener class:
System.out.println(Thread.currentThread().getContextClassLoader()
.equals(this.getClass().getClassLoader()));
I thought, maybe this is a listener thing, but if I do it in the init() method of a servlet that I could specify to load on startup, it could work, but still, it didn't.
I cannot understand, why is it that the only correct class loader is the one used to load the compiled JSP class?!
Does anyone have any other ideas?
Thanks -
AES Algorithm error when trying to encrypt using stored Java class.
Dear All,
We have a specific reuirement where in we cannot use DBMS_CRYPTO package to encrypt/decrypt data using AES Algorithm
So I am trying to use a stored Java class and I am getting "AES algorithm not available".
I am using Oracle 10gR2 standard edition.
Below is my code
1. Stored Java class
2. Stored function to access the above Java class.
3. Test anonymus PL/SQL to test above code.
Please help me finding the problem why I am getting "AES algorithm not available" error when I call stored Java class in Oracle.?
**** If I use "DES" algorithm, it works. Also the Java code works well if I execute it as normal Java class from Eclipse.
I verified the java.security file in jre/lib/security and I see that there is provider entry for SunJCE.
The jre version in Oracle is 1.4.2.
I appreciate your help.
Thanks,
Priyanka
Step1: Stored java class to encrypt and decrypt data
CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "EncryptUtil" AS
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class EncryptUtil
public static String encrypt(String inStr)
String outStr = "Test data 123";
try
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted =
cipher.doFinal(inStr.getBytes());
outStr =new String(encrypted);
catch (Exception e)
outStr = outStr + "exception thrown::" + e.getMessage();
e.printStackTrace();
return outStr;
Step2: Stored function to access above stored java class.
CREATE OR REPLACE FUNCTION SF_ENCRYPTUTIL(
pKey1 VARCHAR2
) RETURN VARCHAR2 AS
LANGUAGE JAVA NAME 'EncryptUtil.encrypt(java.lang.String ) return java.lang.String';
Step3: Test encryption and descryption
DECLARE
outstr VARCHAR2(2000);
BEGIN
DBMS_OUTPUT.PUT_LINE('outstr-->' || SF_ENCRYPTUTIL('12345'));
END;
Below code example using DBMS_CRYPTO. This works, but we do not want to use this.
declare
l_in_val varchar2(2000) := 'Test data 123';
l_mod number := dbms_crypto.ENCRYPT_AES128
+ dbms_crypto.CHAIN_CBC
+ dbms_crypto.PAD_PKCS5;
l_enc raw (2000);
l_enc_key raw (2000);
l_dec raw (2000);
begin
l_enc := dbms_crypto.encrypt
UTL_I18N.STRING_TO_RAW (l_in_val, 'AL32UTF8'),
l_mod,
HEXTORAW('156ae12300ccfbeb48e43aa016febb36'),
HEXTORAW('001122230405060708090a0b0c0d0e0f')
dbms_output.put_line ('Encrypted='||l_enc);
end;
Edited by: user5092433 on Sep 10, 2009 12:26 AMI guess I'd be a bit curious about why you can't use a DBMS_CRYPTO solution that provides identical output. It seems odd to want to have a procedure running inside Oracle and then dictate that it has to be Java and not PL/SQL...
I verified the java.security file in jre/lib/security and I see that there is provider entry for SunJCE.
The jre version in Oracle is 1.4.2.Which java.security file are you talking about? The JVM that is inside the Oracle database does not and can not use configuration files that are outside the database. I suspect when you talk about files and paths that you're looking at a JVM outside the database, which is not the JVM that your Java stored procedure would be using.
Looking at the error, my assumption is that some JAR file needs to be loaded into the internal JVM in order for the AES algorithm to be available. But I'm unfortunately not familiar enough with these classes to say what that would be.
Justin -
Java Classes and JSP`s (urgent)
hi, my question is:
How can i invoke normal java classes` methods using Jsp`s for this??, is it possible??, if it is, then how do you do this, and where do you have to put the java classes in order to find them from a jsp.
thanksHi,
You can access normal java classes in JSP pages. You have to import them in the header like this:
<%@ page language="java" import="//your java class file with package"%>
or if u r using java beans, then use the <usebean> tag. Put the java classes in the classes directory. Which server u r using? If it is JWS, then u have a specified classes directory, where u have to put all the class files along with their packages. Hope this will help.
atanu. -
Audit of Java Class, Resource, and Source
We are currently at 10.1.0.5 on Win@K3 server, and are implementing DIACAP requirements. One of the finding states we need to add auditing of objects and they gave us the script to implement this:
AUDIT ALL BY ACCESS;
AUDIT ALL PRIVILEGES BY ACCESS;
AUDIT ALTER JAVA CLASS BY ACCESS;
AUDIT ALTER JAVA RESOURCE BY ACCESS;
AUDIT ALTER JAVA SOURCE BY ACCESS;
When we try to run this in sqlplus, it gives us an error on the Java lines (Ora-00969: Missing ON keyword). According to the documentation I found on line, which was limited, this is the correct syntax. Anyone know why this is failing?
Thanks!We are currently at 10.1.0.5 on Win@K3 server, and are implementing DIACAP requirements. One of the finding states we need to add auditing of objects and they gave us the script to implement this:
AUDIT ALL BY ACCESS;
AUDIT ALL PRIVILEGES BY ACCESS;
AUDIT ALTER JAVA CLASS BY ACCESS;
AUDIT ALTER JAVA RESOURCE BY ACCESS;
AUDIT ALTER JAVA SOURCE BY ACCESS;
When we try to run this in sqlplus, it gives us an error on the Java lines (Ora-00969: Missing ON keyword). According to the documentation I found on line, which was limited, this is the correct syntax. Anyone know why this is failing?
Thanks! -
Exception : importing java classes
Hi all,
I'm trying to import java classes in forms 9i, but it generates me this error :
Import de la classe prj.proxy.MyWebService1SoapHttpPortClient...
Exception : java.lang.NoClassDefFoundError: oracle/webservices/transport/ClientTransport
Please give me some help with this issue.For the importer to work, your jar-file must be part of the CLASSPATH-environment-variable-setting. If you're classes to be imported contain references to external classes (as you to with your webservices), that jar-file must also be part of the CLASSPATH.
-
Changing Java class in to Java Bean
Can somebody tell me how to change a normal Java class into Java Bean.I dont need any visual interface in Java Bean.I simple need to turn my Java class into Java Bean.
Hi,
Chanchal,
you didn't specify anything abt ur java class. In a java bean basically you use getter and setter methods to call. import relevant packages and extend them into your class. If u give sufficient info, then i can help you out.
Durga -
Unable to get database connection from loaded java class in oracle
Hi all,
I am trying to call java class method from oracle function, but getting below exception, while creating connection.
SQL> select charge_calculation(1,'2011-06-01', 'E') from dual;
select charge_calculation(1,'2011-06-01', 'E') from dual
ERROR at line 1:
ORA-29532: Java call terminated by uncaught Java exception:
java.lang.ExceptionInInitializerError
inside main method
inside main method1
inside main method2
inside main method3
inside main method3
Exception in thread "Root Thread" java.lang.ExceptionInInitializerError
at javax.crypto.Cipher.getInstance(DashoA12275)
at oracle.security.o5logon.O5LoginClientHelper.decryptAES(Unknown Source
at oracle.security.o5logon.O5LoginClientHelper.generateOAuthResponse(Unk
nown
Source)
at
oracle.jdbc.driver.T4CTTIoauthenticate.marshalOauth(T4CTTIoauthenticate.java)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:367)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:
501)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:203)
at
oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:33)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java)
at java.sql.DriverManager.getConnection(DriverManager.java)
at java.sql.DriverManager.getConnection(DriverManager.java:187)
at SPEodPricing.spEodPricing(SPEODPRICING:98)
at SPEodPricing.main1(SPEODPRICING:47)
Caused by: java.lang.SecurityException: Cannot set up certs for trusted CAs
at javax.crypto.SunJCE_b.<clinit>(DashoA12275)
... 13 more
Caused by: java.security.PrivilegedActionException: java.io.IOException
at java.security.AccessController.doPrivileged(Native Method)
... 14 more
Caused by: java.io.IOException
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java)
at sun.net.www.protocol.jar.URLJarFile$1.run(URLJarFile.java:177)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.jar.URLJarFile.retrieve(URLJarFile.java:165)
at sun.net.www.protocol.jar.URLJarFile.getJarFile(URLJarFile.java:43)
at sun.net.www.protocol.jar.JarFileFactory.get(JarFileFactory.java:70)
at sun.net.www.protocol.jar.JarURLConnection.connect(JarURLConnection.ja
va:102)
at
sun.net.www.protocol.jar.JarURLConnection.getInputStream(JarURLConnection.java:1
24)
at javax.crypto.SunJCE_d.a(DashoA12275)
at javax.crypto.SunJCE_b.g(DashoA12275)
at javax.crypto.SunJCE_b.e(DashoA12275)
at javax.crypto.SunJCE_q.run(DashoA12275)
... 15 more
SQL> select charge_calculation(1,'2011-06-01', 'E') from dual;
select charge_calculation(1,'2011-06-01', 'E') from dual
ERROR at line 1:
ORA-29549: class BBVA_MERGED.SPEodPricing has changed, Java session state
cleared
SQL> exit
Disconnected from Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64
bit Production
With the Partitioning, Real Application Clusters, OLAP, Data Mining
and Real Application Testing options
JAVA Sample code:-
public String method1(int pi_ctry_id,String pi_cur_busi_date ,String pi_eod_bod_flag)
System.out.println("inside main method1");
CachedRowSet tmplcrs = null;
HashMap resMap = new HashMap();
Double ln_candidate_extra = 0.0;
Double ln_calculate_on_val = 0.0;
int lv_calculate_on = 0;
int lv_cand_attribute = 0;
// int pi_ctry_id = 0;
// String pi_cur_busi_date = null;
int pi_bch_id = 0;
// String pi_eod_bod_flag = null;
Date ldt_cur_busi_date = null;
Date lstr_next_calc_date = null;
int li_bch_id = 0;
int li_chg_ac_branch = 0;
int calFrequency = 0;
DbUtils dbObj = new DbUtils();
Map reqMap = new HashMap();
CachedRowSet updtcrs = null;
Connection conn = null;
try
System.out.println("inside main method2");
reqMap.put("pi_ctry_id", ""+pi_ctry_id);
reqMap.put("pi_cur_busi_date", ""+pi_cur_busi_date);
reqMap.put("pi_eod_bod_flag", ""+pi_eod_bod_flag);
System.out.println("inside main method3");
Class.forName("oracle.jdbc.driver.OracleDriver");
// Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@10.1.56.85:1521:orcl", "bbva_merged", "bbva_merged");
// conn = DriverManager.getConnection("jdbc:oracle:thin:@10.1.50.104:1521:cmsdb6", "bbva_base", "bbva_base");
System.out.println("inside main method3");
conn = DriverManager.getConnection("jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS = (PROTOCOL = TCP)(HOST = 10.1.50.129)(PORT = 1521))(ADDRESS = (PROTOCOL = TCP)(HOST = 10.1.50.130)(PORT = 1521))(LOAD_BALANCE = yes)(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = BBVASIT)))", "BBVA_MERGED", "BBVA_MERGED");
conn.setAutoCommit(false);
System.out.println("inside main method4");
}29532, 00000, "Java call terminated by uncaught Java exception: %s"
// *Cause: A Java exception or error was signaled and could not be
// resolved by the Java code.
// *Action: Modify Java code, if this behavior is not intended.
Maybe you are looking for
-
To disable the Application tool bar button in ALV report
Hi Everyone, Iam using REUSE_ALV_GRID_DISPLAY to display ALV report. Now my requirement is to disable(I mean grey out) a application tool bar button. Thanks in advance Moderator message: please search for available information and try yourself before
-
Upgraded 2 macs to Mavericks, can no longer access shared folders/files.
So I upgraded my Macbook Pro, and Mac Mini to Mavericks today, and previously when they were both on mountain lion I could access the shared folders/files and screen share with absolutely no issue whatsoever. But upon updating to Mavericks today it a
-
Installed itunes and now my CD won't work!!!!!
I just bought an ipod, and installed itunes on my PC laptop. then, all of a sudden, My Computer won't show the CD drive anymore. does anybody know how to resolve this??? Thanks
-
I have been having an entirely consistent issue with Adobe Acrobat X. Every time it opens, not only can I not quit the application, but I also can't close any windows that are open in the application, nor can I force quit. Last night it opened up a f
-
ABAP provider proxy error using Fault Message Type
Hello experts, I'm using a provider ABAP proxy with a fault message type in the inbound service interface. In the ABAP code on the backend system, I need to fill a database table. in case the record exist --> fault + message back to SAP PI to be aler