File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Servlets and the fly likes why controller is servlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "why controller is servlet" Watch "why controller is servlet" New topic
Author

why controller is servlet

Manas Ahlaad
Ranch Hand

Joined: Nov 07, 2001
Posts: 165
Why should a controller be a servlet , why not a JSP ? why is it mentioned in all the framesworks like Structs, MVC that servlet is controller.
please clarify


Manas<br />Today If You are not Confused,You are just not thinking Clearly !<br />---------------------------------
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
The controller is usually a servlet, because it does not generate any HTML. A controller (or dispatcher) just works out what needs doing, then forwards to something else to generate the output.
The whole reason for JSP is to make HTML generation easier than using the likes of raw "print" statements. If you are not generating HTML, there's no point using a JSP.


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Jayson Falkner
Author
Ranch Hand

Joined: May 07, 2001
Posts: 57
You can certainly use whatever you please as the controller. JSP work, Servlets work, and Filters work. However, you commonly see a either a filter or a servlet as the controller for a few reasons. The first is that servlets were around before filters, hence projects such as Struts started off building a controller servlet, and it has yet to be changed to a filter. Filters make fairly ideal controller components, they cleanly stack on top of the web application, they work as a request dispatcher, and they are authored in Java. As mentioned above, usually you want your controller to have nothing to do with HTML, instead it works with the rest of your Java code -- this makes having the pure Java interface helpful. JSP provides only a clumsy method of embedding Java scriptlets, which usually end up being a pain to maintain.
However, JSP is really good at making HTML. Usually a web application is divided in to the controller (either servlet or filter) and the view (JSP), because the controller needs to work with Java code and the view needs to make HTML.
With all that said, there is still no reason you can't use JSP as a controller. The MVC design pattern works because you are logically splitting up your web application in to smaller, specialized parts. There is no limit to JSP that makes it not work as any of these parts.


Jayson Falkner<br />jayson@jspinsider.com<br />Author of <a href="http://www.jspbook.com" target="_blank" rel="nofollow">Servlets and JavaServer Pages; the J2EE Web Tier</a>
Ken Robinson
Ranch Hand

Joined: Dec 23, 2003
Posts: 101
Why not use the server itself as the controller?
It already finds the servlet to call based on the <url-mapping>, and any common code could easily go into one or more super classes.
Usually a controller is used in a web app to do common work and delegate to a class specific to a requested URL. Although it does not seem to be a popular view, the web container itself already does this. The container looks at the url, determines which Servlet to call and calls it. Why have an other 'controller' look at the same URL a second time for the same purpose?
Phil Chuang
Ranch Hand

Joined: Feb 15, 2003
Posts: 251
There's times when a single point of entry is desirable. Instead of having different urls for different servlets, you'd have a single servlet with different parameters. Makes extension easier, imo. You're correct that the controller mappings can be defined in the server's web.xml file - but why put those non web-oriented settings in the web.xml file? They are application-oriented settings.
Also, when you make the server do the work of the controller, then that means you've got URLs hardcoded into the webpages, which makes it hard to extend or maintain.
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15286
    
    6

Also, when you make the server do the work of the controller, then that means you've got URLs hardcoded into the webpages, which makes it hard to extend or maintain.
Making servelts to the work of a controller? A controller is a servlet.
Anyway, just because you don't use a single Controller doesn't mean URL's are hardcoded into your Servlets. Isn't that what a servlet-mapping/url-pattern is for? And besides, how often do you have to go to your web app and change URL's around?
However, I think this is all beyond what the original poster wanted to know. He wanted to know why a Servlet should be used as the Controller instead of JSP, etc. Not WHY one should use a Controller.
[ February 02, 2004: Message edited by: Gregg Bolinger ]

GenRocket - A Test Data Generation Platform
Phil Chuang
Ranch Hand

Joined: Feb 15, 2003
Posts: 251
I guess I'm coming from the viewpoint where I'm using the controller more for application flow than mere URL->servlet flow. My current project is being designed such that there is one "controller" servlet per application. It has an instance of a POJO (Plain Old Java Object) controller, and based on params, it determines which workflow to call (more POJOs). Instead of having multiple servlets, I have one servlet and multiple POJOs. So my controller at the java application level and not the servlet level.
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15286
    
    6

Originally posted by Phil Chuang:
I guess I'm coming from the viewpoint where I'm using the controller more for application flow than mere URL->servlet flow. My current project is being designed such that there is one "controller" servlet per application. It has an instance of a POJO (Plain Old Java Object) controller, and based on params, it determines which workflow to call (more POJOs). Instead of having multiple servlets, I have one servlet and multiple POJOs. So my controller at the java application level and not the servlet level.

To me it's 6 one way, half a dozen the other. I still use POJO's, but I just call them from my servlets. All my servlet does is forward requests. So instead of having a Controller lookup a "success" or "failure" in some file, my servlets do the fowarding themselves.
I've used Struts, WebWork, and I have created my own "framework" that uses a Front Controller. I just like plain old Servlets used the way J2EE is designed. Take a request and forward it, or send a response. It doesn't get any simpler. This discussion might prove better in a thread of it's own rather than highjacking Manas' thread.
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
Gregg wrote: Making servelts to the work of a controller? A controller is a servlet.
Anyway, just because you don't use a single Controller doesn't mean URL's are hardcoded into your Servlets. Isn't that what a servlet-mapping/url-pattern is for? And besides, how often do you have to go to your web app and change URL's around?

I think you may have missed the point of Phil Chuang's post. He was concentrating on the idea of using the server as the controller, using URL mappings in web.xml, not using a servlet as a controller.
I have worked with web applications which (in effect) did this. There are problems with this approach, though, and they become obvious if you try to design a system where the mapping depends on form data, or on which button has been clicked.
Imagine the common scenario of a list of items, each with "edit" and "delete" buttons. It's pretty obvious that we might want the "edit" and "delete" operations to be directed to different destinations, but it's surprisingly hard to build efficient HTML to do this. Each form has only a single "method" URL. If you want each button to go to a separate URL, you either need a separate form for each button (which is very hard to layout nicely, even with lots of CSS, and means loads of copies of any hidden fields), or javascript to modify the method URL attached to each button (which is icky, and can be very difficult to test properly)
The "natural" solution to this has several buttons in a form, and allows the destination servlet/JSP to decide on the action by looking at which button was pressed. But if you do that, you are implementing part of the controller in the servlet.
And what about another requirement where (for example) form submissions with a "date" field in the future should go to the "book/edit a session" page, and submissions with a "date" field in the past should go to the "comment on a session" page? It's impossible to know at the time the page is created what date will be entered, so the URL of the destination cannot be embedded in the page.
General wisdom follows the approach that these sort of issues are bound to arise, and centralising the controller/dispatcher logic in one place (be it a servlet or a filter) provides the flexibility to handle all of these cases, and more.
Of course. If you are happy to start "lean", and refactor as more features are requested, then feel free to use the servlet/JSP mappings as a controller at the start. But if you do, please build a good set of unit tests as you go along, so that if/when you need to change the controller paradigm, you can be sure you haven't broken anything important.
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15286
    
    6

The "natural" solution to this has several buttons in a form, and allows the destination servlet/JSP to decide on the action by looking at which button was pressed. But if you do that, you are implementing part of the controller in the servlet.
I'm lost on how using a Front Controller solves this. Unless there is a means I am not aware of (highly possible ), you still have to pull the Request elements out and determine which button was pressed. Do this in the Controller, or do this in a plain servlet, it still has to happen. Am I missing something?
Andres Gonzalez
Ranch Hand

Joined: Nov 27, 2001
Posts: 1561
Originally posted by Manas Ahlaad:
Why should a controller be a servlet , why not a JSP ? why is it mentioned in all the framesworks like Structs, MVC that servlet is controller.
please clarify

Manas, here's an example of using JSP as a controller. There's nothing wrong with it, even though the JSP page itself doesn't generate *any* html or output at all, it just redirects.
[ February 02, 2004: Message edited by: Andres Gonzalez ]

I'm not going to be a Rock Star. I'm going to be a LEGEND! --Freddie Mercury
boyet silverio
Ranch Hand

Joined: Aug 28, 2002
Posts: 173
Hello Manas,
Andres there has pointed out a good article (better save that because there's news that JavaWorld may not be available sometime in the future-forgot the month-, unless a savior appears). One advantage of JSP is that of the <jsp:useBean...>. This can save you a lot of getParameter/setAttribute pairs of coding specially when you're processing a form with 5, 10, 20 or more parameters. Of course this can also be avoided by making use of the frameworks out there which modify or use servlets.
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
Gregg wrote: you still have to pull the Request elements out and determine which button was pressed. Do this in the Controller, or do this in a plain servlet, it still has to happen. Am I missing something?
Nope. You are not missing anything. That's the thrust of my argument.
I was still following the suggestion made by a previous poster that you don't need an explicit controller (servlet, JSP, filter), but could rely entirely on the URL mappings in web.xml to direct the application to the correct destination.
My intention ws to show that there are pelnty of common situations where you cannot simply use the URL mappings, without extra code to decide.
Ken Robinson
Ranch Hand

Joined: Dec 23, 2003
Posts: 101
Originally posted by Gregg Bolinger:

I just like plain old Servlets used the way J2EE is designed. Take a request and forward it, or send a response. It doesn't get any simpler.

BINGO
This, in a very small nutshell, is everything you need to know about the basics of web applications.
I could (and have) go on for hours about why I think so, but that is not what this thread is about.
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15286
    
    6

Originally posted by Kenneth Robinson:

BINGO
This, in a very small nutshell, is everything you need to know about the basics of web applications.
I could (and have) go on for hours about why I think so, but that is not what this thread is about.


I know you have. I was involved in one of them a long time ago when you were arguing against using Struts or rather, why one SHOULD use struts. Oddly enough, I argued for Struts. Alas, I have seen the light...
Manas Ahlaad
Ranch Hand

Joined: Nov 07, 2001
Posts: 165
Though ,I couldnt get satisfactory answer , your comments were helpful. Thanks guys !
Phil Chuang
Ranch Hand

Joined: Feb 15, 2003
Posts: 251
ANYWAY,
getting back to the original topic:
You can put your controller in a servlet or a jsp or a pojo. It's just that putting any sort of business logic in a jsp is not the en vogue thing to do nowadays .
Back to the tangential discussion w/ Gregg & Frank -
I guess the merit of the POJO controller vs. the servlet controller is for when you're working with an application that is not strictly a web application. For a web-only application, a servlet controller is fine and dandy, and you save a bit of coding by not having to write to an extra layer. But for an application that is designed to run with multiple front-ends, such as Swing, or a Web GUI, then having that extra layer really simplifies things - you code two lightweight mini-controllers in front of the main controller instead of two main controllers.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
It's just that putting any sort of business logic in a jsp is not the en vogue thing to do nowadays

I'm currently in a vendor framework that's, um, like nothing else, so this is not personal experience, but I really like a set of guidelines that I have heard tossed around on other teams:
Controller servlet has no HTML.
JSPs have no Java - only tags.
POJO commands called directly from controller knows HTTP (request, response, etc.)
POJO model has no HTML and no HTTP, just Java business logic.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Ken Robinson
Ranch Hand

Joined: Dec 23, 2003
Posts: 101
The problem is if you ask 50 people how to do a web app correctly, you'll get 50 different answers. I prefer the answer that requires the least amount of work, is the most efficient and is the most widely supported. Knowing the Servlet Spec and using it as intended is in my mind the best solution.
Putting logic in POJOs or Business Delegates that are independent of the web is not web design, it's just good design. If I where writing a GUI, an EJB app or a webservices app, I'd also use POJOs or Business Delegates. As Gregg Bolinger pointed out, a web app's main purpose is to get input from the browser and sent output to it. The POJOs should always do the meat to allow for portability while the web app only gets request parameters (Servlet) and formats the output (JSP). In my mind, this is such a basic concept there is no need for anything but straight J2EE.
Of course, to borrow a phrase, it's just not en vogue to do that right now. The current buzz word is CONTROLLER. Many people are so stuck on having one they don't realize that the web server is a controller. It controls which servlet is called based on the URL.
This is kind of like the B2 stealth bomber. Way back in the 50/60s, Northrup built a 'flying wing'. Nothing ever came of it, but they knew they had a good design, effeicient, low profile and such. For years everyone made other 'better' bombers. When they decided to make the B2 a flying wing and did high powered calculations to determine the best dimensions to use, they found the dimensions of the original Northrup aircraft where dead on all along.
Sun really put a lot of thought into the Servlet Spec and classes. They've been dead on all along in my opinion. If they where THE standard, how much easier would it be to find answers to questions, get good examples and have tools everyone knew? This is an appealing advantage MS have over Java. It doesn't matter how 'good' their API is, the majority of developers do everything the same way and thus it's seen as 'better' by them.
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
Many people are so stuck on having one they don't realize that the web server is a controller. It controls which servlet is called based on the URL.
I'm still a little worried by this. I tried to give some examples of where I think this approach falls down a few posts back, but they seem to have been missed or ignored. EIther that, or I'm misunderstanding what you are proposing here.
I completely agree that the web server directs URLs to servlets, and thus functions like a controller. What I disagree with is that it is sufficient for even fairly ordinary web applications. In almost all web applications I have worked on, there has been a need to make "controller" decisions on user input and other information not available when the GET or POST URLs are built into the pages (I give some examples in a previous post, above).
How does your server-as-controller architecture cope with these situations?
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15286
    
    6

Frank, I see what you are saying about the Server being the Controller versus using a Front Controller. And you are right, all the server can do is process requests and responses based on the web.xml file. Anything that needs to be done with the GET and POST would have to be hand written. But I think where we are differing is "controller decisions". Now I give you the benefit of the doubt as you have been doing this longer than I have and have more experience.
But from my point of view, I don't necessarily think that a "controller" should be forced to make that many custom decisions. Kenneth will probably argue, and Kenneth if I get this wrong you can correct me, that your "controller decisions" can be placed in a Servlet super class and subclassed by other Servlets. Whether or not that method is better/worse than using a Front Controller is probably completely based on personal opinion. One persons preference if you will.
My opinion is that if a Front Controller is such a grand idea and design pattern, why didn't they incorporate something into the new J2EE spec? Similar to when they added Filter. Someone seemed to think that Filters were such a good design they were added to the spec as a special class. And given a purpose. And now some people begin to argue that a Filter can be used as a Front Controller. Of course, the same person that argued that also thinks the J2EE spec needs a complete re-write and wants to add some new scripting langauge to JSP. :roll:
Ken Robinson
Ranch Hand

Joined: Dec 23, 2003
Posts: 101
Any logic that is dependent on information specific to a particular request I keep in the business layer of the application. Since that same logic would need to be present if this where a GUI or other type of app, I seperate that into a facade or delegate factory like class.
The app's business requirements do not change because it is currently presented over the web, just the interface between the user and the logic. I only use the web to gether the incoming data, just as I would if this where a GUI front end, webservice or any other type of app.
I am not saying that there is not a need for controller type decisions. I am saying they do not belong in the web layer of the app. If I put the decisions in the web layer and then have to open my logic up to an other app, platform or language (very possible with my current company), I can't resuse that logic.
I usually only use a superclass servlet for processing that needs to be done on a very wide range of servlets, and a Filter could be done to do the same thing. With the original servlet spec, the promise of servlet chaining was a big plus that was advertised, but it was never really available without custom coding. Filters where finally released in 2.3 to fulfill that promise by simply adding or moving <filter-mapping> tags in web.xml. I don't think they should be used as a controller since once the FilterChain is determined, you either go to the next link in the chain or you break the chain. With a FrontController, you go to the FC and let it determine where to go.
It's just my design preference, but I use the web layer only as a gateway or bridge to the business layer. The business layer has all of the logic, processing and 'meat' of my app. The servlets are only present to get the incoming request to the business layer's expected format. Most controllers set a hidden var to a value or look at a buttons value to determine where to go. That is as invovled as just changing the action prior to submitting the page in my mind.
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
The business layer has all of the logic, processing and 'meat' of my app. The servlets are only present to get the incoming request to the business layer's expected format. Most controllers set a hidden var to a value or look at a buttons value to determine where to go. That is as invovled as just changing the action prior to submitting the page in my mind.
Aha. there we get to one of our key points of difference, I think.
It looks like given the tricky-but-common situation of "edit" and "delete" buttons in the same HTML form (and hence with the same action URL) you come down in favour of rewriting the action URL using JavaScript on the client, and I come down in favour of decoding the button in a server-side controller of some sort.
We can probably agree to disagree.
I have encountered enough situations where JavaScript didn't do what I expected that I prefer to keep control on the server. You seem to have encountered enough bloated and overcomplex "frameworks" that you will consider the JavaScript route if it means you can dispense with a whole big chunk of server-side processing.
As far as I can tell, beyond the thin HTTP/HTML layer, our applications would likely be very similar. It's just how we get from a button click on a web form to a call of deleteThingy(thingName) on a business POJO where we take different paths.
Please correct me If I've still got you wrong
Ken Robinson
Ranch Hand

Joined: Dec 23, 2003
Posts: 101
Frank, I think you are correct that we agree on everything except when to determine what the Servlet is responsible for doing prior to calling the actual logic requested.
I don't even know if one way is 'wrong' or 'right', it's really a matter of preference.
I agree that javascript is a situation I usually avoid, but due to requirements on my current app I've really come to appreciate it (uuggh, never thought I'd say that). As far as changing the action attribute, that is very basic. Beyond that, you usually hit some browser specific stuff that just annoys you, that and the horific 'Object Expected' message that really should say 'I found an error, but I'm not telling you what it is'.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why controller is servlet
 
Similar Threads
In MVC
servlet is used as controller
Parsing xml from a URL
ActionServlet
why servlet as controller