How do JSF view technologies translate client-side? - java

So I understand that JSPs are a mixture of a client-side code (DHTML, JS, CSS, etc.) and Java. In this way, JSPs are kind of like pure PHP or pure ASP. When the web container receives a request for a JSP, it compiles the Java inside the JSP, executes it and then returns the resultant client-side code in the HTTP Response.
I also understand that an alternative to JSPs are Servlets, or a Servlet/templating combo, like FreeMarker. The servlets contain pure Java (business logic), and the templates contain presentation logic.
What I don't understand is how JSF-derived technologies like RichFaces, PrimeFaces and ICEFaces turn Java code into client-side code that can run in a browser. I've also heard that the major draw to these frameworks are the "rich" UI controls they come with, but am having a tough time connecting all the dots.
Do these frameworks get compiled to JS like the GWT does? If that's the case then I would assume that these rich UI controls would be the same as, say, jQuery UI controls that are just pure JS.
If that's not the case then I just don't understand (at all) how these frameworks turn server-side code into "stuff" that can execute client-side.
Thanks in advance!

What I don't understand is how JSF-derived technologies like RichFaces, PrimeFaces and ICEFaces turn Java code into client-side code that can run in a browser
The HTML is generated by encodeXxx() methods of UIComponent and/or Renderer implementations. Those methods are invoked during render response phase, starting with the UIViewRoot which delegates the call all the way through the entire component tree hierarchy.
JSF implementations such as Mojarra and practically all component libraries are open source. To take the JSF standard <h:inputText> component as an example, start looking at com.sun.faces.renderkit.html_basic.TextRenderer class to see all the HTML generating code.
Do these frameworks get compiled to JS like the GWT does?
Absolutely not. Open a JSF page in browser, rightclick and View Source. It's all just HTML code, if necessary along with auto-included CSS/JS files. With GWT it's one and all JS code.
See also:
Java EE 6 tutorial - Creating custom components - to learn how to program it yourself.
What is the difference between JSF, Servlet and JSP?
What is the need of JSF, when UI can be achieved from CSS, HTML, JavaScript, jQuery?

No, JSF is not something like GWT. The idea is different. But let's start from the beginning.
Servlets are not really alternative to JSP. JSP is a technology, which is responsible for View part in Model-View-Controller design pattern. Servlets usually play role of the Controller.
In a typical scenario Servlet receives request from the user, parses it and calls bussines logic (Model) - it could be just the set of java classes or EJB components or whatever else which calculates something, talks to database, etc. Then Servlet gets the data from bussines logic (if any) and redirects user to a proper View element - JSP, pure HTML page, some template engine, etc.
JSF is sort of a layer over JSP + Servlets that makes programmers' live easier (although many would strongly diagree with that :) )
JSF page is basically a JSP page, that uses set of specialized tags - components (JSF native tags or RichFaces tags or ICE Faces tags). These tags can be written in Java, can boundle JavaScript, CSS. The final effect is that these tags generate HTML representing "component", for instance fancy table with sorting capabilites.
So you have for instance component that you place on JSP page and it represents nicely looking table.
In addition JSF is armed with standard controller, which is not written in Java, but is a set of navigation rules between pages written in XML.
One more element are JSF Beans, which are bounded to JSF pages and are automatically filled with data taken from these pages. It is often quite straighforward - user fills the form, which is a part of JSF page (form also use specialized tags - components). Once this form is submitted the JSF Bean class is filled with data and action method is called. The action method returns a string, which is used to identify page to which user should be redirected (the rule is taken from XML controller configuration).
So in case JSF the frontend part is generated in backend - JSF tags (or components, as people call them) are interpreted in the backend and the backend generates HTML from them.
This could be contrasted with thechnologies, which separates frontend and backend. Backend receives and returns data in the form of XML or, more often, JSON and exchanges them with frontend part of the application. Frontend could be written in JavaScript, Flex, etc. So backend and frontend are totally separated.

Related

Programmatically Display a web page from a Servlet class

I'm really new to JSP and Servlets and all that jazz, and I'm confused about how to approach it.
Right now my main confusion is as follows:
It seems there are two ways to get a web page to display on the screen in a Java EE/JSP project:
Create an HTML page with the extension .jsp and in the web.xml file, map it to a url pattern (let's assume just /)
Create a Java class that extends Servlet, override the doGET() method to return a string of HTML code and map to this Java class in the web.xml.
My JSP project requires a decent amount of Java code to perform logic and login/logout operations. I've read that it's bad practice to inlcude Java code inside JSP pages as it becomes impossible to reuse, hard to keep track of, messy etc. I want to include much of code in Java, which will feel much more natural for me.
How should I build my project (assuming it's a simple beginner project in which I want to employ the best practices for organization, testing etc in preparation for building a larger project)? How can cleanly deploy web pages from inside Java classes, rather than having many JSP pages containing bits of Java code?
The pattern I've used in the past is to:
1) Write the servlet to perform whatever logic is necessary and to construct a reasonable number of serializable java objects to hold all of the data you want to be rendered via HTML.
2) The servlet stores those objects into the HTTP request and forwards the request and response objects to a JSP:
request.getRequestDispatcher("/some.jsp").forward(request, response);
3) The JSP can access the java objects in the request and merge the data with the static HTML to complete the request.
This is exactly the problem MVC pattern solves.
You do all your complex logic in the Controller (simple Java class, or a Servlet), then pass the data to View (JSP, Velocity, Freemarker, anything that can process the data and make a HTML).
There are several implementations of MVC for Java most popular being Spring MVC and Struts. Alternatively, you can just use your servlet for all your logic and then manually forward the request to a JSP for processing:
request.getRequestDispatcher("/index.jsp").forward(request,response);
If your are looking for best practices in clean separation of java code from the presentation, you might as well use a MVC Framework (Spring MVC or Struts are well know examples) that will help you to cleanly separate :
view layer (JSP)
controller layer
service layer
domain objects
persistence layer
It may be hard to begin with, but you will find nice tutorials through official sites and google.
If you want to only use servlets and JSP, the common rule is to have all logic and Java code in servlets, and that those servlets simply forward to JSP pages that will do the view part. The communication between then is done with request attributes (and of course, session and application context attributes.
Good luck ...
To manage bit of java code, you can use Scriptlet.
Also mentioned in other answers, you can use jsp:forward or response.sendRedirect
to call web pages.
Also see What is the difference between jsp:forward and response.sendRedirect
I'm not sure where you heard that its bad practice to include Java code in the HTML(JSP) files but in order to have a dynamically data driven website, Java is what you would use in the HTML(JSP). Keep in mind, all of your front end design will be in the HTML using JSP, and all of the your logic for handling requests and redirectors and passing data will be managed in the servlets using Java.
Your servlets can pass data, whether it be from a database or other data source, to the front end and your JSP will just help in displaying that data. It's called JSP for a reason. You can write Java in it.
The best approach for designing websites in Java is to use the MVC pattern that way it helps seperate all of the core functions of the site and can easily be scaled and managed.
Do you have any code that you have to show what you have done so far?

Working of MVC architecture for Servlets

So, yeah, this is what I understood.
Servlet is just an intermediary responsible for finding out what the parameters in the request mean. These parameters are given to the .java file. It is a mere intermediary
.java file is the Model which does business logic
View is the JSP that will do the presentation
Did I get that right?
The Model View Controller pattern is not specific to Java or Servlet technology. There are many non-java MVC implementations, and in Java, there are non-Servlet implementations (Swing is an example).
In Java, when using Servlet-based MVC, usually an MVC framework is used. There are two main categories here: action based and component based, the difference being that action based frameworks listen each registered URL independently while component based frameworks keep a component tree and maintain server-side state.
Action based frameworks are Spring MVC, Struts 1+2, Stripes, Play etc. Component based frameworks are Wicket, JSF 1 & 2, Tapestry etc.
Your diagram gets close to the truth, but there are a few subtle misconceptions.
First, it doesn't make sense to speak of .java files. Java source files are totally irrelevant to a deployed web application, it uses compiled .class files only, and the JavaVM can be programmed in many different languages, so the application doesn't care whether the .class files were compiled from Java, Scala, Groovy, JRuby, Clojure, AspectJ or anything else as long as they comply to the Java Class File specification.
Second, while JSP has long been the default view technology in Java Servlet technology, it's far from the only one. Other technologies include Facelets, Velocity, Freemarker etc., and there's also nothing to stop you from writing data directly to a request from a controller without a dedicated view technology (although this is usually not advisable).
Basically, what MVC stands for is a system where there is separate code for business logic (the M), the view technology (V) and the Controller that ties things together. In a well-organized MVC architecture, the M part is so well encapsulated that the same business logic can also be executed through other channels (e.g. web services, direct library access etc.). Also, it should be possible to switch view technologies through configuration from the outside without editing the actual controller logic.
I would advise you to read the docs for the Spring MVC framework, it is to my knowledge the most robust (and also easy-to-use) MVC framework out there, and the tooling support is also great (in either InteliJ Idea or the Eclipse-based SpringSource Tool Suite).
When you are talking about MVC, then all three layers should be separated from each other.
In web application :
1: A controller should be responsible handling the user request then filtering & executing the appropriate actions and then forward the generated response to the client.
2: A model consist of your Business logic,beans & Pojo classes. This should deal with you logic ,perform some operation and renders the generated result to some kind of persistent object or DTO's.
3: A view is consist of your GUI, some presentation-logic , it should be separated from your back-end ,ultimately you are showing an encapsulated form of result to your client i.e. what a client actually needed.
There are two types of MVC: MVC1(Push-MVC) and MVC2(Pull-MVC)
Pull-MVC and Push-MVC are better understood with how the view layer is getting data i.e. Model to render. In case of Push-MVC the data( Model) is constructed and given to the view layer by the Controllers by putting it in the scoped variables like request or session. Typical example is Spring MVC and Struts1. Pull-MVC on the other hand puts the model data typically constructed in Controllers are kept in a common place i.e. in actions, which then gets rendered by view layer. Struts2 is a Pull-MVC based architecture, in which all data is stored in Value Stack and retrieved by view layer for rendering.

Spring MVC with JSP

Are there any sample / tutorial on Spring MVC with JSP without using Tag Libraries. Pure JSP.
I am not conversant with Tag Libraries and I am good with JSP. So I would like to see if there are any examples and tutorials using pure JSP without ANY tag libraries.
I don't mean to say this in a degrading manner, but if you are good with JSP, you should be able to pick up the Spring MVC tags easily. JSP, custom tags and ELs go hand-in-hand. They are created for a reason: to make your life simpler. A quick example, if you use Spring MVC's form tag, Spring MVC will automatically prefill the form fields for you based on the data you have in the model. Think about how tedious your code will be to prefill the checkboxes/radiobuttons or preselect the drop down lists.
If you are also Spring Security, the provided custom tags allow you to easily control what data to be displayed based on the user roles.
Writing all of that using pure JSP don't even make sense to me... not to mention the amount of time wasted writing less than perfect home grown solutions.

Use of JSTL in a web app

I am a front end or UI developer with limited understanding of Java. I have a java based web app with JSTL used in it..I would like to understand the exact use of JSTL. Is it always used within JSP pages and is it used only for getting data from the database. Could you please explain with some basic examples..
JSP tags are used to generate HTML dynamically in a JSP, but without mixing Java code and HTML markup. The JSTL is a library of standard JSP tags. It means "JavaServer Pages Standard Tag Library", and as its name indicates, it's used within JSPs.
It should never be used to get data from the database. Getting data from the database should be done before executing the JSP, in a controller written in Java. Once the controller has done its job, it should dispatch the HTTP request to a view (the JSP), whose role is to render the data.
So if your application uses sql tags, then it's wrong. core and fmt tags are OK. As the Java EE tutorial indicates :
The JSTL SQL tags for accessing
databases listed in Table 7-7 are
designed for quick prototyping and
simple applications. For production
applications, database operations are
normally encapsulated in JavaBeans
components.
JSTL - JavaServer Pages Standard Tag Library - was designed to overcome a shortcoming in JSP, namely that a simpler way was needed to invoke Java libraries from the JSP page. The previous way to do it was to escape into Java with <%, %> and <%= and do what you needed, which led to very complex and difficult to maintain JSP pages.
JSTL give you new tags in addition to the HTML-tags you have in your JSP-pages, but which have special meaning server side, so it is interpreted when asked for by the client, and the result put in the actual page sent back to the client.
The tag definitions can do anything you can do in Java but you should strongly consider what you do where. Having e.g. SQL requests in your JSP-page mean that you tie business logic together with actual presentation, which has been - painfully - learned also gives complex and difficult to maintain web applications.
Is it always used within JSP pages
Yes.
... and is it used only for getting data from the database.
No. In fact, in most cases it is bad practice to access the database from a JSP, using JSTL or using other means (e.g. scriptlets).
does it mean like most JSP would have an associated Java file like 1-1 mapped, where the logic to get data using SQL query is written and is given to the JSP page.
Sort of. But there is not necessarily a 1 to 1 mapping:
Not all JSPs need to access the database.
A Java servlet may use multiple JSPs to render different output pages.
Different servlets may share a single JSP; e.g. to render a common error message page.
If yes, what exactly is the role of JSTL code within the JSP.
The aim of a JSP is to render output; typically HTML pages, but it could be anything text-based. JSTL is used within JSPs when the the output rendering logic is too complicated or messy to express using JSP EL.
UPDATE
The old-fashioned alternative to JSTL and JSP EL is to embed Java code ... i.e. scriptlets ... in the JSPs. For example:
<c:if test="${a == 'true'}">
hi
</c:if>
is equivalent to something like this:
<% if ("true".equals(context.findAttribute("a")) { %>
hi
<% } %>
Also for JSTL use, from what I understand, it is used within the JSP for dynamic HTML rendering through if-else statements.
You are describing HTML whose structure and content depends request parameters, configuration parameters, data fetched from the database and so in. This is the primary uses of JSTL.
However, this is NOT what is normally referred to as "Dynamic HTML". Dynamic HTML is where the browser changes the HTML of the currently displayed page, for e.g., when Javascript embedded in the page changes displayed page by modifying the DOM.
JSTL is a "custom tag library set" developed in and for the specifications of the J2EE server JSP servlet engine section. "Any tag in a Java J2EE spec. server markup page" configured for the java server written in Java2 J2EE spec is a "Custom Tag implementation" whether JSF , JSP , JSTL or Databasing cudtom tag. However it is not a Java Bean (only extremely similar to them in syntax and semantic to write a class program).
Each custom tag library has its own set of useful properties in java server markup and is why the system was developed. The Java Bean system is alike but is done through EL language.
A "tag" uses both a markup representation in the page and its co-bound(configured) .class file program in the server to process page markup and interface or join other server processes and programs.
JSTL is simply java server markup library for the JSP-servelt engine as JSF is a markup for the faces-servlet engine and both are only a custom tag.

jsp, servlets, faces and beans?

i´ve read a little about java's structure and could someone tell me if my view of all these components are correct:
JSP corresponds a View
Servlet corresponds a Controller
Bean corresponds a Model
Faces correspond layouts to render display
is this roughly correct?
JSPs are view technology - HTML with Java embedded in it.
Servlets should be used as controllers - they're Java classes that implement methods to read and write HTTP streams.
In a web app Javabeans are usually the model - JSPs and other Java view technologies understand how to access properties of Javabeans, bind them to forms, etc.
Faces is a separate stack JSF (Java Server Faces) is a component based web framework.
Yes, you're roughly correct.
Only, the Faces is more than just "layouts to render a display". JSF is a full fledged component based MVC framework which is built on top of the Servlet API. It uses the FacesServlet as the sole controller. It used to use JSP as view technology, which is now replaced by Facelets (XHTML) as per the new JSF 2.0 API. It uses the so-called backing beans as model. Then, you have taglibs/components which can be used in the view layer to generate HTML and uses Expression Language to associate the data/events with the model objects (the managed beans).

Categories

Resources