Mixing jsp and jsf - java

I will elaborate somewhat. Jsf is kind-of extremely painful for working with from designer's perspective, somewhat in the range of trying to draw a picture while having hands tied at your back, but it is good for chewing up forms and listing lots of data. So sites we are making in my company are jsf admin pages and jsp user pages. Problem occurs when user pages have some complicated forms and stuff and jsf starts kickin' in.
Here is the question: I'm on pure jsp page. I need to access some jsf page that uses session bean. How can I initialize that bean? If I was on jsf page, I could have some commandLink which would prepare data. Only thing I can come up with is having dummy jsf page that will do the work and redirect me to needed jsf page, but that's kind of ugly, and I don't want to end up with 50 dummy pages. I would rather find some mechanism to reinitialize bean that is already in session with some wanted parameters.
Edit: some more details. In this specific situation, I have a tests that are either full or filtered. It's a same test with same logic and everything, except if test is filtered, it should eliminate some questions depending on answers. Upon a clicking a link, it should start a requested test in one of the two modes. Links are parts of main menu-tree and are visible on many sibling jsp pages. My task is to have 4 links: testA full, testA filtered, testB full, testB filtered, that all lead on same jsf page and TestFormBean should be reinitialized accordingly.
Edit: I've researched facelets a bit, and while it won't help me now, I'll definitely keep that in mind for next project.

have you looked into using facelets? It lets you get rid of the whole JSF / JSP differences (it's an alternate and superior view controller).
It also supports great design-time semantics with the jsfc tag...
<input type="text" jsfc="#{SomeBean.property}" class="foo" />
gets translated internally to the correct JSF stuff, so you can work with your existing tools.

You can retrieve a managed bean inside of a tag library using something like this:
FacesContext context = FacesContext.getCurrentInstance();
Object myBean = context.getELContext().getELResolver().getValue(context.getELContext(), null, "myBeanName");
However, you'd need to use the tag library from one of your JSF pages. FacesContext.getCurrentInstance() returns null when it's called outside of the FacesServlet.

To solve this one I'd probably create a JSF fragment that only includes your form, then use a <c:import> tag to include it in my JSF page.
That solution is probably a little fragile depending on your environment though.
EDIT: See Chris Hall's answer, FacesContext is not available outside the FacesServlet.

Actually, I've resolved this by removing bean from session, so it has to be generated again when jsf page is called. Then I pick up get parameters from a request in constructor.

Create a custom JSP tag handler. You can then retrieve the bean from session scope and then initialize it on the fly. See this tutorial for more details.

Related

why does the page name is not added in the url after launching jsf application [duplicate]

I am currently learning JSF and was rather amazed and puzzled when I realized that whenever we use <h:form>, the standard behavior of JSF is to always show me the URL of the previous page in the browser, as opposed to the URL of the current page.
I understand that this has to do with the way JSF always posts a form to the same page and then just renders whatever page the controller gives it back to the browser which doesn't know the page location has changed.
It seems like JSF has been around for long enough that there must be a clean, solid way to deal with this. If so, would you mind sharing?
I have found various workarounds, but sadly nothing that seems like a real solid solution.
Simply accept that the URL is misleading.
Append "?faces-redirect=true" to the return value of every bean's action and then
figure out how to replace #RequestScoped with something else (Flash Scopes, CDI conversation, #SessionScoped, ...).
accept to have two HTTP round trips for every user action.
Use some method (e.g. 3rd party library or custom code) to hide the page name in the URL, always using the same generic URL for every page.
If "?faces-redirect=true" is as good as it gets, is there a way do configure an entire application to treat all requests this way?
Indeed, JSF as being a form based application targeted MVC framework submits the POST form to the very same URL as where the page with the <h:form> is been requested form. You can confirm it by looking at the <form action> URL of the generated HTML output. This is in web development terms characterized as postback. A navigation on a postback does by default not cause a new request to the new URL, but instead loads the target page as content of the response. This is indeed confusing when you merely want page-to-page navigation.
Generally, the right approach as to navigation/redirection depends on the business requirements and the idempotence (read: "bookmarkability") of the request (note: for concrete code examples, see the "See also" links below).
If the request is idempotent, just use a GET form/link instead of POST form (i.e. use <a>, <form>, <h:link> or <h:button> instead of <h:form> and <h:commandXxx>).
For example, page-to-page navigation, Google-like search form, etc.
If the request is non-idempotent, just show results conditionally in the same view (i.e. return null or void from action method and make use of e.g. <h:message(s)> and/or rendered).
For example, in-page data entry/edit, multi-step wizard, modal dialog, confirmation form, etc.
If the request is non-idempotent, but the target page is idempotent, just send a redirect after POST (i.e. return outcome with ?faces-redirect=true from action method, or manually invoke ExternalContext#redirect(), or put <redirect/> in legacy XML navigation case).
For example, showing list of all data after successful editing, redirect after login, etc.
Note that pure page-to-page navigation is usually idempotent and this is where many JSF starters fail by abusing command links/buttons for that and then complain afterwards that URLs don't change. Also note that navigation cases are very rarely used in real world applications which are developed with respect to SEO/UX and this is where many JSF tutorials fail by letting the readers believe otherwise.
Also note that using POST is absolutely not "more secure" than GET because the request parameters aren't immediately visible in URL. They are still visible in HTTP request body and still manipulatable. So there's absolutely no reason to prefer POST for idempotent requests for the sake of "security". The real security is in using HTTPS instead of HTTP and checking in business service methods if currently logged-in user is allowed to query entity X, or to manipulate entity X, etc. A decent security framework offers annotations for this.
See also:
What is the difference between redirect and navigation/forward and when to use what?
JSF implicit vs. explicit navigation
What URL to use to link / navigate to other JSF pages
Bookmarkability via View Parameters feature
What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?
When should I use h:outputLink instead of h:commandLink?
Creating master-detail pages for entities, how to link them and which bean scope to choose
Retaining GET request query string parameters on JSF form submit
Pass an object between #ViewScoped beans without using GET params

Spring mvc posting data to controller

This is a question what I have been wondering for quite some time.
Often enough I have my jsp which has to post some data to my controller. In this jsp I have some data I need to post to controller, but aren't touched by the user.. (ie, administration data like an ID). As far as I know there are 2 options to give the controller this data.
Use <input type="hidden"> fields
Put everything in a session variable.
Option 2 has my preference since it requires me to type less code, and I can't forget hidden fields. Though this also has downsides, like another page overriding the session attribute.
What are your preferences? And are there any other options?
Thanks!
Davey
I always prefer to make session object as small and as light as possible. I know its convenient but if your site is high traffic then these session object size will soon start adding to the JVM instance of the Web Server.
So I would prefer option 1 over option 2.

In Wicket, what to do write by hand in HTML and what do I generate?

This is my first time with wicket, so please bear with me.
Most examples in wicket show how with a wicket id you can automagically replace the inner HTML with different things. Using this knowledge I've hand written a form in HTML with lots of formatting and JQuery for different things, and only using Wicket to autogenerate the info for 2 select boxes. However when I try to parse the submitted information on the Wicket side, I get confused.
The only way I've figured out that's easy is using RequestCycle.get().getRequest().getRequestParameters(). to get all the passed info. It works, but I don't think that's the ideal way to use Wicket. There also seems to be a way with request handlers but I have no idea where to start, especially since a lot of documentation is out of date with the new 6.0.0 release.
What is the way I'm supposed to use Wicket with forms? Do I hand write most of the form, only let Wicket autogenerate some of the info, and use RequestCycle? Do I write a skeleton form, have Wicket autogenerate the rest, and use lots of submit handlers? Where is this documented in an easy to understand beginner tutorial?
Note: My form has several fields that are created dynamically (think "click here to add more options") and is submitted in the background with AJAX, verified, then cleared. This might complicate the Wicket side of things, but is a functional requirement
With Wicket you can think of HTML markup as if it was a template. Markup is actually almost-standard HTML. You can (and should) define wicket:id attributes for everything that will have certain behavior or logic attached (forms, buttons, links), or require some server-side processing (such as form components or nested custom components or panels). Everything else will be output in the response as it is in the markup.
Wicket will handle form submission and process the request for you. In Wicket, form components are usually defined server-side, and added to a Form component. In the Form component's onSubmit(), Wicket will have already processed the request, and the submitted values will be available in the FormComponent's Models.
So, the ideal way for Wicket to handle form submission would involve the server-side creation of any components in the form.
The following Wicket Examples page shows a basic Form with some FormComponents in it: Wicket Examples - forminput. You can even see its source code.
Also, you might find the following Wicket wiki page useful: How to do things in Wicket - Forms.
Regarding dynamic component creation, whenever a new dynamic component has to be created, you could for instance make an Ajax request that creates the component server side (wrapped in a ListView, for example), and get markup refreshed in the ajax callback.
There's an example of such a list here: Wicket in action - Building a ListEditor form component
Just to add, I found the Wicket in Action book to be an excellent resource for learning Wicket. Chapter 6 - Processing user input using forms elaborates on the subject.

Confused: Role of Beans in JSF2 in comparison to classical MVC Controllers

i have a question that is more design and architecture related. I am coming from a classical MVC based background and have to get my hands dirty on JSF2. I read the IBM articles on JSF2 (http://www.ibm.com/developerworks/library/j-jsf1/) and think i understand the overall concept.
I started to get in touch with JSF2 trough ROO. I have the feeling that ROO (maybe this is true for any JSF2-Type App, or maybe not) is making very strange/unclear use of beans. It is in general really not clear to me what the actual role of a Bean is! For example, if i have a view with a form that is for editing a single user-entry, i would initialize the user in a, lets call it UserBean (maybe store in in a member variable) and access this variable trough getters. If i now want to overview all users, i would again render the view in in the UserBean hold a collection of users and again access this collection trough getters. The previous description is actually the way i would do things with jsf. This means i would user the UserBean more as a statefull-service as a controller.
In a typical controller situation i would create for every type of action (list user, edit user, view user, etc) a separate controller, with specific initialized data and this way i would separated the context of the logic by controllers.
I often make use of context specific services, e.g. if i handle user's often an spread over the application, i create a user-service that handles user specific logic that is maybe to complex to be put into the itself. If i now for example look into roo generated Beans, i would find methods that programatically render forms, input fields, labels, that again store list's of users, boolean fields that indicate if data had already been loaded, single user members and a lot of methods that more look like to be put into a UserService (or whatever). I am wondering if this is the way JSF2 is intended to be used, in words: pushing everything that is related to one context into on bean, not making use of service and writing "super-controller-beans" that handle everything.
I don't really know if you get the question right, but what would maybe help me is, a hint to
a very exemplary and commendable example application that makes use of beans the way they where intended to be used in combination with jsf2 features and usecases that for example implement basic CRUD usecases around a given type of entity. (One big confusing point is, that in my case ROO always makes use of AJAX and javascript stuff like Modal-Dialogs to implement CRUD logic. I wonder if with JSF there is a more classical way to to this?[With 'classical' i mean for example URL-Based views and separated views for listing, editing and viewing entities])
a resource that enlightens typical "thats-the-way-the-good-guys-do-it" JSF-Patterns (maybe this is J2EE Patterns?).
Thanks you so much!
Please feel free the push me to concretize specific points if i am not clear!
The link for JSF2 you have posted points to JSF1.2 article. In case you want to start of with JSF2 or JSF I suggest following links.
JSF 2.0 Tutorial # mkYong.com
BalusC JSF blog
Stackoverflow wiki for jsf
I'll suggest start with plain vanilla JSF rather than ROO with JSF to get a hang of JSF.
To answer your question
First link provides you with simple jsf examples, in JSF you can have both ajax based and classical way of submitting form. In JSF 1.x versions ajax was not part and parcel of JSF it was implemented by third party component library mainly RichFaces and PrimeFaces to name few. In JSF2 there is inbuilt support for ajax, this does not apply third party components are no longer required, they still provide some extended features. I'll suggest go through this link to find differences between JSF 1.x and JSF 2.
Patterns I am not aware of as such as specific to JSF apart code can be categorized in model - view - controller. Typical case Person represents model, PersonMangedBean plays role of controller which plays central role of getting data from view(jsp/facelets) and after processing data in bean itself or service beans handles navigation to classic views may be listPersons.xhtml.
JSF managed beans are not "super-controller-beans" handling every thing in that bean. I try to categorize things the way you mentioned i.e. have a service layer where we have all business logic may be EJB or Spring managed bean and it decouples at-least business logic away from view technology JSF whereby it(service) can be reused somewhere else as a library if designed properly.
Tip: JSF is component based framework not an action based and it has lifecycle of its own, do get a grip of that life-cycle will save lots of time and proper understanding of the framework. This link though for JSF 1.x holds good for JSF2 too, for basic understanding of life-cycle.
Hope this helps.

In Struts 1.3, what's the best way for the Controller to fill the View with variables?

I've just inherited some old Struts code.
If Struts (1.3) follows the MVC pattern, how do the Action classes fill the View with variables to render in HTML ?
So far, I've seen the Action classes push variables in (1) the HTTP request with
request.setAttribute("name", user.getName())
(2) in ActionForm classes, using methods specific to the application:
UserForm form = (UserForm) actionForm;
form.setUserName(user.getName());
and (3) a requestScope variable, that I see in the JSP layer (the view uses JSP), but I can't see in the Action classes.
<p style='color: red'><c:out value='${requestScope.userName}' /></p>
So, which of these is considered old-school, and what's the recommended way of pushing variables in the View in Struts ?
My Struts days are long over, but as far as I remember we used to place one view-specific bean (which would work as a holder for fine-graner beans or collections of beans) into the request scope within our Action.perform() implementation. This view-specific bean would then be rendered by the view.
As Struts 1.3 is considered old-school, I'd recommend to go with the flow and use the style that already is used throughout the application you inherited.
If all different styles are already used, pick the most used one. After that, pick your personal favourite. Mine would be 1 or 3 - the form (2) is usually best suited for data that will eventually be rendered inside some form controls. If this is the case - use the form, otherwise - don't.

Categories