I want to do something like this: index.xhtml -> createPerson.xhtml -> addAddress.xhtml -> index.xhtml.
In Managed-Bean CreatePerson a new Person-Object will be created, filled and saved, in Managed-Bean AddAddress I need the Person-Object in order to add an address to this person and after this, it should navigate back to the starting point. I think, the Managed-Bean CreatePerson should be #SessionScoped, because I have to inject the Person-Object into AddAdress (here #ViewScoped).
I want to have a loop or rather the possibility to create more than one person, but how can I do this if I have a SessionScoped-Bean, that lives longer than I need it? Is there any command or annotation to destroy it? How do you handle such workflows related to the scopes?
I know about MyFaces Orchestra with conversation-scope, but I will, if possible, do it only with Eclipse/Tomcat (7.0.11)/Mojarra (2.0.3).
Use a single view and make use of the rendered attribute to show/hide included views with "subforms" depending on each other. This way you can go with a #ViewScoped bean.
Alternatively, just save the Person in the DB after create and pass its id as request parameter to the next view and let it load from the DB again.
If you only want (or can) use Tomcat and Mojarra then both solutions mentioned by BalusC work perfectly, although with the limitations that you have to stay on a single page or redo queries between page navigation. Your use case is exactly what the conversation scope in Java EE 6 (through CDI) is made for. You can add this too to Tomcat via the Weld reference implementation.
When using the method BalusC outlined for staying on a single page, to give the user a tiny bit the impression of dealing with separate pages, it might be an option to display the rendered parts of the page using 'dialogs' (floating, css, ...). If using a third party component library is an option for you, you could add RichFaces or PrimeFaces that both contain ready to use dialog components.
Related
I have this project with Liferay where I manage courses for a training center. So I'll have a bunch of portlets for creating courses, a year schedule, teachers, etc.
And then I have a series of screens & portlets where you can manage and monitor the evolution of a specific course. So basically I have like two hierarchical sections of a website where you can create the entities in one, and manage a specific entity in other.
What I want to have is these two sections clearly separated, this way:
So in the course section all my portlets and the navigation menu are dependant of a "global" parameter which is the selected course identifier.
But I am new at Liferay and I am struggling with something that I'm sure it's fairly easy -- how can I pass this courseId parameter through all my dependant portlets? Sort of like a global variable for that context only?
In a normal website I would just append the parameter in the URL and I'll be fine but having many portlets in this section I'm sure there's gotta be a better way than passing the parameter to every single one of them.
Well, a few ways to do this are mentioned in the wiki here.
This basically shows 3 ways of doing it.
Using Session
Using Events
Using Cookies
Kindly go through the wiki link, it should equip you with the right ways to do that.
HTH
There is another possibility: jsr168 specified that you can have multiple public render parameter.
They are mapped into portlet.xml and if you use them you will receive values specified in url transparently.
You will find usage of these parameters into asset publisher portlet, for example, where public render parameter are used to listen user choice in category or tags navigation portlet.
Check out the jsr168/jsr286 portlet specification to find a way to manage them! ;)
To get google tag manager data we need to add code provided by google into each and every page.
I dont want to manually add the code to each and every page component in CQ,as numerous templates can be created and it becomes manual job.
Instead i want to add the HTML code into my page on every page load.
Can i achieve this using service component(java class).
If not please, provide any alternative to achieve this.
Accounting for recent posts, your requirement, if I may paraphrase, says, "I want Google Tag Manager code included in all pages automatically, except on the pages where the author doesn't want it." In that case, your option is some form of component instance on every page, where the component's dialog.xml has a simple include GTM/don't include GTM checkbox. Alternatively, you could use a page property or a CQ5 tag. In any case, the author has to check the box or not.
you should use inheritance to achive this.
usually we got a so called "abstract" or "base" template which is more or less extending the foundtion page template were every other template can get kind of global code snipplets from.
You can put this "global" code into a seperate jsp within the abstract-template too and let people overwrite/disable that functionality in some of the extending templates (in case it is not needed in 100% of them) optionally too.
use this template in a way you would normally use the foundation components in every other template you are creating as resourceSuperType and there you go :-)
As suggested by chrysler you can use inheritance for this. Alternatively if you are very sure that you will need this google tag manager code in pretty much all the pages put the code in header/footer components assuming here that you are using header/footer in all the templates.
thanks for your reply. i am aware of this form of implementation wherein you create a parent page template and then refer to it via sling:resourceSuperType in all the child templates.
But what i wanted to know is if there is any other alternative wherein i dont have to host this code on the template's component, and the user can decide which page he wants to get tracked or not, who might not have coding knowledge.
I am not really femiliar with java web tchnologies.
I am using spring mvc with apache tiles. Now I desire to create a user control (user control like in asp.net).
For example, I am going to use many times in specific html pattern (like address chooser that uses cascading drop downs and ajax calls).
What is the best thecnology/framework that will allow me create user controls and will work good with spring mvc and tiles?
You can have something that helps you to reuse some code, but in the end it is nothing more like a (more or less intelligent) snippets. (Dave Newton already explaind in his comment, that jsp are action based and not component oriented)
It is called custom tags: tag or tagx.
And good example how to use tagx files and jspx files (the x is important) works together can be found in a spring roo project.
#See http://docs.oracle.com/javaee/5/tutorial/doc/bnalk.html -- may not so good example but it should be complete
I'm having a performance problem with my JSF/RichFaces/Facelets ajax requests and from what I can tell its because the entire component tree is being rebuild on each ajax request. This is happening even if I use ajaxSingle=true, wrap sections in a4j:region, declare a single section for rerendering or none at all. Our page is a dynamic page with many nested levels. The page may contain around 800-900 fields (inputText, rich calendars, selectOneMenus, etc). The initial load time is an issue, but I understand that issue, its a lot of fields. Once we have that initial build/render time though we have designed all other actions to be ajax and only reRender what is needed. From facelets debug logs I see messages like this on any ajax call:
2011-08-24 22:19:03,054 DEBUG [facelets.viewhandler] (http-0.0.0.0-8080-2) Took
24445ms to build view: /oconsole/appfile.xhtml
2011-08-24 22:19:09,377 DEBUG [facelets.viewhandler] (http-0.0.0.0-8080-2) Took
6323ms to render view: /oconsole/appfile.xhtml
I'm not sure if something we are doing is causing the rebuild of the entire component tree, or facelets is determining this need required for some reason (stale cache?). Here is our stack:
JBoss 5.1
JSF 1.2
RichFaces. 3.3.3.Final
Facelets 1.1.15
Seam 2.1.2
I have tried adding some context parameters to see if they would help, but they did nothing:
facelets.BUILD_BEFORE_RESTORE = false
facelets.REFRESH_PERIOD = -1 or 5 (as in 5min)
Is there anyway to tell if our views are being cached properly? We do not delcare a state saving method, so I believe it defaults to server side. All our requests happen within seam long running conversations. I wasn'te sure if this plays a factor as I thought views get cached at session level? Any help would be greatly appreciated, thank you.
Update after more debugging:
The AjaxViewHandler (which has a member variable of the FaceletsViewHandler) has developmentMode=true set. I'm not sure if this is causing facelets to not cache any views so any changes would be refreshed during development cycles...?? Its been very difficult to find any information on facelets/JSF caching of views and the behavior and controlling that. Furthermore, when I add config param:
<context-param>
<param-name>facelets.DEVELOPMENT</param-name>
<param-value>false</param-value>
</context-param>
This did not take! In debugger I still see true set. Since we have a lot of subviews I also tried
com.sun.faces.numberOfLogicalViews and
com.sun.faces.numberOfViewsInSession
to 1000 up from 15(default) and this had no effect.
I also tried changing to client side state saving without any luck. Running out of ideas....hope someone can help....
It seems Seam 2.1 auto-initializes RichFaces and I'm not sure if that has something to do with it.....
As with any performance problem, a profiler would help greatly in locating the bottlenecks. (Yes, you know it is the restore_view phase, but not where in the restore_view phase).
That said, the restore view phase indeed restores the entire view, not just the parts that will be processed or rendered. Quoting the RichFaces taglib documentation:
process: Id['s] (in format of call UIComponent.findComponent()) of components, processed at the phases 2-5 in case of AjaxRequest caused by this component. Can be single id, comma-separated list of Id's, or EL Expression with array or Collection
RESTORE_VIEW is phase 1. Also:
reRender: Id['s] (in format of call UIComponent.findComponent()) of components, rendered in case of AjaxRequest caused by this component. Can be single id, comma-separated list of Id's, or EL Expression with array or Collection
Moreover, I am not sure that UIComponent.findComponent() is implemented using a more suitable datastructure than a component tree. (Finding something in the component tree would boil down to linear search ...).
I have observed similar effects with JSF 2.0 (Mojarra). My conclusion was that views must not contain more than a couple dozen UIComponents, irrespective of whether they are rendered. (Put differently, AJAX is unsuitable for page navigation.) We indend to keep views small by including only components that are currently visible in the view, and switch views if many new components need to appear. That is, instead of one view with 10 tabs with 30 components each, we'd have 10 views, each only containing the content of a single tab. A drawback of that approach is that components are disposed when switching tabs, causing any state not held in backing beans to be lost.
I do not claim this to be a good solution. Alas, it was the best one I found when looking into this a couple weeks ago. I'd be happy to be shown a better one, too.
Edit
When I say restore, I mean ViewHandler.restoreView(), which called both for an initial get request and a postback. It is incorrect to say that restoreView would simply reuse an existing view as is. For instance, the JSF 2.0 spec mandates in section 7.6.2.7: ]
The restoreView() method must fulfill the following responsibilities:
All implementations must:
If no viewId could be identified, return null.
Call the restoreView() method of the associated StateManager , passing the FacesContext instance for
the current request and the calculated viewId, and return the returned UIViewRoot, which may be null.
and in section 7.7.2:
JSF implementations support two primary mechanisms for saving state, based on the value of the
javax.faces.STATE_SAVING_METHOD initialization parameter (see Section 11.1.3 “Application Configuration
Parameters”). The possible values for this parameter give a general indication of the approach to be used, while allowing
JSF implementations to innovate on the technical details:
client -- [...]
server -- Cause the saved state to be stored on the server in between requests. Implementations that wish to enable
their saved state to fail over to a different container instance must keep this in mind when implementing their server
side state saving strategy. The default implementation Serializes the view in both the client and server modes. In the
server mode, this serialized view is stored in the session and a unique key to retrieve the view is sent down to the
client. By storing the serialized view in the session, failover may happen using the usual mechanisms provided by the
container.
Put differently, the AJAX support added to JSF (both the one added by RichFaces 3 to JSF 1.2, and the one incorporated into JSF 2.0) aims to reduce network bandwith consumption, not server side cpu consumption.
From my analysis the issue is caused by the implementation of facelets. Based on debugger the following lines of FaceletViewHandler class, causes rebuild of tree on each (even AJAX) request (buildBeforeRestore is false, so buildView method is invoked):
// build view - but not if we're in "buildBeforeRestore"
// land and we've already got a populated view. Note
// that this optimizations breaks if there's a "c:if" in
// the page that toggles as a result of request processing -
// should that be handled? Or
// is this optimization simply so minor that it should just
// be trimmed altogether?
if (!this.buildBeforeRestore
|| viewToRender.getChildren().isEmpty()) {
this.buildView(context, viewToRender);
}
So in my mind to resolve the issue of tree rebuild on each request is to go deeply to facelets implementation and do reimplementation... I would rather prefer restructure the view and minimize number of components, so build tree time is low.
Anyone know of any other custom spring scopes than Servlet Context Scope and ThreadScope ?
If you've made some closed-source custom scope I'd really also be interested in hearing what it does and how it worked out for you. (I'd imagine someone would make a WindowScope in a desktop app ?)
I'm open to all use cases, I'm looking to expand my horizon here.
We implemented our own custom Spring scope. A lot of our code works at a relatively low level, close to the database, and we maintain a conceptual level on top of that with its own object model of data sources, links, attributes etc.
Anyway, a lot of beans require a so-called StorageDictionary (an encapsulation of this object graph) to do their work. When we make non-trivial changes to the object graph, the dictionary sometimes needs to be blown away and recreated. Consequently, we implemented a custom scope for objects that were dictionary scoped, and part of the invalidation of a given dictionary involves clearing this custom scope. This lets Spring handle a nice form of automatic caching for these objects. You get the same object back every time up until the dictionary is invalidated, at which point you get a new object.
This helps not only with consistency but also allows the objects themselves to cache references to entities within the dictionary, safe within the knowledge that the cache will be valid for as long as they themselves are retrievable by Spring. This in turn lets us build these as immutable objects (so long as they can be wired via constructor injection), which is a very good thing to do anyway wherever possible.
This technique won't work everywhere and does depend heavily on the characteristics of the software (e.g. if the dictionary was modified regularly this would be horribly inefficient, and if it was updated never this would be unnecessary and slightly less efficient than direct access). However, it has definitely helped us pass off this management of lifecycle to Spring in a way that is conceptually straightforward and in my opinion quite elegant.
In my company we've created two custom scopes, one that will use Thread or Request and another that will use either Thread or Session. The idea is that a single scope can be used for scoped beans without having to change configuration based on the execution environment (JUnit or Servlet container). This also really comes in handy for when you run items in Quartz and no longer have a Request or Session scope available.
Background:
I work on a single web app that runs 4 different web sites under the same servlet context. Each site has its own domain name, e.g. www.examplesite1.com, www.examplesite2.com, etc.
Problem:
Sites sometimes require their own customised instance of a bean from the app context (usually for customised display of messages or formatting of objects).
For example, say sites 1 and 2 both use the "standardDateFormatter" bean, site 3 uses the "usDateFormatter" bean and site 4 uses the "ukDateFormatter" bean.
Solution:
I'm planning on using a "site" scope.
We have a Site enum like this:
enum Site {
SITE1, SITE2, SITE3, SITE4;
}
Then we have a filter that stores one of these Site values in the request's thread using a ThreadLocal. This is the site scope's "conversation id".
Then in the app context there'd be a bean named "dateFormatter", with 'scope="site"'. Then, wherever we want to use a date formatter, the correct one for the user's current site will be used.
Added later:
Sample code here:
http://github.com/eliotsykes/spring-site-scope
Oracle Coherence has implemented a datagrid scope for Spring beans. To sum it up:
A Data Grid Bean is a proxy to a
java.io.Serializable Bean instance
that is stored in a non-expiring
Coherence Distributed Cache (called
near-datagridbeans).
Never used them myself but they seem cool.
Apache Orchestra provides SpringConversationScope.
In a Spring Batch application, we have implemented an item scope.
Background
We have lots of #Service components which compute something based on the current batch item. Many of them need the same workflow:
Determine relevant item parts.
Init stuff based on the item.
For each item part, compute something (using stuff).
We moved the workflow into a base class template method, so the subclasses implement only findItemParts(Item) (doing 1 and 2) and computeSomething(ItemPart) (doing 3). So they became stateful (stuff initialized in findItemParts is needed in computeSomething), and that state must be cleared before the next item.
Some of those services also involve injected Spring beans which are also derived from the current item and must be removed afterwards.
Design
We implemented an AbstractScopeRegisteringItemProcessor which registers the item and allows subclasses to register derived beans. At the end of its process method, it removes the item from its scope context, and the derived beans using DefaultSingletonBeanRegistry.destroySingleton.
How it worked out
It works, but has the following problems:
We did not manage to get the derived beans cleaned up without registration (just based on their #Scope). The concrete processor must create and register them.
AbstractScopeRegisteringItemProcessor would have been nicer using composition and dynamically implementing all interfaces of the underlying processor. But then the resulting #StepScope bean is a proxy for the declared return type (i.e. AbstractScopeRegisteringItemProcessor or ItemProcessor) without the required callback interfaces.
EDIT
With the aid of #Eliot Sykes's solution and shared code plus #Cheetah's BeanDefinition registration, I was able to get rid of the registration as singleton beans. Instead, ItemScopeContext (the storage used by both the processor and the Scope implementation; Java-configured via a static #Bean method) implements BeanDefinitionRegistryPostProcessor. It registers a FactoryBean whose getObject() returns the current item or throws an exception if there is none. Now, a #Component annotated with #Scope(scopeName = "Item", proxyMode = ScopedProxyMode.TARGET_CLASS) can simply inject the item and need not be registered for end-of-scope cleanup.
So in the end, it did work out well.
A spring locale scope based on the users locale wihtin a web application
See related wiki page
In my company, we have also implemented spring custom scope. We have a multi tenant system where every customer can customize settings. Instance based scope of ours, caches the beans which are customer specific. So each time user of a customer logs in, these settings are cached and reused again when other users of the same customers sign in.
I once used a kind of conversation scope to store some objects in the session scope, in order to keep them when re-entering the same page, but limited to a single page to avoid to leave useless objects in the session. The implementation just stored the page URL and cleaned the conversation scope on each page change.