jQuery in Action, 3rd edition
The moose likes Servlets and the fly likes Never POST to JSP Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Never POST to JSP" Watch "Never POST to JSP" New topic

Never POST to JSP

M. Gagnon
Ranch Hand

Joined: Feb 18, 2004
Posts: 68

In a response to someone else's question about using beans vs. servlets you answered:

"That's an easy one: never submit a form to a JSP. Period. JSPs should be restricted to creation of the view; all processing should be done in a servlet controller."

I have a demo web site for buying concert tickets. The shopping cart is quite simple in that one does not "browse" the site for different items to buy, but views one page of concerts and opens a ticket order that is sequential -- first the customer chooses the concert(s), then enters personal and payment info and finally confirms the order. The first pages submit form data to the next JSP and the order isn't submitted to a servlet until the customer confirms that all the data entered is correct. This design makes sense to me. Why add another layer of complexity/processing when all I'm doing in the first steps is storing data in a bean that isn't submitted to the database until the final step? I really can't think of a good reason to use a controller servlet in the first steps. If you can, please let me know.

m. gagnon
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63852

The camel's nose and all..

It's very rare that a posted form's data can be used on JSP page without any processing whatsoever. If it is true, in your case, that the JSP is still only a pure "view" element, then while I would personally still go through a controller (because, sure as hell, as soon as I finish, some requirement that adds processing to the data will come up), then I'd say that posting to the JSP in this case would not be an architectural violation. But I caution that that's a slippery slope. So I reiterate: never send data directly to a JSP -- it's just too easy to fall into a trap.

[Asking smart questions] [About Bear] [Books by Bear]
Ken Robinson
Ranch Hand

Joined: Dec 23, 2003
Posts: 101
I have had this situation before. Usually I keep a JSP and do not add a Servlet just to forward the request, but I register the JSP as a <servlet> in web.xml (use <jsp-file> instead of <servlet-class> ) and give it a mapping consistent with the servlet I would have created in normal circumstances. This way everything fits in a standard way, it's easier to add a servlet in the middle if requirements are added and I just feel better about it. I'm not a fan of having the HTML the client sees send to a JSP.
[ July 21, 2004: Message edited by: Ken Robinson ]
I agree. Here's the link: http://aspose.com/file-tools
subject: Never POST to JSP
It's not a secret anymore!