JSP is a Java view technology running on the server machine which allows you to write template text in client side languages (like HTML, CSS, JavaScript, ect.). JSP supports taglibs, which are backed by pieces of Java code that let you control the page flow or output dynamically. A well-known taglib is JSTL. JSP also supports Expression Language, which can be used to access backend data (via attributes available in the page, request, session and application scopes), mostly in combination with taglibs.
When a JSP is requested for the first time or when the web app starts up, the servlet container will compile it into a class extending HttpServlet
and use it during the web app's lifetime. You can find the generated source code in the server's work directory. In for example Tomcat, it's the /work
directory. On a JSP request, the servlet container will execute the compiled JSP class and send the generated output (usually just HTML/CSS/JS) through the web server over a network to the client side, which in turn displays it in the web browser.
Servlet is a Java application programming interface (API) running on the server machine, which intercepts requests made by the client and generates/sends a response. A well-known example is the HttpServlet
which provides methods to hook on HTTP requests using the popular HTTP methods such as GET
and POST
. You can configure HttpServlet
s to listen to a certain HTTP URL pattern, which is configurable in web.xml
, or more recently with Java EE 6, with @WebServlet
annotation.
When a Servlet is first requested or during web app startup, the servlet container will create an instance of it and keep it in memory during the web app's lifetime. The same instance will be reused for every incoming request whose URL matches the servlet's URL pattern. You can access the request data by HttpServletRequest
and handle the response by HttpServletResponse
. Both objects are available as method arguments inside any of the overridden methods of HttpServlet
, such as doGet()
and doPost()
.
JSF is a component based MVC framework which is built on top of the Servlet API and provides components via taglibs which can be used in JSP or any other Java based view technology such as Facelets. Facelets is much more suited to JSF than JSP. It namely provides great templating capabilities such as composite components, while JSP basically only offers the <jsp:include>
for templating in JSF, so that you're forced to create custom components with raw Java code (which is a bit opaque and a lot of tedious work) when you want to replace a repeated group of components with a single component. Since JSF 2.0, JSP has been deprecated as view technology in favor of Facelets.
Note: JSP itself is NOT deprecated, just the combination of JSF with JSP is deprecated.
Note: JSP has great templating abilities by means of Taglibs, especially the (Tag File) variant. JSP templating in combination with JSF is what is lacking.
As being a MVC (Model-View-Controller) framework, JSF provides the FacesServlet
as the sole request-response Controller. It takes all the standard and tedious HTTP request/response work from your hands, such as gathering user input, validating/converting them, putting them in model objects, invoking actions and rendering the response. This way you end up with basically a JSP or Facelets (XHTML) page for View and a JavaBean class as Model. The JSF components are used to bind the view with the model (such as your ASP.NET web control does) and the FacesServlet
uses the JSF component tree to do all the work.
Related questions
Actually, all of those examples on the web wherein the common content/file type like "js", "css", "img", etc is been used as library name are misleading.
Real world examples
To start, let's look at how existing JSF implementations like Mojarra and MyFaces and JSF component libraries like PrimeFaces and OmniFaces use it. No one of them use resource libraries this way. They use it (under the covers, by @ResourceDependency
or UIViewRoot#addComponentResource()
) the following way:
<h:outputScript library="javax.faces" name="jsf.js" />
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<h:outputScript library="omnifaces" name="omnifaces.js" />
<h:outputScript library="omnifaces" name="fixviewstate.js" />
<h:outputScript library="omnifaces.combined" name="[dynamicname].js" />
<h:outputStylesheet library="primefaces" name="primefaces.css" />
<h:outputStylesheet library="primefaces-aristo" name="theme.css" />
<h:outputStylesheet library="primefaces-vader" name="theme.css" />
It should become clear that it basically represents the common library/module/theme name where all of those resources commonly belong to.
Easier identifying
This way it's so much easier to specify and distinguish where those resources belong to and/or are coming from. Imagine that you happen to have a primefaces.css
resource in your own webapp wherein you're overriding/finetuning some default CSS of PrimeFaces; if PrimeFaces didn't use a library name for its own primefaces.css
, then the PrimeFaces own one wouldn't be loaded, but instead the webapp-supplied one, which would break the look'n'feel.
Also, when you're using a custom ResourceHandler
, you can also apply more finer grained control over resources coming from a specific library when library
is used the right way. If all component libraries would have used "js" for all their JS files, how would the ResourceHandler
ever distinguish if it's coming from a specific component library? Examples are OmniFaces CombinedResourceHandler
and GraphicResourceHandler
; check the createResource()
method wherein the library is checked before delegating to next resource handler in chain. This way they know when to create CombinedResource
or GraphicResource
for the purpose.
Noted should be that RichFaces did it wrong. It didn't use any library
at all and homebrewed another resource handling layer over it and it's therefore impossible to programmatically identify RichFaces resources. That's exactly the reason why OmniFaces CombinedResourceHander
had to introduce a reflection-based hack in order to get it to work anyway with RichFaces resources.
Your own webapp
Your own webapp does not necessarily need a resource library. You'd best just omit it.
<h:outputStylesheet name="css/style.css" />
<h:outputScript name="js/script.js" />
<h:graphicImage name="img/logo.png" />
Or, if you really need to have one, you can just give it a more sensible common name, like "default" or some company name.
<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />
Or, when the resources are specific to some master Facelets template, you could also give it the name of the template, so that it's easier to relate each other. In other words, it's more for self-documentary purposes. E.g. in a /WEB-INF/templates/layout.xhtml
template file:
<h:outputStylesheet library="layout" name="css/style.css" />
<h:outputScript library="layout" name="js/script.js" />
And a /WEB-INF/templates/admin.xhtml
template file:
<h:outputStylesheet library="admin" name="css/style.css" />
<h:outputScript library="admin" name="js/script.js" />
For a real world example, check the OmniFaces showcase source code.
Or, when you'd like to share the same resources over multiple webapps and have created a "common" project for that based on the same example as in this answer which is in turn embedded as JAR in webapp's /WEB-INF/lib
, then also reference it as library (name is free to your choice; component libraries like OmniFaces and PrimeFaces also work that way):
<h:outputStylesheet library="common" name="css/style.css" />
<h:outputScript library="common" name="js/script.js" />
<h:graphicImage library="common" name="img/logo.png" />
Library versioning
Another main advantage is that you can apply resource library versioning the right way on resources provided by your own webapp (this doesn't work for resources embedded in a JAR). You can create a direct child subfolder in the library folder with a name in the \d+(_\d+)*
pattern to denote the resource library version.
WebContent
|-- resources
| `-- default
| `-- 1_0
| |-- css
| | `-- style.css
| |-- img
| | `-- logo.png
| `-- js
| `-- script.js
:
When using this markup:
<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />
This will generate the following HTML with the library version as v
parameter:
<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&v=1_0" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&v=1_0"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&v=1_0" alt="" />
So, if you have edited/updated some resource, then all you need to do is to copy or rename the version folder into a new value. If you have multiple version folders, then the JSF ResourceHandler
will automatically serve the resource from the highest version number, according to numerical ordering rules.
So, when copying/renaming resources/default/1_0/*
folder into resources/default/1_1/*
like follows:
WebContent
|-- resources
| `-- default
| |-- 1_0
| | :
| |
| `-- 1_1
| |-- css
| | `-- style.css
| |-- img
| | `-- logo.png
| `-- js
| `-- script.js
:
Then the last markup example would generate the following HTML:
<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&v=1_1" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&v=1_1"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&v=1_1" alt="" />
This will force the webbrowser to request the resource straight from the server instead of showing the one with the same name from the cache, when the URL with the changed parameter is been requested for the first time. This way the endusers aren't required to do a hard refresh (Ctrl+F5 and so on) when they need to retrieve the updated CSS/JS resource.
Please note that library versioning is not possible for resources enclosed in a JAR file. You'd need a custom ResourceHandler
. See also How to use JSF versioning for resources in jar.
See also:
Best Answer
How does it work?
When a JSF view (Facelets/JSP file) get built/restored, a JSF component tree will be produced. At that moment, the view build time, all
binding
attributes are evaluated (along withid
attribtues and taghandlers like JSTL). When the JSF component needs to be created before being added to the component tree, JSF will check if thebinding
attribute returns a precreated component (i.e. non-null
) and if so, then use it. If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behindbinding
attribute with the autocreated component instance as argument.In effects, it binds a reference of the component instance in the component tree to a scoped variable. This information is in no way visible in the generated HTML representation of the component itself. This information is in no means relevant to the generated HTML output anyway. When the form is submitted and the view is restored, the JSF component tree is just rebuilt from scratch and all
binding
attributes will just be re-evaluated like described in above paragraph. After the component tree is recreated, JSF will restore the JSF view state into the component tree.Component instances are request scoped!
Important to know and understand is that the concrete component instances are effectively request scoped. They're newly created on every request and their properties are filled with values from JSF view state during restore view phase. So, if you bind the component to a property of a backing bean, then the backing bean should absolutely not be in a broader scope than the request scope. See also JSF 2.0 specitication chapter 3.1.5:
Otherwise, component instances are shared among multiple requests, possibly resulting in "duplicate component ID" errors and "weird" behaviors because validators, converters and listeners declared in the view are re-attached to the existing component instance from previous request(s). The symptoms are clear: they are executed multiple times, one time more with each request within the same scope as the component is been bound to.
And, under heavy load (i.e. when multiple different HTTP requests (threads) access and manipulate the very same component instance at the same time), you may face sooner or later an application crash with e.g. Stuck thread at UIComponent.popComponentFromEL, or Java Threads at 100% CPU utilization using richfaces UIDataAdaptorBase and its internal HashMap, or even some "strange"
IndexOutOfBoundsException
orConcurrentModificationException
coming straight from JSF implementation source code while JSF is busy saving or restoring the view state (i.e. the stack trace indicatessaveState()
orrestoreState()
methods and like).Using
binding
on a bean property is bad practiceRegardless, using
binding
this way, binding a whole component instance to a bean property, even on a request scoped bean, is in JSF 2.x a rather rare use case and generally not the best practice. It indicates a design smell. You normally declare components in the view side and bind their runtime attributes likevalue
, and perhaps others likestyleClass
,disabled
,rendered
, etc, to normal bean properties. Then, you just manipulate exactly that bean property you want instead of grabbing the whole component and calling the setter method associated with the attribute.In cases when a component needs to be "dynamically built" based on a static model, better is to use view build time tags like JSTL, if necessary in a tag file, instead of
createComponent()
,new SomeComponent()
,getChildren().add()
and what not. See also How to refactor snippet of old JSP to some JSF equivalent?Or, if a component needs to be "dynamically rendered" based on a dynamic model, then just use an iterator component (
<ui:repeat>
,<h:dataTable>
, etc). See also How to dynamically add JSF components.Composite components is a completely different story. It's completely legit to bind components inside a
<cc:implementation>
to the backing component (i.e. the component identified by<cc:interface componentType>
. See also a.o. Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime and How to implement a dynamic list with a JSF 2.0 Composite Component?Only use
binding
in local scopeHowever, sometimes you'd like to know about the state of a different component from inside a particular component, more than often in use cases related to action/value dependent validation. For that, the
binding
attribute can be used, but not in combination with a bean property. You can just specify an in the local EL scope unique variable name in thebinding
attribute like sobinding="#{foo}"
and the component is during render response elsewhere in the same view directly asUIComponent
reference available by#{foo}
. Here are several related questions where such a solution is been used in the answer:Use an EL expression to pass a component ID to a composite component in JSF
(and that's only from the last month...)
See also: