How can I implement CSS Cache Busting with JSF outputStylesheet? - java

In JSF page templates I use this code to include a CSS resource:
<h:outputStylesheet library="css" name="mystyles.css" />
The usual way to implement CSS cache busting would be to add a version parameter, like v=123, however this is not supported in outputStyleSheet:
<h:outputStylesheet library="css" name="mystyles.css?v=123" />
will cause a JSF1064 warning and the CSS will not be found.

That's not possible without overridding the StylesheetRenderer (assuming you're on Mojarra). It does indeed not take the query string into account. However, as a (temporary) workaround it's good to know that it is valid to include the CSS using CSS' own #import rule inside <h:outputStyleSheet>.
<h:outputStylesheet target="head">
#import url('css/mystyles.css?v=123')
</h:outputStylesheet>
You might want to post an enhancement request to the Mojarra boys to take this into account in future releases.

Related

jsp:include vs %#include for %#taglib functionality [duplicate]

It seems that there are two methods for templating with JSP. Including files with one of these statements
<%# include file="foo.html" %>
<jsp:include page="foo.html" />
or using JSP tag files
// Save this as mytag.tag
<%# tag description="Description" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>
<jsp:doBody/>
</body>
</html>
And in another JSP page call it with
<%# taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:mytag>
<h1>Hello World</h1>
</t:mytag>
So which method should I use? Is one now considered deprecated or are they both valid and cover different use cases?
Edit
Isn't using this tag file the same as using an include?
// Save this as product.tag
<%# tag description="Product templage" pageEncoding="UTF-8"%>
<%# tag import="com.myapp.Product" %>
<%# attribute name="product" required="true" type="com.myapp.Product"%>
Product name: ${product.name} <br/>
Quantity: ${product.quantity} <br/>
And call it on another JSP with
<%# taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:product>
<c:forEach items="${cart.products}" var="product">
<t:product product="${product}"/>
</c:forEach>
</t:product>
That seems to me to be the very same as using an include and passing parameters to it. So are Tag Files the same as includes?
Overview of JSP Syntax Elements
First, to make things more clear, here is a short overview of JSP syntax elements:
Directives: These convey information regarding the JSP page as a
whole.
Scripting elements: These are Java coding elements such as
declarations, expressions, scriptlets, and comments.
Objects and scopes: JSP objects can be created either explicitly or
implicitly and are accessible within a given scope, such as from
anywhere in the JSP page or the session.
Actions: These create objects or affect the output stream in the JSP
response (or both).
How content is included in JSP
There are several mechanisms for reusing content in a JSP file.
The following 4 mechanisms to include content in JSP can be categorized as direct reuse:
(for the first 3 mechanisms quoting from "Head First Servlets and JSP")
1) The include directive:
<%# include file="header.html" %>
Static: adds the content from the value of the file attribute to the current page at translation time. The directive was
originally intended for static layout templates, like HTML headers.
2) The <jsp:include> standard action:
<jsp:include page="header.jsp" />
Dynamic: adds the content from the value of the page attribute to the current page at request time. Was intended more for dynamic
content coming from JSPs.
3) The <c:import> JSTL tag:
<c:import url=”http://www.example.com/foo/bar.html” />
Dynamic: adds the content from the value of the URL attribute to the current page, at request time. It works a lot like
<jsp:include>, but it’s more powerful and flexible: unlike the
other two includes, the <c:import> URL can be from outside the
web Container!
4) Preludes and codas:
Static: preludes and codas can be applied only to the beginnings and ends of pages.
You can implicitly include preludes (also called headers) and codas
(also called footers) for a group of JSP pages by adding
<include-prelude> and <include-coda> elements respectively within
a <jsp-property-group> element in the Web application web.xml deployment descriptor.
Read more here:
• Configuring Implicit Includes at the Beginning and End of JSPs
• Defining implicit includes
Tag File is an indirect method of content reuse, the way of encapsulating reusable content.
A Tag File is a source file that contains a fragment of JSP code that is reusable as a custom tag.
The PURPOSE of includes and Tag Files is different.
Tag file (a concept introduced with JSP 2.0) is one of the options for creating custom tags. It's a faster and easier way to build custom tags.
Custom tags, also known as tag extensions, are JSP elements that allow custom logic and output provided by other Java components to be inserted into JSP pages. The logic provided through a custom tag is implemented by a Java object known as a tag handler.
Some examples of tasks that can be performed by custom tags include operating on implicit objects, processing forms, accessing databases and other enterprise services such as email and directories, and implementing flow control.
Regarding your Edit
Maybe in your example (in your "Edit" paragraph), there is no difference between using direct include and a Tag File. But custom tags have a rich set of features. They can
Be customized by means of attributes passed from the calling page.
Pass variables back to the calling page.
Access all the objects available to JSP pages.
Communicate with each other. You can create and initialize a JavaBeans component, create a public EL variable that refers to that bean in one tag, and then use the bean in another tag.
Be nested within one another and communicate by means of private variables.
Also read this from "Pro JSP 2": Understanding JSP Custom Tags.
Useful reading.
Difference between include directive and include action in
JSP
JSP tricks to make templating
easier
Very informative and easy to understand tutorial from coreservlet.com with beautiful
explanations that include <jsp:include> VS. <%# include %>
comparison table:
Including Files and Applets in JSP
Pages
Another nice tutorial from coreservlets.com related to tag libraries and
tag files:
Creating Custom JSP Tag Libraries: The
Basics
The official Java EE 5 Tutorial with examples:
Encapsulating Reusable Content
Using Tag
Files.
This page from the official Java EE 5 tutorial should give you even
more understanding:
Reusing Content in JSP
Pages.
This excerpt from the book "Pro JSP 2" also discuses why do you need
a Tag File instead of using static include:
Reusing Content with Tag
Files
Very useful guide right from the Oracle documentation:
Static Includes Versus Dynamic Includes
Conclusion
Use the right tools for each task.
Use Tag Files as a quick and easy way of creating custom tags that can help you encapsulate reusable content.
As for the including content in JSP (quote from here):
Use the include directive if the file changes rarely. It’s the fastest mechanism. If your container doesn’t automatically detect changes, you can force the changes to take effect by deleting the main page class file.
Use the include action only for content that changes often, and if which page to include cannot be decided until the main page is requested.
Possible Duplicate Question
<#include> - The directive tag instructs the JSP compiler to merge contents of the included file into the JSP before creating the generated servlet code. It is the equivalent to cutting and pasting the text from your include page right into your JSP.
Only one servlet is executed at run time.
Scriptlet variables declared in the parent page can be accessed in the included page (remember, they are the same page).
The included page does not need to able to be compiled as a standalone JSP. It can be a code fragment or plain text. The included page will never be compiled as a standalone. The included page can also have any extension, though .jspf has become a conventionally used extension.
One drawback on older containers is that changes to the include pages may not take effect until the parent page is updated. Recent versions of Tomcat will check the include pages for updates and force a recompile of the parent if they're updated.
A further drawback is that since the code is inlined directly into the service method of the generated servlet, the method can grow very large. If it exceeds 64 KB, your JSP compilation will likely fail.
<jsp:include> - The JSP Action tag on the other hand instructs the container to pause the execution of this page, go run the included page, and merge the output from that page into the output from this page.
Each included page is executed as a separate servlet at run time.
Pages can conditionally be included at run time. This is often useful for templating frameworks that build pages out of includes. The parent page can determine which page, if any, to include according to some run-time condition.
The values of scriptlet variables need to be explicitly passed to the include page.
The included page must be able to be run on its own.
You are less likely to run into compilation errors due to the maximum method size being exceeded in the generated servlet class.
Depending on your needs, you may either use <#include> or
<jsp:include>
Main advantage of <jsp:include /> over <%# include > is:
<jsp:include /> allows to pass parameters
<jsp:include page="inclusion.jsp">
<jsp:param name="menu" value="objectValue"/>
</jsp:include>
which is not possible in <%#include file="somefile.jsp" %>
All three template options - <%#include>, <jsp:include> and <%#tag> are valid, and all three cover different use cases.
With <#include>, the JSP parser in-lines the content of the included file into the JSP before compilation (similar to a C #include). You'd use this option with simple, static content: for example, if you wanted to include header, footer, or navigation elements into every page in your web-app. The included content becomes part of the compiled JSP and there's no extra cost at runtime.
<jsp:include> (and JSTL's <c:import>, which is similar and even more powerful) are best suited to dynamic content. Use these when you need to include content from another URL, local or remote; when the resource you're including is itself dynamic; or when the included content uses variables or bean definitions that conflict with the including page. <c:import> also allows you to store the included text in a variable, which you can further manipulate or reuse. Both these incur an additional runtime cost for the dispatch: this is minimal, but you need to be aware that the dynamic include is not "free".
Use tag files when you want to create reusable user interface components. If you have a List of Widgets, say, and you want to iterate over the Widgets and display properties of each (in a table, or in a form), you'd create a tag. Tags can take arguments, using <%#tag attribute> and these arguments can be either mandatory or optional - somewhat like method parameters.
Tag files are a simpler, JSP-based mechanism of writing tag libraries, which (pre JSP 2.0) you had to write using Java code. It's a lot cleaner to write JSP tag files when there's a lot of rendering to do in the tag: you don't need to mix Java and HTML code as you'd have to do if you wrote your tags in Java.
According to:
Java Revisited
Resources included by include directive are loaded during jsp translation time, while resources included by include action are loaded during request time.
Any change on included resources will not be visible in case of include directive until jsp file compiles again. While in case of include action, any change in included resource will be visible in the next request.
Include directive is static import, while include action is dynamic import.
Include directive uses file attribute to specify resources to be included while include action uses page attribute for the same purpose.

Loading messages from resource bundle in Struts 2

I want to load resource bundle (I have two: one for selected language and another default) dynamically in JSP and read the content in JSP. I have tried following way but its just hard-coded.
<s:i18n name="resourcebundle_fr">
<s:text name="fr_message1" />
</s:i18n>
where what I want is instead of resourcebundle_fr, I want it to be dynamic.
Also, the same page has included another JSP page which should also pick the messages from the selected language specific resource bundle.
Struts2 tags has support for OGNL. You can use OGNL expressions in the Struts tag's attributes.
<s:i18n name="%{resourceBundle}">
<s:text name="fr_message1" />
</s:i18n>

Sitemesh change decorator on runtime

My greetings!
The question is pretty short: is there any way to change the decorator during runtime? For example, I have a dropdown menu with some "decorator styles", so when the user chooses different style, it will change the decorator.
If you have any useful links on this topic, I'd be very grateful.
Found this thread - SiteMesh: Changing the content-type of the response - but still, no help.
I know you can use a meta HTML tag to specify which decorator you want to use with your JSP files. For example in the file login.jsp where I need the login decorator:
<head>
<meta name="decorator" content="login" />
<!-- where "login" is the name of the decorator -->
</head>
So, I never tried yet, but you could probably give the name of the decorator through a POST or a GET parameter, and using it within the meta tag:
<meta name="decorator" content="${decoratorName}" />

c:url tag includes jsession id query string

What is the best way of obtaining context-root on a jsp page. If I hardcode my css/image to "/myapp/images/foo.gif" then it will be a broken link if the context root / app name is changed. Using relative path is not always preferrable because a context root can be multi-path (eg: /mysite/myapp)
So far I've tried using <c:url var="root" value="/"/> which works alright (${root} will give the context-root /myapp/), however if this is the very first time user is visiting the site (or if cookie is cleaned on the browser), the value assigned to ${root} became something like /myapp/;jsessionid=019762g1hk3781kh98uihilho and it breaks the images/css reference. Is there any other better way than this?
So far I've tried using <c:url var="root" value="/"/> which works alright (${root} will give the context-root /myapp/)
This is not the right way. The <c:url> should be applied on every single URL individually.
You'd better use
<c:set var="root" value="${pageContext.request.contextPath}" />
See also:
Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

Rendering my own <script> tag instead of the one provided by JSF

I have page which consists of couple fragments and in the "header" fragment I have this tag <webuijsf:script id="script_logo" url="/resources/logo.js"/>. This is rendered in HTML as <script src="/app/resources/logo.js" type="text/javascript" id="Header:script_logo"></script>. This is fine and it is working as expected. Now I need to force JSF somehow to return URL to the javascript with current version of app. This is known technique for forcing the reload of resource (javascript, css and images) in case they are cashed on client's side. I need to render something like <script src="/app/resources/logo.js?ver=1.0.405" type="text/javascript" id="Header:script_logo"></script>. Please note the ver parameter in the URL.
Thanks.
Tomas
Well, you can simply add it to the page:
<script src="/app/resources/logo.js?ver=#{commonBean.version}" ...>
I've assumed you want to version to be configurable and sent by the server, so commonBean is some jsf bean that returns the proper version.
Update: also take a look at <rich:loadScritp>. (from RichFaces)
The final option is to create your own component and include the version automatically. Look for tutorial for how to make that, it's not easy for JSF 1.2
Well thats pretty easy. JSF 2 uses a configuration to Bind a renderer to a component.
Therefor you need a component-family and a renderer-type. Now you can define in your
faces-config.xml a renderer for that family and renderer-type.
In Mojorra the following configuration is set for a outputScript-Component:
<renderer>
<component-family>javax.faces.Output</component-family>
<renderer-type>javax.faces.resource.Script</renderer-type>
<renderer-class>com.sun.faces.renderkit.html_basic.ScriptRenderer</renderer-class>
</renderer>
I must admit, that this info is coming from my debugging. I debugged the ScriptRenderer
and was able to get the component-family and renderer-type from the UIComponent.
Now if you use an other Renderer for that Component, just change the configuration
and the original will be overwritten:
<renderer>
<component-family>javax.faces.Output</component-family>
<renderer-type>javax.faces.resource.Script</renderer-type>
<renderer-class>your.own.renderer.class</renderer-class>
</renderer>
Do not forget, all h:outputScript components will render now with the new Renderer.
Same goes with stylesheets, but those will have an other render-type.

Categories

Resources