JSP and MVC Best Practices - java

I am new to JSP programming and am writing a web app for a family member. As I study, I hear a lot about how JSP's are supposed to be used for presentation and servlets are for business logic. My question is basically about how far that goes and when my use of JSTL would be bad practice. Here's an example: I have a login page for my app, and I am using c:if's with custom functions connected to my java classes to process the form. Would that be considered poor MVC practice or, since I'm only referencing my logic code from EL, is this a legitimate use of JSP's?

Your question contains a lot of what are best-practices which invokes a lot of opinion and debate, which is usually frowned upon in this forum. In general, the JSP is the "V"iew in MVC and should be used to present the data provided by the "M"odel which would be your Java code. The "C"ontroller is often scattered between the M and the V (inviting more debate, sorry).
Any logic you put in your JSP that is beyond looking at the data given you and deciding how to present it, moves it towards the Model. Your login page should just collect the credentials and present them to the Model, which should in turn respond with "Invalid" and re-request the credentials (or fail completely) or if valid, move on to the next page.
In practice, IMHO, you should not put a lot, if any, code that manipulates the data except for formatting it - creating table entries, wrapping with links, etc. You should not (IMHO) query databases, perform calculations, etc., in the JSP - let the Model do that.
As duffymo stated, JSPs are old, but they are still valid. I would suggest that you also consider AngularJs (ng) (after reading about the controversy of V1 v. V2).

JSP is an outdated technology and there are very few Softwares that still use it. But if you want to use it I would suggest that you use Oracle Coding Standards with it. This page should give you a clear idea of what you should and shouldn't do with it.

The best practice with JSP - is not to use JSP at all. I’ll try to explain why and be clear.
First I have to explain something that does not have a connection to JSP at all, but it will help you to understand exact problems with JSP technology.
In functional programming there is a term - pure function. It means that it does not have side effects. Additionally, such function does guarantee that for each invocation with the same input it ALWAYS return the same output.
In OOP functions are not pure. It may have side effects. It makes our life more complicated. But what is important is that these side effects can happen only WITHIN your function. You can debug it. More or less it is UNDER YOUR CONTROL.
Let’s imagine our functionality written in JSP as a function f with input I and output O:
O f(I)
The first problem with JSP is that it DOES have side effects AND such side effects can happen not only inside of your function f, but also can affect it from outside. A simple example: you use tiles technology, your jsp page is used as a component in a tiles template. Another component of this template uses getOutputstream() method and writes to this output stream. But an application can either call getOutputStream or getWriter on any given response, it's not allowed to do both. JSP engines use getWriter, and so you cannot call getOutputStream. And you get in your jsp page that works fine when it is alone:
java.lang.IllegalStateException: getOutputStream() has already been called for this response
getOutputStream() has already been called for this response
With a function you get explicitly input parameters. The input is always clear. Additionally you can use constants or, if your function has side effect use another service to get data for processing. But it is always WITHIN your function and more or less under control. With JSP pages you do not have such control at all. Input data can be put into session with different servlets/web components, input data can be put into request scope via servlet with a lot of if statements. You must first investigate a logic of this servlet. It is additional complexity that is not obvious when you create “Hello World!” program, but that really makes you crazy when you maintain such pages, written several years ago.
I think you have already read that mixing both output and logic is not a good idea. JSP allows people to do that. Cause it is “so convenient”.
You cannot test logic within your jsp pages. Or it makes it more difficult.
You can say that correct usage of jsp technology and applying best practices resolve most of issues. Yes. Agree. But it will never get rid of its internal drawbacks and complexity. You always have to check, really developers followed best practices or not? There are better, much better technologies our days.
Note: the only exception, or use case, when I’d personally would use it: for localisation. You do not have get all messages from server. You do not want to ask a server to get a localized string one by one. You do want to get a batch of values, that will be used on your web form, for instance. With JSP + JS you can do that very easily and explicite.

Related

Why does images.google.com GET requests have such an un-readable form?

Particularly, what are all the dots and numbers at the end for.
Here is an example:
https://www.google.com/search?site=&tbm=isch&source=hp&biw=1366&bih=673&q=kale&oq=kale&gs_l=img.3..0l10.403.1120.0.1352.4.4.0.0.0.0.407.543.0j1j4-1.2.0....0...1ac.1.32.img..2.2.542.vC-f2Kfx-2E
It is a GET variables value, but why such a strange un-human readable syntax?
I assume they are using PHP or Java on the back-end.
What you are seeing is internal computer data, not exactly intended for normal human consumption, but there for a good reason. Also perhaps you are thinking, why would anyone want these ugly internal details displayed on the average user's screen?
When HTTP was invented the thought was that GET requests should be stateful, in other words, if I copy a URI from my browser and email it to you, and you browse to it, then you should see exactly what I saw. To make this work the GET data needed to be in the URI and not hidden from view. Thus the dirty details you are seeing. Back in the day they were thinking of simple GET queries, for example: http://www.somedomain.com/Search?Find=FooBar
However, as software has evolved more data needs to be passed with GET requests and unfortunately it is all visible in the URI. (Note that this also becomes a minor security hole because the average user can see some of the internals of web page production and easily tamper with it.)
What is needed is a hidden data passing method for GET type queries to clean up URIs when it is not necessary for these details to be present. A proposal for such an improvement to HTTP is in the process of being considered. It would involve adding a new method to HTTP similar to GET but with hidden data passing like POST.

using jsp/taglibs versus template engine

I've done some php dev and the big trend in this language is using things like smarty or other template engine.
It usually roughly runs as follows :
load the template as a regular string,
look for its {tags}
replace each {tag} with the result of some code.
cache page with input parameters
render resulting page.
(sometimes add some OO principles such as template becomes an object...)
When I look at jsp, I see usage of scriplets, taglibs with complicated things like
<%# taglib uri="/tags/struts-logic" prefix="logic" %>
<%# page import="ghhghjjgj"%>
then :
<logic:if>some html </logic:if>
or worse :
<%= if (blabal) {%>
some html
<%}else ...%>
and so forth.
Okay, tiles enables me to glue together some jsp pages together which is really handy (like the include in php, sort of)
It seems to me that the php approach is much better in the way that :
It totally separates gui and model processing.
-It's easier to change the pages content when you are working on the behind part,
you're in a real java class with no complicated stuff like % # <%=. (who said
code behind ala C# ;) ?)
The C# approah is very interesting as well but I just want to adress the template part in my question and not start any C# Vs Java Troll war.
I do not also want to say php is better.
I just want to know why there is not a well installed templating engine in java and why we still use scriplets/taglibs.
So I guess I must be missing something.
Can some Java EE Web expert show me the flaws of my reasoning?
J2EE became Java EE a long time ago. Drop the "2".
No one should use scriptlets. It's 1999 technology. If you're seeing it in books, it's because the books are old. There's not a lot of good reasons for writing another servlet/JSP book now.
Custom tag libraries have fallen out of favor. JSTL is the standard. It's unlikely that you'll need more than that.
Templating is common - have a look at Velocity. One project I'm working on uses it exclusively for streaming HTML to the browser.
There are many template engines for Java, Velocity, for example. JSP compiles to Java bytecode. It allows for very fast execution. Whether this factor is important for you or not, depends on your task, for most web sites template processing won't be an issue.
I don't really understand the implications why it's great to write
{if blabal} some html{/if}
and not so good to write
<logic:if test="blabal"> some html</logic:if>
and it's worse to write
<% if (blabal) { %> some html <% } %>
but it's good to write
#if ( blabal )
some html
#end
I personally like to write my logic in java.
Type save
I know the syntax
However, to me it's not a matter of syntax wheter mixing template code and logic is a good or a bad thing. Thus I prefer Snippetory. I gets the logic out of the template while keeping the responsibility for consistence (ecaping stuff and the like), the look (formatting...) and internationalization in the template. The binding logic gets testable, easy to organize and reuse. The data model can be used as is and there's no need to translate it into a model sufficient for some kind of alien technology. In this case the template is rather a kind of a model where you copy the necessary data into rather than a process that self-services from a context.
Now, in this case we'll need to peaces of software to express the same thing, as it always happens as one uses the principles of separation of concerns to get software more maintainable.
Template:
<t:named-region> some html with a {v:value} </t:named-region>
Logic:
if (blabal) {
template.get("named-region").set("value", value).render();
}
Now as we look at this, it's quite a bit more code. Again this is typical to serparation of concerns. However, a quick look on the steps might make sense:
Access to the region is aquired.
Data is bound to the template. This happens fine grained, just like filling in a from.
The completed form is bound to the output.
The last step seems kind of dispenseable. I fill data to it, so it's clear I want to use it. But you have to be aware, render()is a short cut for render(template, "named-region"). So it's a discription how it is used. Thanks to this mechanism you can easily combine the building blocks of one file or even several files to an output of your choise. This leads to an surprisingly convenient re-use of those blocks.
And it gains me focus: When I'm fighting to get html, css and javaScript right I don't have to deal with 'how is the exact path to access the data?' or 'what are the exact case this button is displayed?'. It's just about 'there is logic, so it gets a name'. Very simple, very clean.
Of course there are some other engines this support for separation of template and logic like jByte (I used it for a while) or JTPL just to name a view. However, all of them seem to lack some functionality though, I decided to write Snippetory.

Decorating a multi-client webapp

I have a web-app in Java, Spring, Struts 2 and Hibernate, that servers multiple clients. Each client with multiple users. To create a personal feel for each client, i would like to customize the header for each client.
I'm using sitemesh as decorator, and am looking for tips or examples or someone who can point me in the right direction as to how to acomplish this in the best practice.
What would you think? Should i just code it direct in the header.jsp? Extracting the info about the logged in user and from that create a custom header by code? Or is there a more clever solution out there?
Thanks!
Update:
To further clearify what i want:
Different properties-files for each client is not an option. We are looking at potentionally hundreds of clients. It needs to be database-driven. But thats the easy part. There is no problem storing the information in db and extracting it when needed.
What im trying to figure out is if there is some sort of standard way of doing this. Some sort of filter or Action that is run before the sitemesh decorator that will provide the decorator with the correct info?
Struts2 provides application scope, for variables which are global to the application.
Load all the customer specific strings into #application scope (I would use spring to do this when the application starts up). From there referencing the strings would be pretty obvious: #application.greeting I don't like the idea of using an interceptor because there is nothing to intercept. I would say for what you are doing application scope is the perfect place. If it is a single client system I can see no reason why anything would be stored in application scope.
Aside: Tiles uses a different template paradigm than site mesh, and they have slightly different purposes. As such the two can be complimentary. Tiles relying on XML definitions can have it's definitions stored in a DB and is definitely less computationally intensive, however where there is interplay between different UI components... or disparate elements appearing on the page you need to use sitemesh. So for basic template needs tiles does everything and is quite easy to understand but say you wanted to make add a certain widget in the middle of the page which relies on JS which needs to be added to the header it would be tricky to do this in Tiles (although the obvious solution is to just roll the JS functionality into one JS file for all possible uses in a particular part of the site).
Asside 2: By using a view technology such as velocity or freemarker in conjunction with tiles it is conceivable to move the entire view layer into a database. I just thought I would mention that as for some maintenance issues that could be extremely beneficial.
Sitemesh makes it's decisions about what decoration to use based upon the requested URL string, so unless you have a reference to the client in every url - either as part of the main url string or as a known parameter, then Sitemesh out of the box is not going to help.
This leaves a few possibilities to achieve what you want;
1) Write a filter that runs before Sitemesh that adds, for example, "&clientId="xx" to every incoming request.
2) Dive into the source code for Sitemesh & look for where Sitemesh finally makes it's decision about which decorators to use and override it. I've never tried this so I don't know how practical this might be.
3) Make the style sheet definition in your jsp pages an OGNL expression and provide that information in a base action class that all your actions extend. In this way you end up with (potentially) a different CSS file for each client and you provide your customisation via CSS.
Hope that this helps.

Is there a way to limit the number of AJAX calls in the browser that remain open?

I have a software design question on what's the best way to handle a client javascript program that relies in multiple (but mostly consecutive, not simultaneous), short-lived AJAX calls to the server as a response to user interaction [in my particular case, it will be a facebook-GAE/J app, but I believe the question is relevant to any client(browser)/server design].
First, I asked this question: What is the life span of an ajax call? . Based on BalusC answer (I encourage it to read it there), the short answer is "that's up to the browser". So, right now I do not have really control of what's happening after the server sent the response.
If the main use for an AJAX call is to retrieve data just once from the server, is it possible to manually destroy it? Would xhr1.abort() do that?
Or, the best choice is leave it like that? Would manually closing each connection (if even possible) add too much overhead to each call?
Is it possible to manually set the limit per domain?
And last (but not least!), should I really worry about this? What would be a number of calls large enough to start delaying the browser (specially some IE browsers with the leak bug that BalusC mentioned in the other question? Please, bear in mind that this is my first javascript/java servlets project.
Thank you in advance
The usage paradigm for XHR is that you don't have to worry about what happens to the object -- the browser's engine takes care of that behind the scenes for you. So I don't see any point in attempting to "improve" things manually. Browser developers are certainly aware that 99.9999% of JS programmers do not do that, so they have not only taken it into account but probably optimized for that scenario as well.
You should not worry about it unless and until you have a concrete problem in your hands.
As for limiting the number of AJAX calls per domain (either concurrent outstanding calls, or total calls made, or any other metric you might be interested in), the solution would be the venerable CS classic: add another layer of abstraction.
In this case, the extra layer of abstraction would be a function through which all AJAX calls would be routed through; you can then implement logic that tracks the progress of each call (per domain if you want it to) and rejects or postpones incoming calls based on that state. It won't be easy to get it correctly, but it's certainly doable.
However, I suggest also not worrying about this unless and until you have a concrete problem in your hands. :)
Update:
Browsers do enforce their own limits on concurrent AJAX calls; there's a very good question about that here: How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?
Also, as T. J. Crowder mentions in the comments: make sure you are not keeping references to XHR objects when you are done with them, so that they can be garbage collected -- otherwise, you are creating a resource leak yourself.
Second update:
There is a good blog post about reusing XHR here -- it's actually the start of a chain of relevant posts. On the down side, it's dated and it doesn't come to any practical conclusion. But it covers the mechanics of reusing XHR well.
If the main use for an AJAX call is to retrieve data just once from the server, is it possible to manually destroy it? Would xhr1.abort() do that?
It only aborts the running request. It does not close the connection.
Or, the best choice is leave it like that? Would manually closing each connection (if even possible) add too much overhead to each call?
Not possible. It's the browser's responsibility.
Is it possible to manually set the limit per domain?
Not possible from the server side on. This is a browser specific setting. Best what you could to is to ask in some page dialog the enduser to change the setting if not done yet. But this makes after all no sense, certainly not if the enduser does totally not understand the rationale behind this.
And last (but not least!), should I really worry about this? What would be a number of calls large enough to start delaying the browser (specially some IE browsers with the leak bug that BalusC mentioned in the other question? Please, bear in mind that this is my first javascript/java servlets project.
Yes, you should certainly worry about browser specific bugs. You want your application to work without issues, do you? Why wouldn't you just use an existing ajax library like jQuery? It has already handled all nasty bugs and details under the covers for you (which is many more than only MSIE memory leaking). Just call $.ajax(), $.get(), $.post() or $.getJSON() and that's it. I wouldn't attempt to reinvent the XHR handling wheel when you're fairly new to the materials. You can find some jQuery-Servlet communication examples in this answer.

Using sqls in JSP - What is the best practice?

Say, You have an application which lists down users in your application. Ideally, if you were writing code to achieve this in Java, irrespective of what your UI layer is, I would think that you would write code which retrieves result set from the database and maps it to your application object. So, in this scenario, you are looking at your ORM / Data layer doing its thing and creating a list of "User" objects.
Let's assume that your User object looks as follows:
public class User {
private String userName;
private int userid;
}
You can now use this list of "User" objects, in any UI. (Swing / Webapp).
Now, imagine a scenario, where you have to list down the userName and a count of say, departments or whatever and this is a very specific screen in a webapp. So you are looking a object structure like this:
public class UserViewBean {
private String userName;
private int countDepartments;
}
The easiest way of doing this is writing SQL for retrieving department count along with user name in one query. If I you to write such a query, where would you have this query? In your jsp? But, if you were doing this in a MVC framework, would you move this query to your data layer, get the result set, convert it to UserViewBean and send it to your jsp in request scope? If you write queries directly into jsps/if you are making use of connections directly in JSP, isn't that a bad practice?
I know, some of you might say, 'hey, you got your object composition wrong! if department is linked to user, you would want to create a list of departments in your User object' - Yes, I agree. But, think of this scenario - Say, I don't need this department count information anywhere else in my application other than this one screen. Are you saying that whereever I load my User object from the database, I would have to load a list of dependency objects, even if I won't be using them? How long will your object graph get with all the relational integrity? Yes, I do know that you have ORMs for this very reason, so that you get benefits of lazy loading and stuff, but I dont have the privilage to use one.
The bottom line question here is:
Would you write sqls in to your JSP if it serves just one screen? OR
Would you compose an anemic object
that caters to your view and make
your business layer return this
object for this screen - just to make
it look a bit OOish? OR
irrespective of what your screen
demands, would you compose your
objects such that an object graph
is loaded and you would get the
size of that list?
What is the best practice here?
I would never put SQL in a JSP. I would use Spring MVC or Struts controllers, or servlets to contain all of that type of logic. It allows for better error handling among other things (you can forward to error pages when queries fail).
If you really must do this, use the JSTL SQL tags.
Personally, I take a simple pragmatic approach. If I was writing screen that just displays a list of users with their deparment count, so that the entire code is maybe a page, and I don't expect this code to be used on any other screen, I'd probably just throw it all in the JSP. Yes, I know there are all the MVC purists who will say, "business logic should never go in a JSP". But aside from a dogmatic rule, why not? What would it hurt in a case like this?
If I found that I had two screens, maybe one where I had to simply display the list and another where I had to do some additional processing on the list, then I would certainly pull the common code out into a class that was called from both places.
I believe that the criteria should be: What produces the most maintainable code? What is shortest and easiest to understand? What produces the least linkages between modules? etc.
I adamantly refuse to accept the principle: "In some cases this approach leads to problems, therefore never use it." If sometimes it leads to problems, then don't use it in the cases where it leads to problems. Or worse, "Somebody wrote it in a book, therefore it cannot be questioned." Sure, there are some rules that are valid 99.99% of the time, so it gets to be pointless to check if this particular case is an exception. But there are lots of rules that are good 51% of the time and people leap from "mostly" to "always".
Would you write sqls in to your JSP if it serves just one screen?
In a prototype, just as a quick hack - maybe. In any other situation, not to mention a production environment - NEVER.
Use a proper MVC framework to separate business logic from presentation.
I am not even sure that JSP should be used, but for trivial applications. If you really have to use them, use MVC pattern or encapsulate your logic in a JavaBean.
Have a look at JPA which allow you to do object manipulations which then is persisted in the database
I wouldn't put SQL in a jsp for fear of forgetting it in future maintenance. Think of the poor guy maintaining your code-- poor guy = you in 10 months or whenever the database is restructured-- and at least put all SQL in the same general region.

Categories