The current application I'm working on is a traditional J2EE application from 2003!, with a JSP based front-end, and some service tiers that are the usual suspects (Auth, DAOs etc.).
Trouble is, the front-end is a mess. No MVC, no templating, no nothing. Developers over the years have written code straight into JSPs (I mean massive chunks of Java code), and at some point in those chunks, the control flow passes into the service tiers. It's a pain to read and debug.
I'm writing new functionality for this application, and have to do it in a fairly unobtrusive way. Anything that changes xml configs, or classpath settings etc., is generally discouraged.
My question is: Given nothing but JSPs as entry points into the application, how to best go about writing the cleanest possible code under these constaints?
I'm making ajaxian modules (jQuery available in project svn already), so my JavaScript and JSPs typically look like these:
JavaScript:
jsAjaxCall({
url: 'myActionURL.jsp',
method: 'post',
params: {},
success: function(data){
},
failure: function(data){
}
});
myActionURL.jsp
<%
//entry into server tiers
SomeEntryPointClass entry = new SomeEntryPointClass(request);
String responseString = entry.doYourJob();
PrintWriter out = response.getWriter();
out.print(responseString);
out.flush();
%>
Questions:
The idea is to keep Java Code inside JSPs at an absolute minimum,
and handoff the request object to a front-facing (what an thing to
name it!) object as soon as possible. Is this a reasonably correct
approach given the constraints?
What are the additional things I can do to keep things clean and
well organized? (I've already rolled my own classes for binding
request parameters to domain objects, so that's a nice plus too).
How do I do PAINLESS form validation in a situation like this? I'm
missing Spring MVC's validation! Just can't imagine all the manual hoopla and routing and binding mess with nothing but JSPs! :(
The good news is that jsp's compile into servlets. This ofcourse is good news as it will allow you to use your jsp's in the way you would normally use servlets.
Keeping your java usage in the jsp's and passing off to helper objects ( couldn't bring myself to say front facing) is the correct call as:
1) There is a hard limit to how big your jsp files can get
2) writing unit tests from jsps is harder than pure classes
3) most IDEs won't give you the same level of code writing support for java embedded in a jsp that they do for normal classes
4) debugging will be easier
As for your second question if it is jsp 2 you could look at using custom tags, they can be a useful way to organise jsp heavy code.
Additionally I guess if you want to go ajax the whole way and are feeling cunning you could write jsp pages designed to provide you Json objects. Effectively turning your jsp's into front end services.
As for the third option, I'm sorry but your system sounds anything but painless.
With strut's or jsr303 or spring mvc or even new servlets validation is going to be a bit painful.
Ofcourse if you wrote a validation jsp which returned a validated json object (see suggestion above) it might make your life a little easier.
Good luck
Related
I am new to JQuery, and so far I used it in side projects to add visual animations to the user interface. Since I always used Thymeleaf on the UI when writing a Spring Boot application, I was satisfied combining the two of them. The data from the user side goes through the Model via Thymeleaf, which is processed by the server, and then it injects the results in different objects back to the UI (via the Model again).
But now I started to simplify the process by using JQuery ajax queries, which have the benefit of getting rid of page refreshing, and also I don't have to use the model to inject the objects into every single page. (In case of Thymeleaf, even if a user decides not to change something on the page - like a form - an object still needs to be there - just in case - which will store their changes.)
The question is: Is that a good strategy to get rid of the Thymeleaf and using pure HTML+JQuery to do all the request+response work on the userinterface? I was wondering if there is any cons of it, as there are many people using thymeleaf to handle these stuff without JS, and maybe they have a good reason to do that way.
So after all I think I have found an answer for the question, by considering some important aspects just like:
Code Reusability
A big benefit of using a framework like Thymeleaf is that you can easily reuse the code what you have written - in case of TL - by using fragments. Creating the front-end in pure HTML+JQuery means every single page needs to have a separate .html, except if we build a single page application, but in that case using Angular would be much more efficient.
Security
Another aspect which I didn't take into consideration; Thymeleaf is compatible with Spring Security, also it has it's specific syntax which is hidden from the user at runtime. If a server is REST server (as it is in several cases when working with Spring boot) additional security needs to be implemented, what Thymeleaf can help with. (Additional security is mostly needed anyway)
So probably the best solution is to stay with Thymeleaf, using JQuery as a support on the interface (just like caching the data when using ajax, which Thymeleaf is not that good at, and also doing the visual bells and whistles) and let them work together.
I am using JQuery to make some AJAX calls to my tomcat7 server, for example like this:
$.get("ajax.jsp", {param1: val}, function(data, status) { ... }
Is there any problem with coding an AJAX response in Java purely as a JSP rather than as a servlet with doGet()? In my case, I am returning HTML and not JSON and I am using JSP's ability to intermix Java with HTML to return what I want.
The reason I ask is that all the examples and other stackoverflow answers I've seen related to coding AJAX in Java advise doing this as a Servlet. Will I get into trouble coding this as a JSP?
Yes you will get into trouble. Trouble debugging and maintaining this mish mash of server side and client side code, and it being in unexpected places.
The server should return a view, or in this case it should return the model as json, from a #responsebody annotated controller method.
There is no problem at all to implements the response handlers in jsp and to write all your code and html and mix them.
but from design decision and best practices in maintainability, simplicity, clearity and security are to separate your code in different modules each of them responsible for specific job, in web application it is a good idea to separate your java business logic code from pages that render and care of data.
The best design pattern for this issue is the model view controller (MVC design pattern).
imagine in the future if you change your rendering framework.
Imagine if you work in a team consists of java developer, web graphics design, database developer, how does you split your tasks with others.
Keep in mind that a good understanding in design patterns and MVC will give you a way to learn and use a good frameworks like Spring, Spring MVC, struts2, JSF, Javaee, ....,
I am trying to implement a reasonably complex page flow (100+ pages) as a traditional web application. I found a few options, but none of them are 100% convincing
Harcode the flow into the controllers, do redirects, etc. This is obviously not the best thing for maintenance
JSF not only handles the flow, but also requires to use JSF as the view technology. I don't like this lock-in
Spring web flow. The current version 2.3.1 defines flows in XML that is not easy to maintain. The upcoming 3.0 release promises to define flows with annotations in pure java, but it does not even have a timeline. Additionally the project development slowed down significantly in the past years.
GWT and Vaadin's concept is closer to a traditional desktop application then to a web application, that is really convenient to use, but it wont fit to my project.
Additionally I found dozens of abandoned projects like this: http://javasteps.sourceforge.net/
I am wondering why all these projects are abandoned, what is the way to implement a complex page flow in 2012?
Personally, I'd recommend Single Page Architecture:
Architecture of a single-page JavaScript web application?
I'm not sure if that is feasible or not with your application. I've used all the flows you mentioned above and am currently working on a single-page application and I love it. We're using Dojo on the client-side, which calls a REST API on the server. It's been pretty nice.
Vaadin is pretty solid too and is much easier to set up than just bare-bones GWT. If you have a lot of UI guys on your project that like to code in CSS and Javascript, they'll hate that approach though.
Spring Webflow is pretty solid actually. I haven't looked at it in a while, but when I was using it, it got the job done for what I worked on at the time.
This is really late but I don't see a satisfactory answer to this question and would like to share an approach I had tried in a recent project which I feel is better than the spring web flow approach which is strictly tied down to spring views. I created a SPA using angular js with Spring MVC. In angular js I did not use routers or state, rather I created a div within the controller like below
<div width="100%" id="fullertonDataPanel" ng-include="page"></div>
On the server side to capture all possible transitions from one frame(I am referring to a particular screen in the SPA) to another I created a tree of rules using MVEL . So in the database I had a structure which stored a tree of rules for every frame . The data in the MVEL expressions were being set by the various services each action invoked. Thus on any action the following steps were followed.
1) Validate the action.
2) Invoke various services.
3) Capture the data from these services and merge it with the existing data of the user.
4) Feed this captured data into collection of rules for each frame along with the details of the current frame.
5) Run the rules of the tree w.r.t to current frame and fetch its output.
6) If there is only one transition then that is the final transition. If there are 2 transitions and one is default then ignore the default transition and use the other transition.
7) Return the template name of the transition to the angular controller and set the value of the page variable in the scope of the controller.
Using this approach all my services had to do was store data in different data fields w.r.t a particular action. All the complex if-else conditions for Web Flows or any complex process definitions(like the one defined in Spring-Web Flow) were not required. The MVEL rule engine managed all that and since it was all in the database it could be changed without needing a server re-start.
I believe this generic approach with MVEL is a flexible approach which comprehensively handles the problem of a convoluted flow without making the application code a mess or adding additional unnecessary xml files.
There is a new MVC framework and web flow implementation for Vaadin component model called Lexaden Web Flow
You can try it out for your application as possible alternative.
I was reading about JSF that it's a UI framework and provides some UI components. But how is it better or different from number of components that are available from jQueryUI, AngularJS, React, Vue.js, Svelte, ExtJS, or even plain HTML, CSS and JavaScript.
Why should someone learn JSF?
JSF to plain JSP/Servlet/HTML/CSS/JS is like as jQuery to plain JS: do more with less code. To take PrimeFaces (jQuery + jQuery UI based) as an example, browse through its showcase to see complete code examples. BootsFaces (jQuery + Bootstrap UI based) has also a showcase with complete code examples. If you study those examples closely, then you'll see that you basically need a simple Javabean class as model and a XHTML file as view.
Note that you should not see JSF as replacement of alone HTML/CSS/JS, you should also take the server side part into account (specifically: JSP/Servlet). JSF removes the need of all the boilerplate of gathering HTTP request parameters, converting/validating them, updating the model values, executing the right Java method to do the business stuff and generating the HTML/CSS/JS boilerplate code. With JSF you basically end up with a XHTML page as view definition and a Javabean class as model definition. This greatly speeds up development.
As with every component based web MVC framework, you have in JSF less fine-grained control over the rendered HTML/CSS/JS. Adding custom JS code isn't that easy as you have to take the JSF view state in the server side into account as well (e.g. enabling a disabled button in JS side won't enable the button in JSF side, which is in turn a huge security advantage). If that is however a major showstopper, then rather look for an action based web MVC framework like Spring MVC. You'll only take into account that you have to write all that HTML/CSS/JS code (and prevention against XSS, CSRF and DOM-manipulation!) yourself. Also if you fall back from Facelets to JSP, you'll miss advanced templating capabilities as well.
On the other hand, if you have a big JSP/Servlet/HTML/CSS/JS/jQuery based website and you'd like to refactor the repeated JSP/Servlet/HTML/CSS/JS/jQuery boilerplate code into reusable components, then one of the solutions would be JSF. Custom templates, tagfiles and components can aid in this. In that perspective, JSF stands above JSP/Servlet/HTML/CSS/JS/jQuery (and that's also why it's pretty important to understand those basics before diving into JSF).
You can find a real world kickoff JSF based project here: Java EE Kickoff App. You'll see that it contains next to JSF as good HTML5, CSS3 and jQuery.
See also:
Difference between Request MVC and Component MVC
Difference between JSP, Servlet and JSF
What are the main disadvantages of JSF 2.0?
Is it possible to use JSF+Facelets with HTML 4/5?
When to use <ui:include>, tag files, composite components and/or custom components?
JSF was created to make it so that java shops didn't have to learn stuff like jQuery and build complex JS but instead focus on a purely Java stack. In a world where time is money and lots of places already focusing on Java development, one less language/piece in the stack makes training and maintaining faster and thus cheaper.
I'll add that JavaScript is easy to become a maintenance nightmare on large teams, especially if some of the developers on the project are not highly web savvy.
With Javascript and frameworks such as jQuery you have full flexibility and full control . With ext's etc you lose much control and must adapt to the framework. With JSF you totally lose control and must totally adapt to the framework. You're invoked in lifecycles etc. and finally you have no control when the call to the server can be made and where not. If you are to do something considered 'special', you're in very hard position. And in JSF world even such basic things as multicolumn table sort or fields where you can type only limited set of characters (such as number field) are considered 'special'.
However, the more flexibility you have, the more errors or bad practices you can made. High flexibility works only with highly intelligent programmers, others will turn the project into unmanagable nightmare.
But, with JSF and its limited flexibility, there's always only a few (or even only one) correct way to do something. You are very limited, you can't make shortcuts, you must write more XML etc. - but when adapting to standard, there's better control on the code the unexperienced or low-skilled programmers will produce. As a result, big corporations love JSF because it is 'safer' for them.
When I moved from GWT to JSF, I was shocked, how many things, that was natural to me, was considered highly untypical and how much simple things were so hard to achieve. What's more, even making the smallest changes, such as adding ':' sign after label, which in GWT/jQuery powered app would be changing one function generating label, required changing dozens of files with localized properties, which wasn't even considered by anyone except me strange...
The benefits of using JSF are not only in generating xhtml + css + js. Sometimes JSF imposes a restriction on the markup you can generate, like any component based framework. But JSF is not just for that, its lifecyle helps greately. After validating the input it can update the model and sync your server side beans without any effort. you just say "whatever the user types here, check if it's a number, if yes then store it in the property YY in object XX" and JSF will do all that.
So yes, you can still use JQuery, JS, etc. But JSF provides many benefits when it comes to writing server side code and saves you from a lot of boiler plate.
I strongly disagree that jsf adds anything. It only adds overhead. Doing ui stuff on the server is the most ridiculous thing ive ever heard. And javascript on large teams works great - its called reusing code.
Just wrap the jquery in some jsp tags, thats all you need and youre done, and dont endure the.shackles and scalability issues with.jsf and richfaces.
Having worked with JSF, Spring MVC, Struts, Grails, JQuery, and ExtJS my opinion is that Grails + ExtJS is one powerful combination.
I would pick Grails over JSF any day. I like the completeness of ExtJS as the client side framework and library, but it comes with a steeper learning curve than JQuery.
Here are the biggest differences between jQuery & JSF:
no MVC architecture
no state control (store date in session or conversation, auto-clean up, etc.)
no (default) validation library
no templating library
no advanced navigation/routing
client side
jQuery was never intended to be used as a full stack webframework. It was more intended for replacing low-level JS code so that writing JS becomes easier and more powerfull in less lines of code.
And it should thus mostly be used to add behaviour on HTML elements.
Having used ExtJS framework for a large web application, I know how easy it is to use. The ExtJS (Schena) is best suited for (Oracle 11g) database interactions in MVC architecture. The View was for the visual / user interactions. The controller specified the 'processing' and the triggers that needed to be used form the PLSQL packages (the API for the CRUD, SQL select queries etc.). The Model and the store files were used to 'map' the data items to the Viewer / inputs.
ExtJS is not suitable for non database intensive web interfaces - where Angular JS may be a better fit.
This question already has answers here:
What is the difference between JSF, Servlet and JSP?
(16 answers)
Closed 7 years ago.
I have an application that sends the customer to another site to handle the payments. The other site, outside of the customer, calls a page on our server to let us know what the status is of the payment. The called page checks the parameters that are given by the payment application and checks to see whether the transaction is known to us. It then updates the database to reflect the status. This is all done without any interaction with the customer.
I have personally chosen to implement this functionality as a JSP since it is easier to just drop a file in the file system than to compile and package the file and then to add an entry into a configuration file.
Considering the functionality of the page I would presume that a servlet would be the preferred option. The question(s) are:
Is my presumption correct?
Is there a real reason to use a servlet over a JSP?
What are those reasons?
A JSP is compiled to a servlet the first time it is run. That means that there's no real runtime difference between them.
However, most have a tradition to use servlets for controllers and JSPs for views. Since controllers are just java classes you can get full tool support (code completion etc.) from all IDEs. That gives better quality and faster development times compared to JSPs. Some more advanced IDE's (IntelliJ IDEA springs to mind) have great JSP support, rendering that argument obsolete.
If you're making your own framework or just making it with simple JSPs, then you should feel free to continue to use JSPs. There's no performance difference and if you feel JSPs are easier to write, then by all means continue.
JSPs: To present data to the user. No business logic should be here, and certainly no database access.
Servlets: To handle input from a form or specific URL. Usually people will use a library like Struts/Spring on top of Servlets to clear up the programming. Regardless the servlet should just validate the data that has come in, and then pass it onto a backend business layer implementation (which you can code test cases against). It should then put the resulting values on the request or session, and call a JSP to display them.
Model: A data model that holds your structured data that the website handles. The servlet may take the arguments, put them into the model and then call the business layer. The model can then interface with back-end DAOs (or Hibernate) to access the database.
Any non-trivial project should implement a MVC structure. It is, of course, overkill for trivial functionality. In your case I would implement a servlet that called a DAO to update the status, etc, or whatever is required.
JSPs should be used in the presentation layer, servlets for business logic and back-end (usually database layer) code.
I don't know any reason why you can't use a JSP as you describe (it gets compiled to a servlet by the containter anyway), but you're right, the preferred method is to make it a servlet in the first place.
There are 2 pretty simple rules:
Whenever you want to write Java code (business logic), do it in a Java class (so, Servlet).
Whenever you want to write HTML/CSS/JS code (view/template logic), do it in a JSP.
Related question:
How to avoid Java code in JSP
JSPs are a shortcut to write a servlet. In fact they are translated to servlet java code before compilation. (You can check it under some tomcat subdir wich I don't remember the name).
To choose between servlet an JSP I use a simple rule: if the page contains more html code than java code, go for JSP, otherwise just write a servlet. In general that translates roughly to: use JSPs for content presentation and servlets for control, validation, etc.
Also, Its easier to organize and structure your code inside a servlet, since it uses the plain java class syntax. JSPs tend to be more monolithic, although its possible to create methods inside then.
JSP's are essentially markup that automatically gets compiled to a servlet by the servlet container, so the compile step will happen in both instances. This is why a servlet container that supports JSP must have the full JDK available as opposed to only needing the JRE.
So the primary reason for JSP is to reduce the amount of code required to render a page. If you don't have to render a page, a servlet is better.
I know this isn't the popular answer today, but: When I'm designing an app from scratch, I always use JSPs. When the logic is non-trivial, I create ordinary Java classes to do the grunt work that I call from the JSP. I've never understood the argument that you should use servlets because, as pure Java classes, they are more maintainable. A JSP can easily call a pure Java class, and of course an ordinary Java class is just as maintainable as any servlet. It's easier to format a page in a JSP because you can put all the markup in-line instead of having to write a bunch of println's. But the biggest advantage of JSPs is that you can just drop them in a directory and they are directly accessible: you don't need to mess with setting up relationships between the URL and the class file. Security is easily handled by having every JSP begin with a security check, which can be a single call statement, so there's no need to put security into a dispatch layer.
The only reason I can see to use a servlet is if you need a complex mapping between URLs and the resulting execution class. Like, if you want to examine the URL and then call one of many classes depending on session state or some such. Personally I've never wanted to do this, and apps I've seen that do do it tend to be hard to maintain because before you can even begin to make a change you have to figure out what code is really being executed.
Most java applications nowadays are build on the MVC pattern...
In the controller side (servlet) you implement business logic. The servlet controller usually forward the request to a jsp that will generate the actual html response (the View in MVC).
The goal is to separate concerns... Thousands of books have been written on that subject.
In an MVC architecture, servlets are used as controller and JSPs as view.
But both are technically the same. JSP will be translated into servlet, either in compile time (like in JDeveloper) or when accessed for the first time (like in Tomcat).
So the real difference is in the ease of use. I'm pretty sure that you'll have a hard time rendering HTML page using servlet; but opposite to common sense, you'll actually find it pretty easy to code even a fairly complex logic all inside JSP (with the help of some prepared helper class maybe). PHP guys do this all the time. And so they fall into the pitfall of creating spaghetti codes.
So my solution to your problem: if you found it easier to code in JSP and it wouldn't involve too many code, feel free to code in JSP. Otherwise, use servlet.
Agreed with all the points above about the differences between JSPs and Servlets, but here are a couple additional considerations. You write:
I have an application that sends the
customer to another site to handle the
payments. The other site, outside of
the customer, calls a page on our
server to let us know what the status
is of the payment. The called page
checks the parameters that are given
by the payment application and checks
to see whether the transaction is
known to us. It then updates the
database to reflect the status. This
is all done without any interaction
with the customer.
Your application is consuming the payment service of another application. Your solution is fragile because if the payment service in the other application changes, that breaks your JSP page. Or if you want to change your application's payment policies, then your page will have to change. The short answer is that your application should be consuming the application's payment service via a web service. Neither a servlet nor a JSP page is appropriate place to put your consumption logic.
Second, along those lines, most usages of servlets/JSP pages in the last few years have been put inside the context of a framework like Spring or Struts. I would recommend Spring, as it offers you the full stack of what you need from the server pages to web service gateway logic to DAOs. If you want to understand the nuts and bolts of Spring, I would recommend Spring in Action. If you need to understand better how to tier an enterprise architecture written in a language like Java (or C#), I would recommend Fowler's Patterns of Enterprise Application Architecture.
Yeah, this should be a servlet. A JSP may be easier to develop, but a servlet will be easier to maintain. Just imagine having to fix some random bug in 6 months and trying to remember how it worked.
In java servlet the HTML tags are embeded in java coding.
In JSP the java codings are embeded in HTML tags.
For big application for big problem the servlet is complex to read,understand,debug,etc because of unreadability of embeding more html tags inside the java coding..So we use jsp.In jsp it is easy to understand,debug,etc.
Thanks & Regards,
Sivakumar.j
i think its up to you?
because
JSP is Java inside of HTML
and Servlet is a Java that can do the HTML inside
hmmm... servlet is more sercure than jsp because if you submit to Servlet and forward to another JSP there is no file extension appear and also you cant see what Page it is..
but the advantage of JSP is you can code there easily.