JSP for .NET developers

This article was originally published in VSJ, which is now part of Developer Fusion.

For developers familiar with .NET development, navigating a JavaServer Pages (JSP) technology stack can be a daunting activity. An alternative foundation platform and variations in architecture, coupled with the frequent use of cryptic acronyms, contribute to making things seem more difficult. This article presents an examination of a modern Java server technology stack, from the perspective of a .NET developer. It provides a fast start into the seemingly foreign world of Java server application development.

The unifying idea to keep in mind, as you read through this article, is that both technology stacks – the ASP.NET stack that you’re already familiar with and the JavaServer Pages based stack – both provide exactly the same features and services to the web application developers. The names they use to identify the features and services may be different for each stack and the manner in which each goes about providing common features and services may also differ.

ASP.NET and JSP

Comparing ASP.NET to JSP is like comparing an apple orchard to an orange. While ASP.NET describes an entire technology stack and a development model for building components-based dynamic web applications, JavaServer Pages (JSP) refers to only a very small piece of the overall Java application server architecture. More specifically, JSP refers to the standard server-side page scripting technology used in a Java application server.

Some readers may remember the days of ASP without .NET, JSP is comparable to it. In today’s terms, a JSP page is very similar to an .aspx page. See this listing for a simple JSP page:

<%@ page language="java" import="java.util.Date" pageEncoding="ISO-8859-1"%>
<%! private static String myname = "Joe"; %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
    	<title>A sample JSP Page</title>
    	<link rel="stylesheet" type="text/css" href="vsjstyles.css">
    	<script language='JavaScript' src='menu.js'/>
    </head>
    <body>
    	The time now is <%= new Date() %> <br> My name is <%= myname %>.
    </body>
</html>

You should notice the following features:

  • It is a basic HTML page with some special markup tags.
  • The page is composed of standard HTML with placeholder tags, allowing an HTML layout specialist/artist to perform the styling of the generated page.
  • The page supports standard web page formatting and DHTML technology such as Cascading Style Sheets (CSS) and JavaScript.
  • The <%@ page %> directive tag which specifies the scripting language (Java) and the code library to be imported (there are Java language code libraries that are being used by the page).
  • The <%! %> declaration tag which contains a static Java variable declaration.
  • The <%= %> scriplet expression tag which is used to embed native programming language code for generating dynamic HTML content.

The purpose of a JSP page is to generate a response for an incoming web request. In fact, every JSP is a Java Servlet. A Java Servlet is a server-side plug-in that typically services HTTP GET and POST requests. The JSP compiler compiles a JSP into byte-code that can be executed by a Java Runtime. The Java Runtime executes the byte-code. For performance reasons, the runtime may convert some byte-code into the native machine language along the way. This is completely analogous to the operation of the MSIL and the .NET CLR.

Support for multiple programming languages

While on the subject of MSIL and the .NET CLR, let’s point out that ASP.NET applications can make use of assemblies written in different programming languages. There are .NET compilers for Visual Basic, C#, Managed C++, and so on. When writing applications on the Java server platforms, however, one typically would only use modules written in the Java programming language. This trend is slowly changing though, as we start to see compilers that compile Python, Ruby, Groovy and other programming languages into Java byte-code.

Servers and deployment architecture
ASP.NET works well with Internet Information Server (IIS). While it is possible to run JSP on a Windows system front-ended by IIS, most Java server deployment uses the Apache Web Server running on a *nix based OS.

In an Apache Web server front-ended deployment, the web server and the (JSP) application server typically run on different machines. The web server services most static content, such as HTML pages and graphics bitmaps (GIFs, JPGs, and so on); for dynamic content, the requests are routed to the application server. Figure 1 illustrates this typical deployment architecture.

Figure 1
Figure 1: Java application server deployment

A large number of popular application servers support JSP. One of the most frequently referenced is Apache Tomcat. Table 1 lists it and several alternatives.

Table 1: Application servers with JSP support
Server Name Home page
Apache Tomcat tomcat.apache.org/download-60.cgi
Jetty jetty.mortbay.org/jetty
Glassfish glassfish.dev.java.net/public/downloadsindex.html
Weblogic www.oracle.com/appserver
Websphere Application Server www.ibm.com/software/webservers/appserv/was
JRun www.adobe.com/products/jrun
Resin www.caucho.com/download

The Apache Tomcat server can double as a general-purpose web server. Some users with single-machine deployments choose to use Tomcat directly as a web server, without Apache Web server as a front-end, to host their applications.

Tomcat instances versus ASP.NET worker processes

An Apache Tomcat server instance, then, is analogous to an ASP.NET worker process.

Indeed, one can scale an application by load balancing requests across multiple ASP.NET instances running on multiple servers in a farm. One can also run multiple instances of Apache Tomcat servers across a farm of servers to service load balanced requests.

Code integration and reuse
In ASP.NET, you can use code-behind to separate the visual page design from the custom code written in C#, Visual Basic or other .NET languages. When coding JSP, you can make use of pre-fabricated logic written in the Java programming language via a JSP Tag Library. One very popular JSP Tag Library is the Java Server Pages Standard Tag Library (JSTL).

The listing below shows JSTL code in action.

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%! public static String [] myList = {"Apple", "Oranges", "Kiwi"}; %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
    	<c:set var="thelist" value="<%= myList %>" scope="request" />
    </head>
    <body>
    	<h2>The items are:</h2>
    	<c:forEach var="listitem" items="${thelist}">
    		<c:out value="${listitem}"/> <br/>
    	</c:forEach>
    </body>
</html>

Note the following: a99c2cd2bcf64955e41dea91b7eb4011

The JSTL standard library has a set of core tags that adds features and flow control, such as URL composition and conditional loops, to JSP programs. JSTL also includes a set of format tags to facilitate internationalization, a set of XML tags to manipulate XML data, and a set of SQL tags that can be used to access a relational database.

In addition to JSTL, there are numerous open source and commercial tag libraries to satisfy different application needs. You can also create your own custom tag library by writing Java code and creating an XML descriptor.

Expression Language (EL)

When using JSP tag libraries, you frequently need to evaluate expressions involving variables and request parameters. JSP includes a comprehensive Expression Language (EL) for this purpose. The code in the listing above shows EL expressions in use. The expression ${thelist} refers to the request scoped variable, while ${listitem} references each element of the array during the <c:forEach> iteration. EL expressions are frequently used in conjunction with the JSTL core flow control tags, the following snippet shows an example of a conditional tag using a boolean EL expression.

<c:if test="${count > 100}">
    The storage is full.
</c:if>

MVC Frameworks
Most modern web applications, whether .NET or Java, utilize the Model-View-Controller architecture to effectively decouple the data and view technologies for flexible and adaptive deployment. For JSP developers, there are many choices for MVC frameworks – Table 2 shows a couple of popular alternatives.

Table 2. MVC Frameworks for JSP
Framework name Home page
Apache Struts struts.apache.org
Stripes www.stripesframework.org/display/stripes/Home

These frameworks provide services such as page-flow and validation, but typically have a strictly HTML-forms based interaction model. However, they also do not provide facilities to work with component-based page generation/construction. In .NET terms, these frameworks do not directly support use of pages composed with a hierarchy of server-side controls.

Server Side Componentization and Web 2.0
Java Server Faces (JSF) is a framework that provides a component model for construction of Java web applications. In fact, JSF comes with a set of ready-to-use server-side controls that wrap the common HTML form controls. Newer Java EE 5 servers, such as glassfish from Sun, come with JSF support out of the box. JSF implementation for servers such as Tomcat are available from Apache (MyFaces), Sun, and other vendors.

To support page creation based on composition of server-side controls, you can add the popular JavaServer Facelets (usually just called Facelets to avoid confusion with JSF) library to JSF.

Facelets also makes layout templating straightforward. The listing below shows a Facelets .xhtml layout template that includes a title area, with header, content, and footer areas.

<!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"
    xmlns:ui="http://java.sun.com/jsf/facelets">
    <head>
    	<title><ui:insert name="myTitle"></ui:insert></title>
    </head>
    <body>
    	<h1><ui:insert name="myHeader"> </ui:insert></h1>
    	<p><ui:insert name="myContent"> </ui:insert></p>
    	<ui:insert name="myFooter"> </ui:insert>
    </body>
</html>

Users of the template can add Facelet’s <ui:composition> and <ui:define> tags in their JSP to populate the various layout areas.

Ajax and server-side controls

The Web 2.0 movement demands highly interactive web user interfaces enabled by browsers supporting Ajax. JSF Server-side control libraries are growing in sophistication and now many support Ajax interactions. Table 3 lists some of the more sophisticated JSF server-side control libraries available with Ajax support.

Table 3 JSF server-side control libraries with Ajax support
JSF components library name Home page
Apache MyFaces Trinidad myfaces.apache.org/trinidatd>
ICEfaces www.icefaces.org/main/home
JBoss Richfaces www.jboss.org/jbossrichfaces
ORACLE ADF Faces www.oracle.com/technology/products/adf/adffaces
QuipuKit www.teamdev.com/quipukit

As an example of Ajax enabled components, the listing below shows JBoss Richfaces server-side controls and standard JSF controls being combined together using Facelet’s composition mechanism.

<!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"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:a4j="http://richfaces.org/a4j"
    xmlns:h="http://java.sun.com/jsf/html">
<ui:composition>
<a4j:form ajaxSubmit="true" reRender="status">
    <h:panelGrid>
    	<h:commandButton value="Click" action="#{backBean.setClicked}" />
    	<h:outputText id="status" value="Name:#{backBean.status}" />
    </h:panelGrid>
</a4j:form>
</ui:composition>
</html>
You can observe the use of Facelets’ <ui:composition> to compose an Ajax supporting <a4j:form> containing an <h:commandButton> and <h:outputText>.

The Facelets <ui:composition> in the listing above can be added to a tag library, and then used in other JSF pages as a new custom component.

Client-side component page construction

Once upon a time, it was possible for a JSP generated web page to interact with software components that are downloaded and running on the client’s computer. These small components ran as part of the user’s browsers and were called Java Applets. In the ASP world, an .aspx can interact with client-side ActiveX controls (OCX). But due to heightened concern for computer security, and the public’s unwillingness to accept code that automatically downloads and executes, both Java Applets and ActiveX control based applications have faded into oblivion. All of the support infrastructure, however, remains in place, and a few system level applications still make use of such technology.

Java server deployment assembly

Java code libraries are typically bundled in Java ARchive (JAR) files. A JAR file is basically an uncompressed archive of a directory hierarchy. To create an assembly deployable by a Java application server, you make a JAR file with a specific directory layout, including an XML deployment descriptor file. The XML deployment descriptor file is always named web.xml, and contains deployment instructions for the application server. JAR files that represents deployable assemblies are renamed with the .war (Web-Archive) extension. Figure 2 shows a directory hierarchy within a deployable .war assembly.

Figure 2
Figure 2: Directory hierarchy of a deployable assembly

In Figure 2, WebRoot is the “root” directory of the assembly; and the META-INF contains a manifest file generated by the JAR archive tool. The jstl.jar and standard.jar files contain code for the JSTL tag libraries.

Note that the web.xml deployment descriptor is always expected to be located under the WEB-INF directory. The listing below shows a simple web.xml deployment descriptor; the descriptor tells the Java application server to locate, process and show the index.jsp as a welcome file (the default file to display).

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <welcome-file-list>
    	<welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Database integration
In the traditional Java EE architecture, application-tier technologies such as JSP do not access databases directly – but rather indirectly through a middle-tier of business objects. More specifically, JSP works with Entity Beans (a type of EJB) which accesses back-end databases.

The current agile interactive web development environment has mandated a departure from this legacy model. More and more, applications in the middle include technology that allows access through a very thin layer of language-based object abstraction – or as is sometimes the case, direct access to database from the application tier without any intervening object abstraction at all.

Whether a system can or should directly access a back-end relational database server directly has become more of a religious discussion rather than pure system architecture. It really depends on the application, the anticipated scalability requirement, the experience and capabilities of the development team, and the personal preference of the system architect.

JSP and the associated servers provide access to databases via a variety of mechanisms. You can code directly to the low-level interconnect driver via the application server’s JDBC (Java Database Connectivity) support. You can add management for your SQL queries using the iBatis mapping framework. You can use popular object to relational mapping technologies such as Hibernate to simplify data access coding. Or you can go for Java platform integrated object-to-relational access mechanism such as JPA (Java Persistence API).

Tooling
While Visual Studio is the IDE of choice for most .NET developers, in Java land there are quite a few choices of development environment. Table 4 lists several of the more popular IDEs for JSP/Java development.

Table 4. Popular JSP / Java Development IDE
IDE Name Home page
Eclipse www.eclipse.org
Netbeans www.netbeans.org
Oracle JDeveloper www.oracle.com/technology/products/jdev
Intellij IDEA www.jetbrains.com/idea
JBOSS Developer Studio www.redhat.com/developer_studio

Conclusion

Writing JSP-centric applications needs not be difficult. .NET and Java server systems are very similar in nature, as they both accomplish the same tasks of generating dynamic web content. Being a seasoned .NET developer gives you a fast track to Java server based development.

You might also like...

Comments

About the author

Sing Li United States

Sing Li has been writing software, and writing about software for twenty plus years. His specialities include scalable distributed computing systems and peer-to-peer technologies. He now spends ...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Some people, when confronted with a problem, think "I know, I’ll use regular expressions." Now they have two problems.” - Jamie Zawinski