Wednesday, March 16, 2011

Comparison of MVC implementation between J2EE and ASP.NET, Who is the best? Part 1

Comparison of MVC implementation between J2EE and ASP.NET, Who is the best? Part 1


Contents

So, what’s the agenda?
This is not for beginners

Overall Comparison without framework

The Sample for comparison

The model – Javabean in J2EE and .NET class in ASP.NET

The Controller – Servlet in J2ee and HttpHandler in ASP.NET

The mapping XML files – Web.xml in J2ee and Web.config in ASP.NET

The View –Servlet in J2ee and HttpHandler in ASP.NET

Summarizing the Final Comparison table

Next steps comparing using frameworks


So, what’s the agenda?

Some times back I was discussing MVC with one of my Java friends. The talk ended up with a fight trying to prove how one technology is better than other in implementing MVC. For whatever reasons good or bad I was trying to prove that Microsoft technology is the best but…hmm,aaahh and ooohh.
The fact is both the technologies have their own way of doing things. So I ended up writing this comparison article which talks about the differences between how MVC is implemented in J2EE as compared to ASP.NET.

To do full justice in terms of comparison I have divided the article in two parts. In the first part we will compare MVC implementation without using framework and tools.

In the second part I will bring up the comparison of MVC using j2EE struts as compared to ASP.NET MVC visual studio template.

You can watch our Java and J2EE design pattern videos on various topics like Model view controller, front controller, intercepting filter, factory patterns and lot more. Do not miss my .NET design pattern videos which covers 24 patterns including MVC, MVP and MVVM.



This is not for beginners

Well this article is definitely not for beginners, in case you are lookingfor MVC fundamental articles you can see my MVC implementation using core HttpHandler @ MVC using HttpHandler ASP.NET

Overall Comparison without framework

So as we all know in MVC the first hit comes to the controller and the controller binds the view with the model and sends it to the end user.
Model, view and controller form the three core pillars for MVC. From 30,000 feet
level (That number makes every architect feel good…) below is how these three
modules are implemented in each of these technologies:-




Below is simple pictorial representation of how things actually look like.





The Sample for comparison

In order to do a proper comparison we have taken a common example. In this example we will do the following:-
• When the user comes to the web site, the first page he will see is the Index page. So if it’s ASP.NET he will see index.aspx page, if its j2EE he will see index.jsp page.

• Index page is nothing but a simple page which takes username and password and sends a login command to the controller.

• Once the controller gets the login command, he creates the object of the model and checks if the user is proper or not.

• If the user is proper he sends them to welcome view page or else he redirects them to the error view page.


The model – Javabean in J2EE and .NET class in ASP.NET

Let’s start with the simplest part of MVC i.e. model.
For the above example we will create a simple class called as “User”, this class will have two properties “Username” and “Password”. The client, which for now the controller will set these two properties can call the “IValid” function to check if the user is valid or not.

In J2EE the model is nothing but the Java bean class , in .NET its a simple class with setter and getters. Below is the sample code for the same.

J2EE Model using Javabean

public class UserBean
{
public UserBean()
{
     this.username="user";
     this.password="pass";
}

public String getPassword()
{
     return password;
}

public void setPassword(String password)
{
      this.password = password;
}

public String getUsername()
{
     return username;
}

public void setUsername(String
username) {
     this.username = username;
}
public boolean IsValid
(String username,String password)
{
return this.username.equals(username)
&& this.password.equals(password);
}
}

ASP.NET Model using .NET class

public class User
{
public string UserName
{
set
{
_strUserName = value;
}
get
{
return _strUserName;
}
}
     public string Password
     {
        set
        {
        _strPassword = value;
        }
        get
        {
            return _strPassword;
         }
      }
      public bool IsValid()
     {
 if (_strUserName == "user"
&& _strPassword == "pass")
        {
              return true;
        }
         else
        {
              return false;
        }
    }
}

The Controller – Servlet in J2ee and HttpHandler in ASP.NET

The next important part is the controller. The controller forms the heart of MVC.
To create a controller in J2EE we create a class which inherits from ‘HttpServlet’ class. The logic of the controller is written in the “processrequest” method. You can access the request and response object using the ‘HttpServletRequest’ class and ‘HttpServletResponse’ class.

To create a controller in ASP.NET we implement the “IHttpHandler” class and override the “processrequest” with the controller logic. Below is the simple code of how the controllers are implemented in both the technologies. To Access the request and response object we need to use the context class in ASP.NET while in J2EE its available as the part of function with different objects as shown in the below code snippet.

J2EE Controller using Servlet

public class LoginServlet extends
HttpServlet

{

protected void
processRequest(HttpServletRequest
request, HttpServletResponse response)

throws ServletException, IOException
{
// In this will go the code for
// connecting the model to the view.
}
}

ASP.NET controller using HttpHandler

public class LoginHandler :
IHttpHandler,IRequiresSessionState
{
public void ProcessRequest(HttpContext
context)
{
// In this will go the code for
// connecting the model to the view.

}
}

In the controller we can get the data from request and response using in both
technologies using the below code.

J2EE Taking data from the JSP form

String username =
(String)request.getParameter("username")
;
String password =
(String)request.getParameter("password")
;
UserBean model = new UserBean();

Taking data from the .aspx page

User obj = new User();
obj.UserName =
context.Request.Form["txtUser"].ToString(
);
obj.Password =
context.Request.Form["txtPassword"].ToString( );

We then call the “isValid” function of the model and redirect to welcome page or to the home page depending on if he is a valid user or not. To redirect in J2EE we use the “RequestDispatcher” class and to redirect in ASP.Net we use the“response.redirect” function.


J2EE checking if user is valid and redirecting

boolean isValidUser = model.isValid();
if(isValidUser)
{
request.setAttribute("welcome","Welcom
e"+username);
}
else
nextJsp ="Error.jsp";
RequestDispatcher dispatch =
request.getRequestDispatcher(nextJsp);
dispatch.forward(request,response);

ASP.NET checking if the user id valid and redirecting.

if (obj.IsValid())
{

context.Session["Welcome"] = "welcome " +
obj.UserName;

context.Response.Redirect("Welcome.aspx");
}
else
{

context.Response.Redirect("Error.aspx");

}

The mapping XML files – Web.xml in J2ee and Web.config in ASP.NET

Now that we have created the controller, we need to map the actions or the URL pattern with the controller. In other words when someone sends an action or URL pattern as “Login” we need to ensure that it invokes the appropriate controller.
Mapping of pattern / action to the controller in both technologies is done by using a configuration XML file. In J2EE this configuration file is called as the “Web.xml” file and in ASP.NET it’s called as “Web.config”.

In J2EE in web.xml we first need to map which URL pattern maps with which servlet. For instance you can see in the below web.xml code snippet we have mapped the Login pattern with LoginServlet servlet name.

<servlet-mapping>

<servlet-name>
LoginServlet
</servlet-name>

<url-pattern>
/Login
</url-pattern>

</servlet-mapping>

Once the pattern is matched with the servlet name, we then need to map the servlet name with the servlet / controller class as shown in the below code snippet.

<servlet-name>
LoginServlet
</servlet-name>
<servlet-class>
com.questpond.controller.LoginServlet
</servlet-class>

In ASP.NET the controller or the handler is mapped with the URL pattern using the web.config file. Below is a web.config file simple XML file code snippet which shows how the Login URL pattern is mapped with the httphandler ‘Loginhandler’.

<httpHandlers>
<add verb="POST" path="Login" type="MVCAspWithoutFramework.LoginHandler"/>
</httpHandlers>
Below is how the overall config file looks in both technologies.

J2EE Web.XML

   <servlet-name>LoginServlet</servlet-
name>
  <servlet-
class>com.questpond.controller.LoginServlet
</servlet-class>
 </servlet>
 <servlet-mapping>
       <servlet-
name>LoginServlet</servlet-name>
      <url-pattern>/Login</url-pattern>
 </servlet-mapping>

ASP.NET Web.config

<httpHandlers>
    <add verb="POST" path="Login"
type="MVCAspWithoutFramework.LoginHan
dler"/>

   </httpHandlers>

The View – Servlet in J2ee and HttpHandler in ASP.NET

The next important part is the view. The view is nothing but a simple page with the form tag and action having the URL pattern.
You can see how the index.jsp and the index.aspx have the action to Login URL
pattern. This URL pattern is then mapped in the web.xml and web.config file to
the appropriate controller.

J2EE view index.jsp


<form action="Login" method="post">
         Username<input type="text"
name="username" value="" />
        <br/>
        Password<input type="password"
name="password" value="" />
       <br/>
       <input type="submit"
value="Submit" />

  </form>

ASP.NET view index.aspx


<form id="form1" runat="server"
action="Login" method=post>
 <div>

<asp:TextBox ID="txtUser"
runat="server"></asp:TextBox>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server"
Text="Button" />

</div>
</form>

Summarizing the Final Comparison table


Next steps comparing using frameworks

This article compared MVC implementation in both technologies without framework, in the next article we will see how MVC differs when frameworks are used. Struts is the most popular framework in J2EE for MVC and the Microsoft VS MVC template is the most used way if implementing MVC in Microsoft.
Let’s see who wins, who is better ….

No comments: