How to redirect to an anchor in JSF? - redirect

Let's say I have this action in a JSF Managed Bean:
public String doSomething() {
FacesContext.getCurrentInstance().getExternalContext().getFlash().put("msg", "Something was done successfully");
return "view?faces-redirect=true";
}
My view has an anchor element with the id msg. I want the url to have this anchor (for accessibility matters), like:
view.jsf#msg
Or whatever is my FacesServlet filter pattern.
return "view#msg?faces-redirect=true"; obviously will not work because JSF (mojarra at least) will try to evaluate view#msg as a view.
So my question is how to make JSF redirect to a URL with #msg in the end.

because JSF (mojarra at least) will try to evaluate view#msg as a view
Oh, that's nasty. It's definitely worth an enhancement request at the JSF/Mojarra boys.
Your best bet is to send the redirect manually with help of ExternalContext#redirect().
public void doSomething() throws IOException {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.getFlash().put("msg", "Something was done successfully");
ec.redirect("view.xhtml#msg");
}
(assuming that FacesServlet is mapped on *.xhtml)
Alternatively, you could conditionally render a piece of JS which does that instead.
<ui:fragment rendered="#{not empty flash.msg}">
<script>window.location.hash = 'msg';</script>
</ui:fragment>

You try to build an illegal URL - the fragment (#) is always the last part of an URL.
return "view?faces-redirect=true#msg" would be the correct URL.
Unfortunately that fragment is stripped by the default NavigationHandler, at least in JSF 2.2.
While the two options of BalusC are working as well, I have a third option to offer. Wrap the NavigationHandler and ViewHandler with a small patch:
public class MyViewHandler extends ViewHandlerWrapper {
public static final String REDIRECT_FRAGMENT_ATTRIBUTE = MyViewHandler.class.getSimpleName() + ".redirect.fragment";
// ... Constructor and getter snipped ...
public String getRedirectURL(final FacesContext context, final String viewId, final Map<String, List<String>> parameters, final boolean includeViewParams) {
final String redirectURL = super.getRedirectURL(context, viewId, removeNulls(parameters), includeViewParams);
final Object fragment = context.getAttributes().get(REDIRECT_FRAGMENT_ATTRIBUTE);
return fragment == null ? redirectURL : redirectURL + fragment;
}
}
public class MyNavigationHandler extends ConfigurableNavigationHandlerWrapper {
// ... Constructor and getter snipped ...
public void handleNavigation(final FacesContext context, final String fromAction, final String outcome) {
super.handleNavigation(context, fromAction,
storeFragment(context, outcome));
}
public void handleNavigation(final FacesContext context, final String fromAction, final String outcome, final String toFlowDocumentId) {
super.handleNavigation(context, fromAction,
storeFragment(context, outcome), toFlowDocumentId);
}
private static String storeFragment(final FacesContext context, final String outcome) {
if (outcome != null) {
final int hash = outcome.lastIndexOf('#');
if (hash >= 0 && hash + 1 < outcome.length() && outcome.charAt(hash + 1) != '{') {
context.getAttributes().put(MyViewHandler.REDIRECT_FRAGMENT_ATTRIBUTE, outcome.substring(hash));
return outcome.substring(0, hash);
}
}
return outcome;
}
}
(I had to create the wrapper for the ViewHandler anyway, because of a fix for JAVASERVERFACES-3154)

Related

JsonpRequestBuilder with typed response throws InCompatibleClassChangeError

I have an existing app that I'm adding a "Suggested Products" feature to and I'm having trouble with my JSONP response not being properly transformed to the typed JsArray. I'm hoping someone can give me an idea of what I'm doing wrong?
I have defined my type that will be returned from the server in its own class:
import com.google.gwt.core.client.JavaScriptObject;
public class SuggestedProduct extends JavaScriptObject {
protected SuggestedProduct() {}
public final native String getFormName();
public final native String getImageURL();
}
I have a method that uses the JsonpRequestBuilder to fire off a request to get my JSON.
private void loadSuggestedProducts() {
JsonpRequestBuilder builder = new JsonpRequestBuilder();
builder.requestObject(buildSuggestedProductURL(), new AsyncCallback<JsArray<SuggestedProduct>>() {
public void onFailure(Throwable caught) {
//Handle errors
}
public void onSuccess(JsArray<SuggestedProduct> data) {
if ( data == null) {
//Handle empty data
return;
}
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("<h4>Suggested Products:</h4>");
for (int i=0; i < data.length(); i++) {
SuggestedProduct product = data.get(i); //<- This line throws the exception
sb.appendHtmlConstant("<div class=\"card\">");
sb.appendHtmlConstant("<img class=\"card-img-top\" src=\"" + product.getImageURL() + "\" alt=\"" + product.getFormName() + "\">");
sb.appendHtmlConstant("<div class=\"card-body\">");
sb.appendHtmlConstant("<h5 class=\"card-title\">" + product.getFormName() + "</h5>");
sb.appendHtmlConstant("<a onclick=\"javascript:addItems();\" class=\"cmd-add\">Add <i aria-hidden=\"true\" class=\"fa fa-plus-circle\"></i></a>");
sb.appendHtmlConstant("</div></div>");
}
view.getSuggestedProducts().setInnerSafeHtml(sb.toSafeHtml());
}
});
}
When I try to use a SuggestedProduct from the response, I get an error:
java.lang.IncompatibleClassChangeError: Found interface
com.google.gwt.cor.client.JsArray, but class was expected
I've been following the guide in the GWT documentation. I don't see any difference between what I'm trying and what they say will work. When I debug, it looks as though the returned data is an array of SuggestedProducts, so I'm stumped as to how to proceed. Any help would be appreciated.
After closer inspection I realized my overlay type was missing method bodies for what fields to return from the JSON object they represented. The fix was to include the proper JSNI method definitions.
import com.google.gwt.core.client.JavaScriptObject;
public class SuggestedProduct extends JavaScriptObject {
protected SuggestedProduct() {}
public final native String getFormName() /*-{ return this.formname; }-*/;
public final native String getImageURL() /*-{ return this.imageurl; }-*/;
}

How to solve waiting for RPC response in GWT?

I know that the RPC is asynchronous but how Can in other way (other than waiting for response) to solve this problem:
public static String htsl(String sentence)
{
final DataBaseAsync db = GWT.create(DataBase.class);
String cookie = staticContent.getCookie("ll");
String shortcut = cookie.split("/")[1];
final String[] lala = new String[1];
database.getTranslated(sentence, shortcut, new AsyncCallback<String>() {
#Override
public void onSuccess(String result) {
lala[0]=result;
//this result I want to return in static function htsl... ?
}
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
}
});
//here I have blank result, because RPC is slower than te return..
And i have always blank result
return lala[0];
}
I know that is not good, but.. If it is no working solution for this, how to wait for response?
Make htsl asynchronous (non-blocking, i.e. with a callack for the response rather than a return value)
Do it like so:
public static String htsl(String sentence, AsyncCallback<String> myCallback) {
final DataBaseAsync db = GWT.create(DataBase.class);
String cookie = staticContent.getCookie("ll");
String shortcut = cookie.split("/")[1];
final String[] lala = new String[1];
database.getTranslated(sentence, shortcut, myCallback);
}
Then you let some other class implement AsyncCallback, pass it as the myCallback argument to the htsl method and Bob's your uncle.

Preserving model state with Post/Redirect/Get pattern

At the moment I am trying to implement the Post/Redirect/Get pattern with Spring MVC 3.1. What is the correct way to preserve and recover the model data + validation errors? I know that I can preserve the model and BindingResult with the RedirectAttributes in my POST method. But what is the correct way of recovering them in the GET method from the flash scope?
I have done the following to POST:
#RequestMapping(value = "/user/create", method = RequestMethod.POST)
public String doCreate(#ModelAttribute("user") #Valid User user, BindingResult result, RedirectAttributes rA){
if(result.hasErrors()){
rA.addFlashAttribute("result", result);
rA.addFlashAttribute("user", user);
return "redirect:/user";
}
return "redirect:/user/success";
}
And the following to GET the user creation form:
#RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView showUserForm(#ModelAttribute("user") User user, ModelAndView model){
model.addObject("user", user);
model.setViewName("userForm");
return model;
}
This allows me to preserve the given user data in the case of an error. But what is the correct way of recovering the errors?(BindingResult) I'd like to show them in the form with the spring form tags:
<form:errors path="*" />
In addition it would be interesting how to access the flash scope from the get method?
public class BindingHandlerInterceptor extends HandlerInterceptorAdapter {
public static final String BINDING_RESULT_FLUSH_ATTRIBUTE_KEY = BindingHandlerInterceptor.class.getName() + ".flashBindingResult";
private static final String METHOD_GET = "GET";
private static final String METHOD_POST = "POST";
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if(METHOD_POST.equals(request.getMethod())) {
BindingResult bindingResult = getBindingResult(modelAndView);
FlashMap outFlash = RequestContextUtils.getOutputFlashMap(request);
if(bindingResult == null || ! bindingResult.hasErrors() || outFlash == null ) {
return;
}
outFlash.put(BINDING_RESULT_FLUSH_ATTRIBUTE_KEY, bindingResult);
}
Map<String, ?> inFlash = RequestContextUtils.getInputFlashMap(request);
if(METHOD_GET.equals(request.getMethod()) && inFlash != null && inFlash.containsKey(BINDING_RESULT_FLUSH_ATTRIBUTE_KEY)) {
BindingResult flashBindingResult = (BindingResult)inFlash.get(BINDING_RESULT_FLUSH_ATTRIBUTE_KEY);
if(flashBindingResult != null) {
BindingResult bindingResult = getBindingResult(modelAndView);
if(bindingResult == null) {
return;
}
bindingResult.addAllErrors(flashBindingResult);
}
}
}
public static BindingResult getBindingResult(ModelAndView modelAndView) {
if(modelAndView == null) {
return null;
}
for (Entry<String,?> key : modelAndView.getModel().entrySet()) {
if(key.getKey().startsWith(BindingResult.MODEL_KEY_PREFIX)) {
return (BindingResult)key.getValue();
}
}
return null;
}
}
Why don't you show the update form after the binding fails, so the user can try to resubmit the form?
The standard approach for this seems to be to return the update form view from the POST handler method.
if (bindingResult.hasErrors()) {
uiModel.addAttribute("user", user);
return "user/create";
}
You can then display errors with the form:errors tag.
what is the correct way of recovering them in the GET method from the
flash scope
I'm not sure I understand what you mean by recovering them. What you add as flash attributes before the redirect will be in the model after the redirect. There is nothing special that needs to be done for that. I gather you're trying to ask something else but I'm not sure what that is.
As phahn pointed out why do you redirect on error? The common way to handle this is to redirect on success.

Place name without a colon (:)?

Still a bit of a GWT noob here but making progress using Activities and Places as described by Google here.
I understand that a Place's "URL consists of the Place's simple class name (like "HelloPlace") followed by a colon (:) and the token returned by the PlaceTokenizer.
Can I somehow remove the colon when I don't have a token to send?
For example, I'm fine with a URL like this "#editPerson:2" when I need to work with PersonId=2. But what about when I just want to present a blank Person form? In that case I would prefer to use "#addPersonForm" rather than "#addPersonForm:"
Any suggestions (even better code suggestions) would be most appreciated!
You can provide your own PlaceHistoryMapper (without using the generator) as already suggested by Boris_siroB, or you can do it within a PlaceTokenizer with an empty prefix: with an empty prefix, there won't be a colon, and the tokenizer can do whatever you want. If you totally distinct places, make it a tokenizer of Place, so it's also the "catchall" for getToken. That way you can keep all the advantages of the generation with prefixes, PlaceTokenizers and WithTokenizers (if you want to take advantage of them)
To take full control of the URL hash (that is to generate your own tokens from Places and map these tokens back to Places) you can implement your own history mapper (a class implementing the PlaceHistoryMapper interface).
public class MyPlaceHistoryMapper implements PlaceHistoryMapper {
#Override
public Place getPlace(String token) {
// parse tokens and create Places here
}
#Override
public String getToken(Place place) {
// examine Places and compose tokens here
}
}
In your entry point class you'd then replace the line:
AppPlaceHistoryMapper historyMapper = GWT.create(AppPlaceHistoryMapper.class);
with:
PlaceHistoryMapper appHistoryMapper = new MyPlaceHistoryMapper();
That's it. Your URL hashes no longer need to be class name-based or to use the : delimiter.
I'm using a PlaceHistoryMapper decorator named PlaceHistoryMapperWithoutColon.
Usage :
final PlaceHistoryMapper historyMapper0 = GWT
.create(PlaceHistoryMapperImpl.class);
final PlaceHistoryMapper historyMapper = new PlaceHistoryMapperWithoutColon(historyMapper0);
Decorator source :
public class PlaceHistoryMapperWithoutColon implements PlaceHistoryMapper {
private static final String COLON = ":";
private PlaceHistoryMapper placeHistoryMapper;
public PlaceHistoryMapperWithoutColon(PlaceHistoryMapper placeHistoryMapper) {
this.placeHistoryMapper = placeHistoryMapper;
}
#Override
public Place getPlace(String token) {
if (token != null && !token.endsWith(COLON)) {
token = token.concat(COLON);
}
return placeHistoryMapper.getPlace(token);
}
#Override
public String getToken(Place place) {
String token = placeHistoryMapper.getToken(place);
if (token != null && token.endsWith(COLON)) {
token = token.substring(0, token.length() - 1);
}
return token;
}
}
Decorated source example :
#WithTokenizers({ FirstPlace.Tokenizer.class, SecondPlace.Tokenizer.class })
public interface PlaceHistoryMapperImpl extends PlaceHistoryMapper {
}
Place source example :
public final class FirstPlace extends Place {
#Prefix("first")
public static class Tokenizer implements PlaceTokenizer<FirstPlace> {
#Override
public NetworkInfosPlace getPlace(String token) {
return new FirstPlace ();
}
#Override
public String getToken(FirstPlace place) {
return "";
}
}
}

How to translate,use JSON in GWT?

I'm new in gwt. and need to know how to use JSON in gwt so i try this simple data loader but i'm still confuse.
I create a project named 'tesdb3' in eclipse. I create the PHP side to access the database, and made the output as JSON.. I create the userdata.php in folder war. then I compile tesdb3 project. Folder tesdb3 and the userdata.php in war moved in local server(I use WAMP). I put the PHP in folder tesdb3. This is the result from my localhost/phpmyadmin/tesdb3/userdata.php
[{"kode":"002","nama":"bambang gentolet"}{"kode":"012","nama":"Algiz"}]
From that result I think the PHP side was working good.Then I create UserData.java as JSNI overlay like this:
package com.tesdb3.client;
import com.google.gwt.core.client.JavaScriptObject;
class UserData extends JavaScriptObject{
protected UserData() {}
public final native String getKode() /*-{ return this.kode; }-*/;
public final native String getNama() /*-{ return this.nama; }-*/;
public final String getFullData() {
return getKode() + ":" + getNama();
}
}
Then Finally in the tesdb3.java:
public class Tesdb3 implements EntryPoint {
String url= "http://localhost/phpmyadmin/tesdb3/datauser.php";
private native JsArray<UserData> getuserdata(String json)
/*-{
return eval(json);
}-*/;
public void LoadData() throws RequestException{
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
builder.sendRequest(null, new RequestCallback(){
#Override
public void onError(Request request, Throwable exception) {
Window.alert("error " + exception);
}
public void onResponseReceived(Request request,
Response response) {
//1
//data(getuserdata(response.getText()));
//2
JsArray<UserData> uda = JsonUtils.unsafeEval(response.getText())
data(uda);
}
});
}
public void data(JsArray<UserData> data){
for (int i = 0; i < data.length(); i++) {
String lkode =data.get(i).getKode();
String lname =data.get(i).getNama();
Label l = new Label(lkode+" "+lname);
tb.setWidget(i, 0, l);
}
RootPanel.get().add(new HTML("my data"));
RootPanel.get().add(tb);
}
public void onModuleLoad() {
try {
LoadData();
} catch (RequestException e) {
e.printStackTrace();
}
}
}
The result from both method i use in the onResponseReceived is the same. Just showing string "my data". but the method 2 create eror like this:
14:41:59.875 [ERROR] [tesdb3] Uncaught exception escaped
com.google.gwt.core.client.JavaScriptException: (SyntaxError): syntax error
Did I miss use the 2nd method? Why method 1 didn't have any eror but can't show the data?
The problem is that your JSON has incorrect syntax, you are missing a comma after the first item of the table, it should be (whitespace added for readability):
[
{
"kode": "002",
"nama": "bambang gentolet"
},
{
"kode": "012",
"nama": "Algiz"
}
]
Since JSON is a part of JavaScript this might be the syntax error exception you are getting.
PS: I'd recommend using some PHP framework to create JSON for you (Zend Framework is my usual choice). Also, JSON validators like JSONLint are very useful for debugging JSON.
It looks like a typo in your code, which brings me to naming conventions: for variables and methods use camel case, starting with a lower case character. Thus UserData UD should be UserData ud.
In your getuserdata method (which should be getUserData) you use the parameter name Json with capital J and in the native code json with the lower j. This explains the error.
Regarding the getUserData method. There is a GWT method: JsonUtils.unsafeEval(json) which you should use.
Furthermore, the code in the onResponseReceived seems incomplete, it might not be of importance as it might be incorrectly be put in this example, but just to be complete, here is what it should look like:
JsArray<UserData> uda = JsonUtils.unsafeEval(response.getText());
for (int i = 0; i < uda.length(); i++) {
UserData ud = uda.get(i);
String lKode = ud.getKode();
String lName = ud.getNama();
Label l = new Label(lKode + " " +lName);
RootPanel.get().add(l);
}