Thursday 6 March 2014

JSP <=> Servlets

A servlet is in essence, a Java class that is executed by the server in response to a client request. A JSP file on the other plays many different roles in the context of a web application. For one role, it could simply be a view that renders the server side response in HTML, XML, JSON or other formats. For another, it could be the intermediary code like ASP or PHP that does some kind of input validation and thereafter forwards this input data to a server for persisting the same in permanent storage. Whatever the role, a JSP is compiled into a servlet and the JSP scriptlet code itself constitutes a part of the doGet() or doPost() methods of the servlet. 

What one needs to internalize here is this interesting relationship between JSPs and Servlets for the former eventually gets rendered into the latter. This leads to a critical inference regarding JSPs and Java classes. A servlet being a Java class, the ultimate form that a JSP takes is a Java class. This relationship between JSPs and Java classes leads to yet another interesting result. A class is composed of member functions and data, so a JSP that eventually gets compiled into a class must provide some mechanism to declare and define class members. The answer is of course, yes. Using the declaration tag, one may declare and define class members in the very same way as in a Java class itself. An example is shown below:

<%!

private String name;
private Integer roll;

public void setName (String name) {
this.name = name;
}

%>

Now one may call a function as shown above from a scriptlet as shown below:

<% 
setName ("Joe");
%>

It's important not to miss the forest for the trees. The crux of the idea is that every web servlet is nothing more than a simple class and the information being passed around is nothing more than a simple object. When you learn object-oriented programming for the first time, it is not very uncommon to read that object passing facilitates message communication. While then it appealed to the senses as nothing more than some kind of an abstract fantasy, we are now seeing rather elegant manifestations of that concept.






No comments:

Post a Comment