I am designing a simple web-based application. I am new to this web-based domain.I needed your advice regarding the design patterns like how responsibility should be distributed among Servlets, criteria to make new Servlet, etc.
Actually, I have few entities on my home page and corresponding to each one of them we have few options like add, edit and delete. Earlier I was using one Servlet per options like Servlet1 for add entity1, Servlet2 for edit entity1 and so on and in this way we ended up having a large number of servlets.
Now we are changing our design. My question is how you exactly choose how you choose the responsibility of a servlet. Should we have one Servlet per entity which will process all it’s options and forward request to the service layer. Or should we have one servlet for the whole page which will process the whole page request and then forward it to the corresponding service layer? Also, should the request object forwarded to service layer or not.
A bit decent web application consists of a mix of design patterns. I’ll mention only the most important ones.
Model View Controller pattern
The core (architectural) design pattern you’d like to use is the Model-View-Controller pattern. The Controller is to be represented by a Servlet which (in)directly creates/uses a specific Model and View based on the request. The Model is to be represented by Javabean classes. This is often further dividable in Business Model which contains the actions (behaviour) and Data Model which contains the data (information). The View is to be represented by JSP files which have direct access to the (Data) Model by EL (Expression Language).
Then, there are variations based on how actions and events are handled. The popular ones are:
Request (action) based MVC: this is the simplest to implement. The (Business) Model works directly with
HttpServletRequestandHttpServletResponseobjects. You have to gather, convert and validate the request parameters (mostly) yourself. The View can be represented by plain vanilla HTML/CSS/JS and it does not maintain state across requests. This is how among others Spring MVC, Struts and Stripes works.Component based MVC: this is harder to implement. But you end up with a simpler model and view wherein all the "raw" Servlet API is abstracted completely away. You shouldn’t have the need to gather, convert and validate the request parameters yourself. The Controller does this task and sets the gathered, converted and validated request parameters in the Model. All you need to do is to define action methods which works directly with the model properties. The View is represented by "components" in flavor of JSP taglibs or XML elements which in turn generates HTML/CSS/JS. The state of the View for the subsequent requests is maintained in the session. This is particularly helpful for server-side conversion, validation and value change events. This is how among others JSF, Wicket and Play! works.
As a side note, hobbying around with a homegrown MVC framework is a very nice learning exercise, and I do recommend it as long as you keep it for personal/private purposes. But once you go professional, then it’s strongly recommended to pick an existing framework rather than reinventing your own. Learning an existing and well-developed framework takes in long term less time than developing and maintaining a robust framework yourself.
In the below detailed explanation I’ll restrict myself to request based MVC since that’s easier to implement.
Front Controller pattern (Mediator pattern)
First, the Controller part should implement the Front Controller pattern (which is a specialized kind of Mediator pattern). It should consist of only a single servlet which provides a centralized entry point of all requests. It should create the Model based on information available by the request, such as the pathinfo or servletpath, the method and/or specific parameters. The Business Model is called
Actionin the belowHttpServletexample.Executing the action should return some identifier to locate the view. Simplest would be to use it as filename of the JSP. Map this servlet on a specific
url-patterninweb.xml, e.g./pages/*,*.door even just*.html.In case of prefix-patterns as for example
/pages/*you could then invoke URL’s like http://example.com/pages/register, http://example.com/pages/login, etc and provide/WEB-INF/register.jsp,/WEB-INF/login.jspwith the appropriate GET and POST actions. The partsregister,login, etc are then available byrequest.getPathInfo()as in above example.When you’re using suffix-patterns like
*.do,*.html, etc, then you could then invoke URL’s like http://example.com/register.do, http://example.com/login.do, etc and you should change the code examples in this answer (also theActionFactory) to extract theregisterandloginparts byrequest.getServletPath()instead.Strategy pattern
The
Actionshould follow the Strategy pattern. It needs to be defined as an abstract/interface type which should do the work based on the passed-in arguments of the abstract method (this is the difference with the Command pattern, wherein the abstract/interface type should do the work based on the arguments which are been passed-in during the creation of the implementation).You may want to make the
Exceptionmore specific with a custom exception likeActionException. It’s just a basic kickoff example, the rest is all up to you.Here’s an example of a
LoginActionwhich (as its name says) logs in the user. TheUseritself is in turn a Data Model. The View is aware of the presence of theUser.Factory method pattern
The
ActionFactoryshould follow the Factory method pattern. Basically, it should provide a creational method which returns a concrete implementation of an abstract/interface type. In this case, it should return an implementation of theActioninterface based on the information provided by the request. For example, the method and pathinfo (the pathinfo is the part after the context and servlet path in the request URL, excluding the query string).The
actionsin turn should be some static/applicationwideMap<String, Action>which holds all known actions. It’s up to you how to fill this map. Hardcoding:Or configurable based on a properties/XML configuration file in the classpath: (pseudo)
Or dynamically based on a scan in the classpath for classes implementing a certain interface and/or annotation: (pseudo)
Keep in mind to create a "do nothing"
Actionfor the case there’s no mapping. Let it for example return directly therequest.getPathInfo().substring(1)then.Other patterns
Those were the important patterns so far.
To get a step further, you could use the Facade pattern to create a
Contextclass which in turn wraps the request and response objects and offers several convenience methods delegating to the request and response objects and pass that as argument into theAction#execute()method instead. This adds an extra abstract layer to hide the raw Servlet API away. You should then basically end up with zeroimport javax.servlet.*declarations in everyActionimplementation. In JSF terms, this is what theFacesContextandExternalContextclasses are doing. You can find a concrete example in this answer.Then there’s the State pattern for the case that you’d like to add an extra abstraction layer to split the tasks of gathering the request parameters, converting them, validating them, updating the model values and execute the actions. In JSF terms, this is what the
LifeCycleis doing.Then there’s the Composite pattern for the case that you’d like to create a component based view which can be attached with the model and whose behaviour depends on the state of the request based lifecycle. In JSF terms, this is what the
UIComponentrepresent.This way you can evolve bit by bit towards a component based framework.
See also: