Sunday, March 8, 2009

Running JSP/Servlets under .NET in C#

Hi there,

Recently I've been amazed by the things you can accomplish by using the IKVM library. I took me quite a while to realize the actual potential that hides behind this kind of integration that IKVM provides (which is kind of stupid as I'm working in both technologies, just not at the same time).

Let's get to the point!

Here's a line that will compile jetty (tried with version 6.1.11) into a .NET assembly with everything required to start writing and hosting JSP and servlets:

ikvmc -target:library jetty-6.1.11.jar jetty-util-6.1.11.jar servlet-api-2.5-6.1.11.jar jsp-2.1\core-3.1.1.jar jsp-2.1\ant-1.6.5.jar jsp-2.1\jsp-2.1.jar jsp-2.1\jsp-api-2.1.jar

That produces a .NET assembly called jetty-6.1.11.dll which you should include along with IKVM.OpenJDK.ClassLibrary.dll and IKVM.Runtime.dll to make it work.

And now for the fun stuff! Here's a code snippet (actually it's a complete application) that starts up jetty, creates 2 contexts (one for the servlet under /servlet and one for the example web application in JSP under /jsp) and starts the server:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using java.lang;
using javax.servlet.http;
using org.mortbay.jetty;
using org.mortbay.jetty.servlet;
using org.mortbay.jetty.webapp;

namespace JettyServletAndJSPExample {
class Program {
static void Main(string[] args) {
Server server = new Server(8080);

// see: http://localhost:8080/servlet/whatever
Context servletContext = new Context(server, "/servlet", Context.SESSIONS);
servletContext.addServlet(new ServletHolder(new TestServlet()), "/*");

// see: http://localhost:8080/jsp/hello.jsp
WebAppContext webapp = new WebAppContext();


class TestServlet : HttpServlet {
protected override void doGet(HttpServletRequest req, HttpServletResponse resp) {
PrintWriter o = resp.getWriter();
o.println("<h1>hello, world!</h1>");

After that you have a full fledged, java-like (very much alike) server that can hosts servlets written in C# for .NET platform and at the same time to host applications written in pure JSP.

The obvious next step will be to extract the rendering engine alone to be used with ASP.NET MVC framework thus enriching the seamless integration between Java and the .NET world.

If you're lazy enough you can download the whole package here and start exploring it immediately.

Have fun!