J2EE Enterprise Design Patterns | how to configure web.xml (Or Deployment descriptor) | Java Application using MyEclipse Debugging | Scala Language

Since last couple of days I was chasing Scala Language Implicit Conversions and implicit Parameters. When I was started to learn Play Framework, I have found there are many places in Controllers Action methods taking implicit request as input parameter and returning response based on executing some logic on implicit request.  During my leaning I was found it was not easy to get an idea about implicit Conversions and Parameters, so I thought to share my knowledge which explains you about some of it concept with examples and different cases.

If you have past experience on C, C++, Java or some programing language you guys have already used this feature as part of respective compiler implementation but you were not aware of it because Scala is the language which provide implicit as language feature. In case of implicit conversion compiler “Do the right thing for you” and convert lower level type to upper level whenever it’s required. Let’s understand this with example.

In salesforce we are using,

System.debug(‘Hello Salesforce  ‘ + 1);                  and                        Println(‘Hello Salesforce  ‘ + 1.0);

Same as in Java we are using somewhere in codes like,

System.out.println(“……  Hello Java” + 1.8);

If you see System.out.println taking two different types of parameters, one having String type and another having value of Integer type.

Have you ever thought of it, why it has happened and why java compiler has not given compilation error? Here comes implicit comes into picture. Behind the hood compiler will insert such convention for you, if compiler will not provide you such facility it would have given you compiler error while you trying to print using two different types for expression together.

Now let’s try to understand how these languages sometime accept different types of expressions as method argument and not showing compilation error. So when java compiler will see System.out.printl() with different expression, compiler will look for respective conversion method for the same scope and if it will find respective method, it will convert to appropriate type. So java has already done the job for you by implementing below method, and we can call these types of methods to run-time conversion methods.

public String int2String(int i) {
return String.valueOf(i);
}

So far so good, I guess now you have got your answer. When compiler saw System.out.println(“Hello Java” + 1) it will insert below convention for you,

System.out.println(“Hello Java” + int2String(1));

The same way it has happened for float2String, boolean2String etc……. The example you have seen above is called implicit conversion and understand how different languages using implicit conversion as part of their implementation.

Same way java 1.5 having concept of AutoBoxing and UnBoxing. These are also an example of implicit conversion. Java collection is collection of objects. When you declare list of integer

List list = new List();
list.add(1); //woking fine with JDK 1.5 or later

Above statement will work fine if you are using JDK 1.5 or later, prior JDK1.5 you have to write like,

list.add(new Integer(1));

Next part I will show you how Scala providing implicit as language feature and provide developer to freedom to use it in project implementation. I feel that Scala implicit must have to understand all Scala developer who all wants to write expressive code, which is easy to readable and execute complex logic behind the lid.

Hope this will help you. Please feel free to provide your feedback…. :)

Tuple in Scala

Before start with Scala tuple we go through what is Tuple in general term. In mathematical terms Tuple is list of ordered and unordered elements. For example if you say n-tuple, your tuple contains n numbers of elements as your tuple values. Scala tuple also having for the same purpose and added powerful feature to the Scala language.  As I mentioned my previous blog Scala emphasise functional programing language and they force to provide immutable collections and in Scala tuples are immutable like List and only different between list and tuples, tuples contains collection of different type.

  • Declare tuple in Scala

Define Scala Tuple

You can create tuple using above image, either writing simple list of elements or by creating object using new keyword. In above tuple I have created 3 element size tuple and while creating tuple I have used “new Tuple3” and in that 3 signify 3 elements size tuple. Scala gives you facility to create up to 22 size elements tuple using “new Tuple22” and if you try to create tuple with size more than 22 elements compiler gives you error like “error: not found: type Tuple”. If you see above image you will notice Scala automatically identify the type of tuple elements how you provide as tuple value. Now you see how to declare tuple but yes you have a question why we need the tuples, let’s take an example where you need your method return multiple values and in that case in java you have to declare a POJO class and return as part of your method return type. Now in Scala you can return tuple instead of your POJO class and you can do this simple thing by creating just tuple.

  • Access tuple elements in Scala

Once you declare elements in tuple you can access it using dot, underscore and element index. For detail see below image,

Access Scala Tuple

So as in above image to access 1st element in tuple I have used tuple._1 which will return first element of the define tuple and same for others what I have to do is change in index number and I will have indexed tuple value.

Now if you aware of Scala or java collection you might having question why we have to use dot, underscore and tuple element index to access the values from tuple. Now in Scala when you write tuple(1) Scala complier call apply method and if you see Scala API apply method always return same type of elements and as I said earlier, Scala tuple is collection of different type of elements.

Some Basic about Scala.

I am writing this blog to give you brief on Scala technology. Since past couple of days I was reading Scala and Scala based web framework Lift so just thought to share something what I did. So before starts with it, give you some brief idea what scala is?

Scala is a multi-paradigm language which runs on the JVM also gives the power of Functional Programming as well as Object Oriented programming and you can also say this language is better java with lot of utility classes, functions and all. The name Scala derived for “Scalable” and “Language” and it has been designed by Martin Odersky very well known for “Java Generics”.

Why Scala ? we have already good technology in the market like Java, C++, Ruby on Rails, and why we are talking about Scala technology? The popularity of Java and C++ has been decreasing against modern dynamic programming languages like Scala. These technologies provide more powerful feathers, and by providing effective syntax reducing lots of line of code.

As a Java, J2EE and Salesforce developer when I was started to learn Scala language first I started to look into comparisons between Java and Scala. Now below you will see some features provided by scala with respect to Java language. The best way to compare Scala with Java is to start with writing a simple Class. Writing a class in scala is simple and if you know how to write class in Java and C++ then you will not find any difficulty and I must say you will enjoy the syntactical freedom provided by Scala.

Now I am writing a Class called Car having two variables with one is final. Show below class for more details,


package com.interview.tests;

public class Car {

private String color;

private final int version = 1;

public Car(String color) {
this.color = color;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}

public int getVersion() {
return version;
}

}

In Scala if you want to write above class you just have to write two line of code,

class Car(color: String, val version: Int) {

}

Scala compiler generates the same thing which we have written in java by removing Public as class access modifier and Private as variable access modifier. In short, you get the same functionality by writing the less code, easier to read and less error prone than Java Class.

Yes I know as a developer you think if scala define constructor like this how can we define multiple constructor. Constructors in Scala are a bit different than Java. Scala has two type of Constructor.

  1. Primary Constructor
  2. Auxiliary Constructor
  • Primary Constructor As we know in Java we have a no argument constructor which is provided by every class and we don’t have to write explicitly. In scala primary constructor also comes in same way and we can define in scala as below,

class Car {
var color: string;
}

Above scala constructor doesn’t accept any parameters, but you can also define primary constructor with parameters and this

is how scala constructor differs from Java one. We can define parameter base constructer in scala as below,

class Car(val version: Int , var color: String) {

}

  • Auxiliary Constructor If we want to declare more than one constructor in Java we used to overloading mechanism accepting different parameters. On similar note Scala classes declare Auxiliary constructor which are overloaded forms of the Primary one. In scala the Auxiliary constructor are named as this like,


class Car(val version: Int , var color: String) {
//Auxiliary Constructor
def this(val version: Int , var color: String, , var name: String){
this(version , color)
this.name = name
}
}

Yes as you see you must call primary constructor before you go ahead with your Auxiliary based constructor.

You learn how to declare class now you will see how to declare variable. Like class remove access modifier same as in variable declaration you don’t need to write access modifier and variable declaration comes in two ways,

  • Var: using var you can declare your normal variable which comes with getter and setter method and you can change your variable value using setter and get value using getter.
  • Val: using val you can declare your Final type of variable which comes only with getter method you cannot set the value.

You already aware of Scala Class and variable it’s time to learn about scala member function. In scala function starts with def keyword with function name and arguments. Below you can find how to write function in scala,


def mileage(runningKm : Double, petrolPrice: Double) : Double = {
runningKm/ petrolPrice
}

Now as you see mileage function starts with def keyword, having two parameters with Double type running kilometres and petrol price which returns calculated car mileage in Double. But wait we have not written any return keyword in method, yes scala provide you the freedom where you don’t need to write return and in function last statement be your return value. Here you will find return type written after function “:  Double = “. Scala also identified return type without mentioning return type at function, you just need to write “=” equals after function like,


def mileage(runningKm : Double, petrolPrice: Double) = {
runningKm/ petrolPrice
}

Both the method behaving same. Now what if you want to write method which return void or nothing.  Scala gives you Unit keyword as void in Java like,


def mileage(runningKm: Double , petrolPrice: Double): Unit = {
runningKm/petrolPrice
}

def mileage(runningKm: Double , petrolPrice: Double) {
runningKm/petrolPrice
}

Both the methods are same and returning nothing(Void).

For more topics follow below URLs,

Thanks for reading you will see some more stuff related to Scala some more time……

Java Application with MyEclipse

Developing Java, J2EE application using available editors like MyEclipse, eclipse, NetBeans and other editor, I have always found so many developers wondering which editor good to develop any java application. After having 2 plus years experience, I found MyEclipse is best way to create new java application, maintain, debug, deploy web application, configure server hot deployment mode, install new plug-in, configure external server and using single click start and stop server is too easy.
My purpose to write this blog is to show you how to use editor effectively when you are developing Java application with MyEclipse. Below I have tried my level best to explain all basic features of MyEclipse.

Create web application and Configure Server with Eclipse

Below snap show you simple MyEclipse editor.1

Second snap show how to create web application.

.2

.3

Click on finish to create skeleton of sample web application.

MyEclipse inbuilt provide MyEclipse Tomcat, so no need to configure external server.

.4

But what if you want to configure external server. See below snap for configure external server. After click on Configure Server show on above snap.Configure Server open window which shows different server and according to your requirement configure with eclipse.

.5

Always launch you server in debug mode because debug mode server take instance changes from change in application so don’t need to restart your server after change in java code. So for hot deployment always launch your server debug mode.

.6

Now after creating web application and configuring web server, now it’s time to deploy application with server. Deploy application with another editor is too massy and long process, but with MyEclipse web application deployment is too easy and with single click. For deploy web application with MyEclipse see below snap. Click on box show in red box. Which open another window and shows all projects, select project which you want to deploy. After select your project click on Add button. After click on add button open another window with configure all server with your MyEclipse IDE. Select one server and press Finish button and then click Ok button. Using these simple step you application successfully deployed with selected server. If you want to remove application from server simple click on Remove button. If you want to re-deploy your application click on Redeploy button. And if you want to look at deploy directory structure at server click on Browse button.

.7

.8

.9

.10

.11

Now you are just some step behind to run your web application with your browser. Start your server just clicking single click.

.12

After starting your server just open your browser and hit request
http://localhost:8080/ SampleApplication
You will get your index page.

.13

Now you start to make web application according to your requirement. Just create package for Java classes at src folder and create jsp for your view part.

Debugging application with Eclipse

How to debug your application with your IDE. Debug will makes your life easy and provide you to fast solution of exception or error. You get direct idea about which variable contains wrong value and what is the reason behind variable contains wrong value.

First follow the basic step describe below.

  • Make sure your server start in debug mode.
  • Mark break point at java class.
  • Hit browser request to send control at your mark break point.
  • Remember F5, F6 and F8 three main keys to debug application.
  • F5:- F5 user for step into particular line.

    F6:- F6 use for execute line and get control to next line.

    F8:- F8 uses for resume you’re debugging from that point or go to next break point if next break point available.

    First mark break point where you want your application flow stops for you. After putting break point hit request your browser for test your java class. Now you saw in green color flow of control reached at given break point. Press F6 for execute that line and go to next line. Now if you want to inspect the value of you variable simple select variable and just press Ctrl+Shift+i (Short cut for Inspect). That will open window and show you value of your variable. Using inspect you can check your variable value and get idea about all variable contains correct value or not.

    .14

    .15

    .16

    .17

    .18

    If you want to step into particular statement Press F5. For example if you inspect your method execution press F5 at your method call, F5 transfer your debugging control to line where you press F5.

    .19

    .20

    At variable section you can also inspect your variable.

    .21

    .22

    If you still have any query and doubt please feel free to ask me question.

    Thanks,
    Nishan Patel
    SCJP 1.5, SCWCD 1.5
    Java Developer
    Enterprise Design Patterns
    Configuring an Application with a Deployment Descriptor

    Configuring an Application with a Deployment Descriptor

    Oh my goodness, I know the power of deployment descriptor or say web.xml. If you don’t know the power of web xml then this blog might help you to explore your knowledge of web xml. I have many times seen that so many java developers don’t know the power of deployment descriptor and also seen that many java developer ask question about most web application on deployment descriptor or most of question solution on just depend on web.xml in web application. As I have explain in my previous blog Enterprise Design pattern I have explain about some design principal and in that I have explain about Deployment descriptor. For any web application web.xml is the heart or also says the look up file for web application. When any web application deploy to server tomcat make look first into web xml and make configuration according to what we have written into web xml. So, we can also say web xml is start up of any web application.

    In this blog I have try to explain about web xml and give configuration of web xml. In any web application we have so many commands through which we can control whole application. For that we don’t have to need person who have knowledge of java, non technical person also change in web xml and change the whole behavior of web application without changing and recompiling java class file.

    But one main thing always wex.xml file under web application WEB-INF directory at tomcat deployment environment. Like if we take example “ExampleWebXml” then our web xml in,

    Tomcat   –>  webapps   –>   “ExampleWebXml”  –>  WEB-INF  –>  And your web.xml file.

    Now, we start with basic configuration of any application web xml file.

    <?xml version=”1.0″ encoding=”UTF-8″?>
    <web-app id=”WebApp_9″ version=”2.4″
    xmlns=”http://java.sun.com/xml/ns/j2ee&#8221;
    xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
    xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”&gt;

    <welcome-file-list>
    <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>

    </web-app>

    That is basic configuration of any web application. When we are not creating any servlet and any model, view and controller. First I give the idea about mapping of servlet into xml.

    In deployment descriptor Url mapped with two tag.

    1) <servlet> tag.

    2) <servlet-mapping> tag.

    Url :- http://localhost:8080/ExampleWebXml/spark

    <servlet>
    <servlet-name>SparkLines</servlet-name>
    <servlet-class>com.service.Controller</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>SparkLines</servlet-name>
    <url-pattern>/spark</url-pattern>
    </servlet-mapping>

    When user hit request with name /spark in browser tomcat look into <servlet-mapping> tag and get servlet reference name with this reference get the servlet class for process this request hit by user in format of /spark. Using this configure all the servlet classes configure for particular request and assign particular servlet for particular request.

    <servlet-class>com.service.Controller</servlet-class> tag contains fully qualified name of the servlet class.

    <url-pattern>/spark</url-pattern> this is how we want the client to refer to the servlet. And one more thing don’t forget to start with a slash “/”.

    OR

    <servlet>
    <servlet-name>SparkLines</servlet-name>
    <jsp-file>/TestController.jsp</jsp-file>
    </servlet>
    <servlet-mapping>
    <servlet-name>SparkLines</servlet-name>
    <url-pattern>/jsp/TestCont.jsp</url-pattern>
    </servlet-mapping>

    You can also give Jsp instead of servlet. Because we all know after compiling jsp it converts into servlet so, our <jsp-file> tag says, ” apply everything in this <servlet> tag to the servlet created from this JSP page….”

    When you define a servlet for a JSP, you must also define a servlet mapping to the JSP page.

    If you want to configure any init parameter with any servlet then you can put <init-parm> tag.

    <servlet>
    <servlet-name>SparkLines</servlet-name>
    <servlet-class>com.service.Controller</servlet-class>
    <init-param>
    <param-name>email</param-name>
    <param-value>nishan5656@yahoo.co.in</ param-value>
    </init-param>
    </servlet>

    Using this you can set init parameter for the servlet Controller and you can get using

    getServletConfig().getInitParameter(“email”);

    We can also declare more than one init-param for the servlet. But this is what we talk about only for the Controller servlet so, what if we want to use all servlet in our application. Then <context-param> tag use for this purpose.

    <context-param>
    <param-name>email</param-name>
    <param-value>nishan5656@yahoo.co.in</param-value>
    </context-param>

    And to get context servlet context use,

    getServletContext().getInitParameter(“email”);

    Configuring Listener into deployment descriptor.

    But, when you are configure init parameter at deployment descriptor no matter it is servlet init parameter or context init parameter, it is always be a String value. So, how to initialize parameter which is other than string or say how to convert your string init parameter to object before call any servlet. So, what if you want to an application init parameter that’s a database DataSource ??

    We have to convert our string parameter into an actual data source reference that all parts of the web application can share. We can’t really put that code in a servlet, because which servlet you put your data source code no guarantee that that code execute first and give data source object to that servlet for use in that servlet.

    So, you need method like main() which execute first when any servlet or jsp called. We can make a separate class, not a servlet or JSP, that can listen for the web application for the two key event in ServletContext’s life creation and destruction. That separate class implements ServletContextListener. That is why for initialize listener class before any servlet call and set servlet context init parameter with object we have to configure at deployment descriptor.

    <listener>
    <listener-class>com.example.MyServletContextListner</listener-class>
    <listener>

    Configuring Session time Out at wex.xml

    Almost web application all over the world user always maintain trough maintaining the user session at application. When user log-in into the application developer registered user session and identified user log-in into the application and according to generate the response to user. But that is good part of application, if you want to make your application well maintain you have to consider all scenario. Consider the situation once user log in after finished work user not click on Log-out link or say direct close browser windows in that case user session always be in application. So, how to make session invalid in that case. Don’t worry web xml have solution for that. Use session timeout tag .

    <session-config>
    <session-timeout>25</session-timeout>
    </session-config>

    But, one thing keep in mind that figure 25 written between <session-timeout> tag that argument is in minute. So, the “25” is in minutes this says if the client doesn’t make any request on this session for 25 minutes, kill it.

    Restrict developer use of scripting into JSPs using Web.xml

    As we know if we want to make our application code which is follows the standard coding standards or make development easily maintainable in future at the time of upgrading functionality then we have to make standard code or say JSPs without scriplets.

    It’s important, you can make it invalid for a JSP to have scripting elements (Scriptlets, Java Expressions, or declarations) b putting a

    <scripting-invalid> tag in the Deployment Descriptor.

    <web-app ……  >

    …………

    <jsp-config>
    <jsp-property-group>
    <url-pattern>*.jsp</jsp-pattern>
    <scripting-invalid>true</scripting-invalid>
    </jsp-property-group>
    </jsp-config>
    …………

    </web-app ……  >

    This disable scripting element for all JSPs in the application because we use the wildcard *.jsp as the URL patterns.

    Before we can also use

    <%@ page isScriptingEnabled=”false”  %>

    This doesn’t work now because isScriptingEnabled attribute is no longer in JSP specification. The only way to invalidate scripting now is through the <scripting-invalid> DD tag.

    Like scripting disable using DD we can also disable EL (Expression language) using DD. But we know that EL is good thing that’s going to save the world as we know.

    <web-app ……  >

    …………

    <jsp-config>
    <jsp-property-group>
    <url-pattern>*.jsp</jsp-pattern>
    <el-ignored>true</el-ignored>
    </jsp-property-group>
    </jsp-config>
    …………

    </web-app ……  >

    Another way to disable using isELIgnored page directive attribute.

    <%@ page isELIgnored=”true”  %>

    Configuring error pages in the DD

    You can declare error pages in the DD based on either <exception-type> or the HTTP status <error-code> number. It is better showing error page rather that error. So always makes error page configuration with DD which makes application good.

    Declaring a catch all error page.

    This environment applies to every exception find at your application.

    <error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/jsp/errorPage.jsp</location>
    </error-page>

    Declaring an error page for a more explicit exception.

    This configuration an error page that’s called only when there’s an ArithmeticException. If you have both this declaration and the catch all above, any exception other than ArithmeticException will still end up the “errorPage.jsp”.

    <error-page>
    <exception-type>java.lang. ArithmeticException</exception-type>
    <location>/jsp/arithmeticErrorPage.jsp</location>
    </error-page>

    Declaring an error page based on an HTTP status code.

    This configuration an error page that’s called only when status code for the response is “404” page not found.

    <error-page>
    <error-code>java.lang. ArithmeticException</error-code>
    <location>/jsp/pageNotFoung.jsp</location>
    </error-page>

    Configuring welcome files in the DD

    You already know that if you type in the name of web site and don’t specify a special file, your application still show you something, and that is your welcome file.

    <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    Configuring <mime-mapping> tag in DD.

    You can configure mapping between an extension and a mime type in DD.

    <mime-mapping>
    <extension>mpg</extension>
    <mime-type>video/mpeg</mime-type>
    </mime-mapping>

    As at the starting of that blog post I have already told that Deployment descriptor is most powerful part of any web application. Still there are so many thing we can configuring using DD like we can configuring custom tag support to application, web application security, ejb configuration, filter and many more.

    So, always keep focus at the time of development of your application. If you make most declaration into DD then you can control application without compiling your java code and get change behavior of application.

    Thanks,
    Nishan Patel
    SCJP 1.5, SCWCD 1.5
    Java Developer
    Enterprise Design Patterns
    Configuring an Application with a Deployment Descriptor


    Enterprise Design Patterns

    If you are the beginner of the web application development you are the lucky. Because someone has already done this work for you. Using J2EE-specification and other design patterns you can simplify your code and your life. And the most significant design patterns for web application, MVC, even has wildly popular framework like Struts, Spring, rails that will help you craft a flexible, maintainable, extensible your application.
    Designing and building a J2EE application is challenging proposition to say the least because a J2EE application distributes processing across multiple tiers, each consisting of many components, some of which reside on different JVM.
    Over time and through trial and error, J2EE developers have come with the best way to solve complex J2EE programming problems. These techniques are called patters.

    “A pattern is a proven technology that is used to develop an efficient J2EE application.”
    OR
    “A repeatable solution for commonly occurring software problem.”

    Professional developer use patterns to avoid making common mistakes when designing and building a J2EE application.

    Web Application Server configuration get complicated

    In the real world, If your web application became popular at the time, and your application get thousand of request per hour, per day, It will not easy to handle with normal server. Then your hardware configuration became quite complex. A common architecture was quite familiar to all developer which is configuring hardware in tiers functionality. Adding more server and computer to tier is known as horizontal scaling, and it is best way to increase output your web application. As we know most of the web application lives in either the “Web tier” or the “Business tier”.
    As web application developer we have already know our web application to be made up many different kinds of software components. The web tire frequently contains HTML pages, JSPs, Servlet, controller, model components, images, and so on. The business tire contains EJBs, legacy application, lookup registries, and most case database driver, and databases. Luckily we have J2EE patterns, these design patterns have been used, tested, and refined by other developers, so that you can don’t have to work out on it.
    When we are developing any large scale we application the most important job is to provide the end user with a reliable, useful, and correct experience. In other words, the application must satisfy the functional requirements, and requirement for what happens behind the scenes, I mean the requirement which is not functional.

    There are so many non-functional requirements we have to take into consideration and those are,

    • Flexibility
    • Maintainability
    • Re usability
    • Extensibility
    • Modularity
    • Performance

    • Design Principles

    As we know patterns also follows design principles which makes patterns to easy and satisfied functional and non-functional requirement with web application. We keep in mind some of design patterns when we are developing web application.

    • High Cohesion

    Cohesion means degree to which a class is design for one, task or purpose.

    • Hide complexity

    Design your application component in such a manner, that one component hide the complexity of another component.

    • Use interfaces

    As we know interface is kind of contract between two objects. Another main benefit of interface is polymorphism. Many classes implement the same class and just override the method and use it.

    • Loose Coupling

    As we know OOPs concept making object of one class just get the property of another class and get the access of another class. So design your class in such a manner that one class not depend another class for perform the class functionality. So design your class which take away which another class.

    Declarative control over the web application is a powerful feature of J2EE containers. We can implement it using our deployment descriptor web.xml file in our web application. Modifying the DD gives us power to change the behavior of application without changing the code. The DD is Xml file that can de maintain and update by non-programmer.

    • How web application sprint

    Ok, before we move ahead for more details of design patterns let’s get some basic idea how web application works when we use MVC architecture, run on a single JVM.

    As we all know MVC mainly stands for Model-View-Controller and I give you brief introduction how it works when any request comes from the client. First of all when user hit request from the browser controller get request, according to mapping logic at controller it send control to model. Model mainly contains business logic for web-application and that models connect to the database and get record according to requirement and business logic at model component. Now as per result from database the model set that result to simple bean (POJO- Plain old java object) class. And then again controller set that bean reference to the request object and controller pass the control to the view component. Now the view (jsp, servlet, freemarker) get the control from the controller and get reference to the bean object set by controller. Then view use EL (Expression language), scriplets, JSTL and gets the bean property and displays it to as a presentation.

    Again that is for web-applications those run on single JVM.

    Then what when if our web-application business logic or model component on another Physical machine or say another JVM and our view and controller on another JVM. That means our application distributed and all the object communicate to each other through network. Now the question is how to handle application run on different JVM. Then JNDI (Java Naming and Directory Interface) and RMI (Remote Method Invocation) comes into the picture for communicate our application object or available object to the network. Both work like a directory which contains list of objects and object details, for communicate across the whole network. Those object we need across network simply we have to register with JNDI and RMI directory. If we want to access those object then application first look up JNDI and RMI directory and get the reference of that object and use it with application, so that way our object communicate across network when our application runs on different JVM.

    So, as I told you that RMI and JNDI handle all the complexity like they handle complex networking communication, I/O performance, serialization and deserialization. Think about it when your application get distributed or say your model and view, controller on different JVM.

    Pattern Catalog

    Patterns are grouped into a collection called a pattern catalog, which you can reference whenever you are designating a J2EE application. The pattern catalog contains many patterns that you will find benefit at your application.

    • Model view controller
    • Business delegates
    • Front controller
    • Filter intercepting
    • Handle-Forward
    • Zero Sum Pattern
    • Status Flag Pattern
    • Sequencer Pattern
    • Transfer Object
    • Service locator
    • Consolidator Pattern
    • Simplicity Pattern
    • Stealth Pattern

    There are also some patterns available for J2EE but I think that are mostly usable. As I describe above two scenario for web application one for all component on same JVM and other where your component are distributed or say different JVM. So, first we discuss patterns which is related to component are distributed or different JVM. There are three patterns for that scenario.

    Patterns use when application component on different JVM.

    • Business delegates
    • Service locator
    • Transfer Object

    So, first I explain basic of this three J2EE patterns what I understand about this patterns. JNDI and RMI both use in all these three patterns.

    Business delegates

    So, when your components are on different JVM, then your business developer registered their model component to JNDI service. When controller get request, the controller code does a JNDI lookup to get object for remote model service. The controller makes business method calls against the object just as actual model object itself. That is the basic scenario when component on different JVM. But as we know controller mainly use for pass request from model and model to view. But in this situation controller makes complex business logic which is use for JNDI lookup. That is not good for the application. In this case all three patterns are comes. First we discuss business delegates. That business delegates is object for the controller to talk to rather than having the controller deal directly with the remoteness of the remote model.

    Advantage:-

    1) Hide the complexity of JNDI lookup.
    2) Hide remoteness complexity.

    Service locator

    So, rather controller communicate with JNDI lookup or model one more object make layer between controller and model component which handle all complexity and hide to controller.
    But in these patterns we have to create more than one business delegate for every request. That business delegates contains duplicate code for JNDI look up business logic. That is again not good for our application. Then a Service locator pattern comes.

    Unless your business delegates use a service Locator, and that Service Locator will have duplicate code for dealing with the lookup service. To implement Service Locator, we will take all logic for doing the JNDI lookup and move it out of multiple Business Delegates and into a single Service Locator.

    Advantage:-

    1) By making the business delegates an object that handless only the business methods rather than also handling JNDI registry look up and that will increase the cohesion for the business delegates.
    2) Again it hides the complexity of JND lookup for business delegates.
    3) We can also create service locator catch and that optional cache can reduce network calls.

    Transfer Object

    We talk, that is about only controller. By using business delegates and service locator patterns, we have got only controller protect from the complexity of remote model components. So, what about view part or how to protecting the web designer’s JSPs from remote model complexity. Business delegates also create remote stub for the JSPs and that jsp use EL expression to get data from the that stub, but that is actual remote object each time it calls getter of the remote object and makes network call massive. Which over load on server. And the JSP is not good to hide the exception that might occur if the remote server crashed.

    So, over rule that situation Transfer Object use. Actually Transfer Object is pass from the remote model server as serialize form and pass to client’s local JVM heap, their serialize object deseralize and use as local object. That objects only simple POJO class which contains populated data from the database. And JSPs use el expression and use to display at view.

    Advantage:-

    1) It basically reduce the Network traffic
    2) Reduce coupling between tires.
    3) Can follow java bean convention so that it can be easily access by another object.

    MVC (Model view controller)

    As, we all know about MVC so, I am not going to explain it details.

    1) MODEL holds the real business logic and the state. In other words, it knows the rules for getting, updating, selecting and deleting state. It is the only part of the application that talks to the database.
    2) CONTROLLER takes user input from the request and interprets what it means. Then it talk to
    model and give command to update model, makes the model state available for the view and
    forward to the JSPs.
    3) VIEW responsible for the presentation. It get the state of the model from the controller as a request form and then JSPs get the all requested parameters and use according to display at user browser side.

    Advantage:-

    1) View can change independently from controller and model.
    2) Model component hide internal details, from the view and controller component.
    3) Increase reusability of model component.
    4) Separation of model code from controller code allows for easier migration to using remote business component.

    But, in MVC there will be corresponding set of model, view and controller component. But, in this case our application with duplicate code across the entire different controller, and didn’t give us a happy feeling about maintainability and flexibility.
    So, all developer have question now how to improving the MVC controller. Beside a lack of cohesiveness, the controller also tightly couple to the model and view component.

    Front Controller

    Now, we can achieve this goal using front controller patterns. Now all well known framework like Struts, spring all work on front controller patterns. The basic idea of the front controller patterns is that a single component, usually a servlet but possibly a JSP, act as a single control point for the presentation tier of a web application. With this patterns all the request of the web application pass through a single controller, which handles dispatching the request to the appropriate places.

    Advantage:-

    1) Centralize a web application’s initial request handing tasks in a single component.
    2) Using front controller with other patterns provide loose coupling.
    3) Decrease over all complexity of application.
    4) Increase maintainability of application.

    Intercepting Filter

    There is only one way to intercept you request or response and that is using Filter. Use the intercepting filter pattern to modify request being sent to servlet, or to modify response being sent to user.

    Advantage:-

    1) We can intercept and/or modify request or response before they reach the servlet or to the client.
    2) Filters are modular so that they can be executing in chains.
    3) Declarative control allows filters to be easily implemented on either a temporary or permanent basis.

    Handle-Forward pattern

    The objective of the handle-forward pattern is to create a handle or forward model infrastructure whereby a request is passed from one component to another component until the request reaches the component that can fulfill the request. The handle forward pattern is ideally suited for an application that implements an approval process such as when an order is received from a client. A company might refrain from processing the order until certain approvals are given and so on. Each approval process applies different routines and is likely to be contained within different components.

    Advantage:-

    1) This pattern simplifies the request for service that is made by an application because the requests are always made to one component.
    2) The application makes fewer requests for service, which decrease the overhead.
    3) Last major advantage flexibility.

    Zero Sum Pattern

    Zero sum patterns is to treat a group of independent processes as a single processing until that collectively can succeed or fail. The until succeeds only if all processes within the until terminate successfully. However, the until fails if even one process fail. This mean that successfully terminated processes must be reversed whenever a process fails. This pattern is ideally use for any type of transaction processing that has multiple coordinated but independent component used to complete transaction processing.

    Advantage:-

    1) Easy to maintain and coordinate the activities of independent components by using one component the processing controller component.

    And many more patterns are available.

    Thanks,
    Nishan Patel
    SCJP 1.5, SCWCD 1.5
    Java Developer
    Enterprise Design Patterns
    Configuring an Application with a Deployment Descriptor

    Follow

    Get every new post delivered to your Inbox.