Meaningless Drivel is fun!
The moose likes Servlets and the fly likes Java native interface under servlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Java native interface under servlet" Watch "Java native interface under servlet" New topic

Java native interface under servlet

chandu joshi

Joined: Sep 15, 2005
Posts: 12
I want to add jni code into my servlet,this is right way.If yes tell me a book or tutorial for basic guideline.
[ October 15, 2005: Message edited by: chandu joshi ]
dema rogatkin
Ranch Hand

Joined: Oct 09, 2002
Posts: 294
If you are familiar with C, then steps are quite simple:
1. create a class which should use native methods and mark some methods as native;
2. compile your class and then use javah.exe to generate C headres;
3. Implement methods in C using headers from 2;
4. add in Java code loading of .dll or .so before calling native methods
5. Note that all memory you allocated and passed to Java (for example your method returns a string) won't be collected unless you use some specific actions

I'd recommend to get JNI manual from Sun's web site, I used it and created several native implementations with great success.

As an example, you can look in SWT implementation. There is nothing specific for servlets, unless your servlet container uses security manager for limiting responsibilities of servlets. In this case you should give your servlet permission to load native libraries.

There is a small problem for serlet packaging using native method, because commonly loadlib method looks for a native library in system path. You can use load method to specify exact location of a library. I think you can figure out a location of deployed war content and provide correct path to a native library.

Tough in space?, <a href="" target="_blank" rel="nofollow">Get J2EE servlet container under 150Kbytes here</a><br />Love your iPod and want it anywhere?<a href="" target="_blank" rel="nofollow">Check it here.</a><br /><a href="" target="_blank" rel="nofollow">Curious about generic in Java?</a><br /><a href="" target="_blank" rel="nofollow">Hate ant? Use bee.</a><br /><a href="" target="_blank" rel="nofollow">Need contacts anywhere?</a><br /><a href="" target="_blank" rel="nofollow">How to promote your business with a search engine</a>
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
Originally posted by chandu joshi:
[QB]I want to add jni code into my servlet,this is right way.If yes tell me a book or tutorial for basic guideline.

By the way, why you want to do this?
I would say you should not, otherwise your application would be no more platform independent.
I agree. Here's the link:
subject: Java native interface under servlet
It's not a secret anymore!