Showing posts with label J2EE. Show all posts
Showing posts with label J2EE. Show all posts

Tuesday, May 24, 2011

Understanding how to implement Model view Control pattern using J2EE and various Java frameworks


MVC stands for Model View Controller design pattern and is one of the widely used pattern especially in Web applications
The pattern segregates the presentation or UI layer as View layer, business logic or application processing into Controller layer and Model is the related data to be used for processing

Since it segregates each of the above three parts it becomes easy to replace one of the above component without affecting the other part and allows the application to replace the existing
component with advanced technology /tool/framework


You can watch my videos on MVC, Struts 2, Spring and other J2EE design patterns and frameworks




In this article we will see following topics

  • Implementing MVC using JSP/Servlet

  • Implementing MVC using Struts 2 framework

  • (Implementing MVC using Struts 2 framework will be part of next series

We will each of the above implementation in a “Hello name” example which takes name from the user and the displays a Hello name message

Integrated Development environment used is Eclipse Europa and Container used is Apache tomcat 6

Implementing MVC using JSP/Servlet

In case of MVC using JSP/Servlet following are the roles taken by each of the component involved





Step 1: Click New=>Other=>Web=>Dynamic web project



Step 2: Enter Project name as MVC and Click on Finish button



Step 3: Click on src and click on New=>package



Step 4: Enter name of package as com.questpond.controller




Similarly create one more package named com.questpond.model


Step 5: Right click Web Content folder New=>JSP


Enter the name of the jsp as index.jsp



Click on Finish button


Step 6: Enter the following code in index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Index jsp</title>
</head>
<body>
<form action="Action.do" method="get">
Enter name <input type="text" name="name"><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

Step 7: Right click on com.questpond.model click on New=>Class. Name the class as ModelBean






Step 8: Within the ModelBean create a variable welcomeMsg and write setters and getters for same

String welcomeMsg;
public String getWelcomeMsg() {
return welcomeMsg;
}
public void setWelcomeMsg(String welcomeMsg) {
this.welcomeMsg = "Welcome "+welcomeMsg;
}


Step 9: Right click on com.questpond.controller and create New=>Servlet

Write the name of servlet as ActionServlet





Step 10: Write the following code within doGet method of ActionServlet

String name =request.getParameter("name");
ModelBean model = new ModelBean();
model.setWelcomeMsg(name);
request.setAttribute("welcomeMsg", model.getWelcomeMsg());
RequestDispatcher dispatch = request.getRequestDispatcher("welcome.jsp");
dispatch.forward(request, response);

Step 11: Create a JSP named welcome.jsp following Step 5 and put the following code inside jsp

<title>Welcome</title>
</head>
<body>
<%=request.getAttribute ("welcomeMsg").toString() %>
</body>

Step 12: Right click on the project and click on export option (Export=>WAR file)






Step 13: Point the destination to the webapps folder of tomcat and check all the options present


Click on finish button


Step 14: Start tomcat (Tomcat=>start.bat) and put the following URL in web browser
http://localhost:8080/MVC/


Following page will appear




Step 15: Enter any name for e.g. John and click on submit button

A page with welcome message will appear as follows






MVC using Struts 2:


Struts 2 makes use of Intercepting Filter pattern which makes use of Filters which can be used for pre processing before executing controller as well as post processing after controller
execution.

For doing pre processing as well as post processing Struts 2 uses Interceptors. Thus request in this case comes to interceptors which then invokes action and based on result of action execution
corresponding view will be displayed to user. This configuration of view with result returned by action is done in an xml known as struts.xml

Model in this case can be Java bean class which can be used with Action







In case of MVC using Struts 2 following are the roles taken by each of the component involved


Advantage of struts 2 MVC is that view for particular action is configured in xml (struts.xml or other xmls included within struts.xml) and hence there is no direct dependency between controller and view

Step 1: Click New=>Other=>Web=>Dynamic web project





Step 2: Enter Project name as WelcomeStruts2MVC and Click on Finish button



Step 3: Copy following jars from the struts 2 libraries from distribution to WEB-INF/lib folder

• commons-logging-1.0.4.jar

• freemarker-2.3.8.jar

• ognl-2.6.11.jar

• struts2-core-2.0.14.jar

• xwork-2.0.7.jar

Step 4: Make following filter entry in web.xml

<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Note: In higher version of struts 2 we can use
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter for filter-class


Step 5: Create an XML within src folder and name it struts.xml




Step 6: Put the following lines inside struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" extends="struts-default">
<action name="welcomeAction" class="com.questpond.action.WelcomeAction">
<result name="success">welcome.jsp</result>
</action>
</package>
</struts>



Step 7: Create a new package by using New=>package and give name as com.questpond.action





Step 8: Click on the package and create a new class by using

New => Class and name the class as WelcomeAction




Step 9: Write the following code within the above class

String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute(){
return Action.SUCCESS; }


Step 10: Create a new jsp by using New=>JSP and name it index.jsp and put the following code within the jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
<s:form action="/welcomeAction.action">
<s:textfield name="name" label="Enter name"></s:textfield>
<s:submit></s:submit>
</s:form>


Step 11: Create one more jsp with name as welcome.jsp and put the following code

<%@ taglib prefix="s" uri="/struts-tags"%>
Welcome <s:property value="name"/>


Step 12: Export the project as war by using right clicking the project and clicking on Export option





Fill the details like destination (where the war has to be kept) in the window. Check all other options and Click on Finish button



Step 13: Start apache tomcat and put the following URL in web browser
http://localhost:8080/WelcomeStruts2MVC/


The following page will appear and fill the name with any string value




Step 14: After filling details click on submit button on which following page will be displayed




What’s next

In my next series we will see how to implement MVC using Spring framework

Thursday, April 28, 2011

Comparing implementation of MVC between J2EE Struts 2 & ASP.NET MVC 2, who is the best? Part 2

So, what’s the agenda?
In case you are new to ASP.NET MVC and J2ee Struts framework

Overall Comparison with framework

Automation using template

Passing data from controller to view

Readymade folder structure

Strong type views for intellisense

Helper classes

URL customization and action mapping

URL validation

Security

Final conclusion

Thanks Vishwa



So, what’s the agenda?


In our previous article we had compared MVC implementation for J2ee and ASP.NET without using frameworks; to view comparison click ASP.NET MVC and J2ee MVC.

In today’s world no one implements MVC without help of frameworks. So it’s either ASP.NET or j2ee, framework support is a must. Struts 2 has been the most accepted framework in J2ee while in ASP.NET the ASP.NET MVC template is the king. In this article we will compare these frameworks in terms of how they differ in implementation and their positive and negative points.

In this article we will compare both frameworks using 8 agenda points: -


  • Automation

  • Passing data between controller to views

  • URL customization

  • Security

  • Folder structure management

  • Intellisense support

  • HTML automation (helper classes).


Do watch our .Net interview questions and answers video from this link
.NET interview questions and answers, you can also catch out J2ee Design pattern videos from this link Java J2ee Design pattern.


In case you are new to ASP.NET MVC and J2ee Struts framework


In case you are not aware of the frameworks you can see the below videos to just get a quick start in both the frameworks

Following is the simple ASP.NET MVC video which displays a hello world.



Following is the simple J2EE struts video to teach struts 2 with the help of an example.




Overall Comparison with framework


Before even I start below is a full comparison sheet which gives an overall view of the comparison. The same we will be discussing in more detail as we proceed in the article.




Automation using template


The first thing which caught our eyes is the Microsoft VS IDE which has a nice readymade template from where developers can start. In MVC J2ee framework the core struts framework does not have something inherent as Microsoft MVC has it.



Said and done that it does not mean J2EE community is lagging; you can still take help of open source plug-in to get the template from
http://mvcwebproject.sourceforge.net. Below is a simple snapshot of MVC web project template.

The only difference it’s not inherent like Microsoft MVC.



Conclusion: - Definitely Microsoft wins here in terms of more user friendly interfaces and automation due to the MVC template. In j2ee struts framework we need to hunt for a third party plug which will help us to achieve the same kind automation.


Passing data from controller to view


In MVC one of the most crucial parts is transferring data from controller to view. Microsoft MVC introduces a new variable called as ‘ViewData’ which will help us to transport data between controller and view as shown in the below code snippet.

The below code snippet sets data in the controller.
ViewData["CurrentTime"] = DateTime.Now.ToString();

The below code snippet displays data on the view.



J2ee Struts framework uses the HTTP request object to pass data from controller to the view. The below code snippet sets a simple date value to the request object using the ‘setAttribute’ function. In ASP.NET MVC we cannot change the request object.
request.setAttribute(“CurrentTime”,new Date());

Later we can display the data using ‘getAttribute’.





Conclusion: - First thing both the technologies have the facility of passing data, but somehow j2ee Struts framework thought process looks more convincing. At the end of the day view gets a HTTP request, so it’s more logical to pass data using the request objects rather than creating a new variable like view data for the same.

Many ASP.NET MVC fans (which includes me) can also argue logically that the request object is created by using the data sent by the end user i.e. from the browser. This data should not be allowed to be changed in between by the web application code. The request object should only be allowed to be modified by the end user using POST and GET.

For this I will give equal point to both of them for now.

Readymade folder structure


In ASP.NET MVC the template creates a readymade folder structure (they are termed as areas) which gives a developer a clear picture of where to store the model, views and controllers as shown in the below figure.



In j2EE struts framework we do not have the clear cut vocabulary for folders as we have in ASP.NET MVC. In J2EE framework the controller and model lies in Java resources folder, while the views are saved in web content folder as show in the below diagram.



Said and done you can always manually rename and create different folder structure to have the same logical representation as we have in ASP.NET MVC , only that it’s not automated.

As per our knowledge the above logical structure is not possible currently by using any J2EE struts plug-in either.

Conclusion: - ASP.NET MVC has a slight advantage in terms of better project management due to readymade logical folder structure, while in J2ee framework we need to create them manually.

Strong type views for intellisense


In ASP.NET MVC you have a nice option where you can create strongly typed view. In other words when you add a view you can select the model with which this view will connect.



Later when you go in the view and type model keyword you can get the properties of the object in a strongly typed manner.


In java we do not have the concept of strongly typed view. If you want you can set the object in request.getAttribute and then to a type cast to get the object intellisense



Conclusion: - This feature can look very exciting for ASP.NET community but it was bit amusing for my J2ee friends (I think they are right in lot of sense also). The whole purpose of strong typed views in ASP.NET MVC is for better intellisense which we can be achieved by type casting data from view data object as shown in the below figure.

The biggest problem here is that developers can start thinking that the model is tied up the view. We understand the intention is not that, but the dialog box just makes a visual intention of doing the same. The end goal of MVC is to separate the model from the view.

So concluding it’s a good feature to get maximum from less code but just that it can be confusing for junior developers who are working on MVC. For a small automation I hope we do not end with a logical confusion about MVC fundamental.

Equal points again to both. I am not giving an extra point to ASP.NET MVC as view thing is more confusing and can be achieved by typecasting.



Helper classes


A good MVC framework will always provide helper classes to create HTML code for views.

In ASP.NET MVC we have the helper classes. For instance to create a simple HTML form in ASP.NET MVC you can use the HTML helper class as shown in the below code.



In j2ee struts framework we have tag libraries which help us to generate the HTML code as it is done by using ASP.NET MVC html helper classes.



Conclusion: - Both the frameworks have HTML helper classes. Let’s not get in to which library is better or else we will lose focus on our main comparison. So even points to both the framework on this discussion.


URL customization and action mapping


MVC is all about actions and these actions are mapped to URL. As a developer you would love to see your MVC framework have the capability of customizing and configuring the MVC URL with action mapping. Below is a simple table which explains why developers would expect customization and configuration for MVC URL’s.



In ASP.NET MVC this is achieved by using the inbuilt routing mechanism. In order to configure routes you can go to the global.asx.cs code and use the routes collection to map the URL structure with the controllers and actions.
routes.MapRoute(
              "HelloWorld", // Route name
              "Pages/RegisterAction/{1}", // URL with parameters
              new { controller = "Register", action = "RegisterAction", id = UrlParameter.Optional }); // Parameter defaults


In order to configure MVC URL in J2ee struts framework we can use the Struts XML file to the same. The below mapping is more clean than the routing collection of ASP.NET MVC. In J2ee framework we can see the mappings more better as they are mapped directly to page names.



Conclusion: - J2ee Struts framework definitely wins in terms of MVC URL configuration and mapping to the controller as its defined using XML file. This thing can be really improved in ASP.NET MVC framework. To change the mapping compiling code is more of a burden.

URL validation


In ASP.NET MVC we have the advantage of doing URL validation using regex (regular expression) before the action hits the controller. For instance below is a simple validation where before the view customer action is called we can check that the input to the action is only numeric value with 2 digits.
routes.MapRoute(
              "View", // Route name
              "View/ViewCustomer/{id}", // URL with parameters
              new { controller = "Customer", action = "DisplayCustomer", id = 0 }, new { id = @"\d{1,2}" }
);


Currently J2ee struts framework does not support the same, said and done you can always still do validation after hitting the controller using some custom logic.

Conclusion: - This is definitely a plus point for ASP.NET MVC because MVC URL’s can be invoked from any medium, via browser, via URLs etc. So we would like to ensure that appropriate validation is checked much before it hits the controller.

Security


MVC URL’s are mapped to action and they can be invoked directly which also means that they are subjected to cross site attacks, sql injection etc. ASP.NET MVC framework has provided security attributes by which we can protect our URL from such attacks.

For instance to prevent forgery attacks and cross site scripting attacks we can use the ‘HtmLAntiForgeryToken()’ as shown in the below code snippet.



In the actions later you can then check if there was any violation.
[HttpPost] [ValidateAntiForgeryToken]
public ActionResult Delete(int customerid)
{

}

You can also mark the controller by using validate input attribute to avoid CSS.
[ValidateInput(true)]
public class OurController : Controller

Critical functions on which you do not want actions to be invoked you can mark the methods as ‘nonaction’ as shown in the below code snippet.
[NonAction]
public void DoPasswordChange(string username, string newpassword)
{
   /* Rest of code unchanged */
}

In J2ee Struts framework currently we do not have any inherent security function to achieve the same. Some customized code.

Conclusion: - This is the biggest win for ASP.NET MVC framework security. Hope that J2ee struts framework in coming times has such kind of inherent security feature which will be a great extra added advantage for the framework.


Final conclusion


Below is the final conclusion. ASP.NET MVC framework out performs J2ee in 4 things while J2ee has the flexible XML URL customization which is currently not available in ASP.NET MVC. For all the other points both of them remain on the same page.

I have tried my level best to put forward both the sides and while doing so I never had in my mind that I am an ASP.NET Microsoft MVP and I should hard sell ASP.NET MVC framework. I have made by best effort to make a true comparison and see which one of them is the best. I do understand how every developer loves his technology, by any chance I have hurted….BIG SORRY.



Thanks Vishwa


Special thanks to Mr Vishwanathan Narayanan who helped me to give inputs on the J2EE side without which I would not have achieved the same. You can see his Java and j2ee design patterns videos by clicking on Java J2ee Design pattern videos.

Thursday, April 7, 2011

.NET and Java J2EE Design pattern interview question: - What is the difference between Facade and Mediator pattern?

Answer:
Facade Design pattern

  1. Aims at simplifying interface.

  2. Existence of façade is not known to sub-system.

  3. Intermediates between client and sub stem.

Mediator Design pattern


  1. Aims at simplifying object interaction.

  2. Existence of mediator is known to objects since they interact using
    the same.

  3. Intermediates between various objects which want to interact.
Regards,

Do visit our .NET design pattern and Java J2EE design pattern interview questions.

Monday, March 28, 2011

.NET and Java J2ee Design pattern interview question: - What is the difference between Template and Strategy pattern

Answer:
Below are the main differences between these two design patterns: -

Template Design pattern

Defines outline for algorithms and allows sub class to override some steps.
Efficient in terms of less redundant code.

Depends on super class for methods.

Strategy Design pattern

Uses object composition to provide variety of algorithm implementation.
Flexible in terms of allowing users to change algorithm at run time.

All the algorithms can be itself implemented.

Regards,

Do visit our .NET design pattern and Java J2EE design pattern interview questions.

Wednesday, March 23, 2011

.NET and Java J2ee Design pattern interview question :- What is the difference between Decorator and Adapter pattern?

Answer:
Below is the main difference between these two design patterns.
Decorator Design pattern
Used to deal with new behavior or responsibilities without affecting existing code.

Provides a wrapper over objects to apply same method which yields different results based on whether the object invoked is granular or composite.

Change of interface does not happen.

Adapter Design pattern

Mainly involved in converting interfaces as per the requirement of client

Allows use of new libraries without changing existing methods

Change of interface happens in this case

Regards,

Do visit our .NET design pattern and Java J2EE design pattern interview questions.

.NET and Java J2ee design pattern interview question :-What is the difference between Object and class adapters?


Answer:

Below are the main difference between these 2 patterns.
Object adapter
Can adapt classes as well as sub classes since uses composition

More flexible since dynamic polymorphism can be used with composition
Class adapter

Can adapt classes or sub classes not both. As a result no need to re implement the entire adaptee
More efficient since class adapter acts as adapter and adaptee

Please do visit my .NET Design patterns and Java J2EE design pattern interview questions

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 ….