Add messages with Spring - java

I have seen that I can add errors and render them via <form:errors /> tag and addError() method of BindingResult class, but I wonder if there is something similar to send information messages to the JSP.
I mean, I want to add messages when the operation has been successful. I know I could do it by sending an error, but it would make no sense to me to add errors when there haven't been any error at all.

Why don't you just add the messages as properties of the model that is passed to the view. In your JSP you would check to see if they are not null, and if not, display them.

Interesting. I found this in an old project of mine.:
(this was a base controller, but could well be an utility method)
protected void addMessage(String key, boolean isError,
HttpServletRequest request, Object... args) {
List<Message> msgs = (List<Message>) request.getAttribute(MESSAGES_KEY);
if (msgs == null) {
msgs = new LinkedList<Message>();
}
Message msg = new Message();
msg.setMessage(msg(key, args));
msg.setError(isError);
msgs.add(msg);
request.setAttribute(MESSAGES_KEY, msgs);
}
and then in a messages.jsp which was included in all pages I had:
<c:forEach items="${messages}" var="message">
//display messages here
</c:forEach>
MESSAGES_KEY is a constant of mine with a value "messages" (so that it is later accessible in the forEach loop).
The Message class is a simple POJO with those two properties. I used it for info messages as well as for custom non-validation errors.
This is a rather custom solution, but perhaps I hadn't found a built-in solution then. Google a bit more before using such a solution.

Use something like Flash messages in Rails.
The hard part is to keep the message in a redirect after post. I.e. you submit a form and you redirect to another page that shows a message notifying you that you have succeded in your action.
It is obvious that you can't keep the message in the request because it will be lost after the redirect.
My solution consists in keeping a session scoped bean that contains the message text and its type (notice, warning or error). The first time you read it in a JSP you have to clear it to avoid showing it more than once.

Related

Changing data on GET page request (dealing with preloading requests)

I have a portlet. When the portlet loads, then before the first view is rendered, in some cases there is a need to call a repository which changes data in the database. I wouldn't go into more detail about why this is necessary and answers about this being a design flaw are not helpful. I am aware that it is a design flaw but I would still like to find out an alternative solution to the following problem:
The problem with this set-up is, that browsers send preloading requests. For example the URL of the page where the portlet resides is /test-portlet. Now when you type it in your address-bar then if you have it in your browser history, then the browser sends a GET request to the page already when it suggests it to you. If you press enter before the first GET request is resolved, then the browser sends a new GET request. This means that the portlet receives 2 separate requests which it starts to process parallelly. The first database procedure might work correctly but considering the nature of the database procedure, the second call usually gives an exception.
What would be a nice clean way to deal with the aforementioned problem from the Java application?
Sidenote: I am using Spring MVC.
A simple example of a possible controller:
#RequestMapping
public String index( Model model, RenderRequest request ){
String username = dummyRepository.changeSomeData(request.getAttribute("userId"));
model.add("userName", username);
return "view";
}
I would be interested in a solution to block the first execution altogether. For example somekind of a redirect to POST from controller which the browser wouldn't trigger. Not sure if it is achievable though.
Using locks I think you could solve it, making the secound request wait for the first to finish and then processing it. I don't have experience with locks in java but i found another stack exchange post about file locks in jave:
How can I lock a file using java (if possible)
Please refer to this answer, it might help you to detect and ignore some preloading requests. However you should also make sure the 'worst case' works, perhaps using the locking as suggested by #jpeg, but it could be as easy as using a synchronize block somewhere.
Since I don't see that chrome adds some specific header (or anyhow notifies the server about prerendering state) it is probably not possible to detect it on the server side... at least not directly. You can however simulate the detection on client side and later combine it with server call.
Notice that you can detect prerendering on the client side:
if (document.webkitVisibilityState == 'prerender' || document.visibilityState == 'prerender' || document.visibilityState[0] == 'prerender') {
// prerendering takes place
}
Now, you can break preloading on client side by showing alert box in case browser is in preloading state (or you can probably do the same with just some error in javascript, instead of using alert()):
if (document.webkitVisibilityState == 'prerender' || document.visibilityState == 'prerender' || document.visibilityState[0] == 'prerender') {
alert('this is alert during prerendering..')
}
Now when chrome prerenders the page it will fail because the javascript alert will prevent the browser to continue executing javascript.
If you type in chrome: chrome://net-internals/#prerender you can track when and for which pages chrome executes prerendering. In case of above example (with alert box during prerendering) you can see there:
Link Rel Prerender (cross
domain) http://some.url.which.is.preloaded Javascript
Alert 2015-06-07 19:26:18.758
The final state - Javascript Alret proves that chrome failed to preload the page (I have tested this).
Now how can this solve your issue? Well, you can combine this with asynchronous call (AJAX) and load some content (from another url) depending on wheater the page is actually prerendering or not.
Consider following code (which might be rendered by your portlet under url /test-portlet):
<html>
<body>
<div id="content"></div>
<script>
if (document.webkitVisibilityState == 'prerender' || document.visibilityState == 'prerender' || document.visibilityState[0] == 'prerender') {
// when chrome uses prerendering we block the request with alert
alert('this is alert during prerendering..');
} else {
// in case no prerendering takes place we load the actual content asynchronously
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// when the content is loaded we place the html inside "content" div
document.getElementById('content').innerHTML = xhr.responseText;
}
}
xhr.open('GET', '/hidden-portlet', true); // we call the actual portlet
xhr.send(null);
}
</script>
</body>
</html>
As you see the /hidden-portlet is only loaded in case browser is loading the page normally (without preloading). The server side handler under url /hidden-portlet (which can be another portlet/servlet) contains actual code which should not be executed during prerendering. So it is the /hidden-portlet which executes
dummyRepository.changeSomeData(request.getAttribute("userId"));
This portlet can also return normal view (rendered html) which will be asynchronously placed on the page under url /test-portlet thanks to the trick on /test-portlet: document.getElementById('content').innerHTML = xhr.responseText;.
So to sumarize the portlet under address /test-portlet only returns html with a javascript code which triggers actual portlet.
If you have many fragile portlets, you can go with this even further, so you can parametrize you /test-portlet with request parameter like /test-portlet?actualUrl=hidden-portlet so that address of the actual portlet is taken from url (which can be read as request parameter on server side). Server will in this case dynamically render the url which should be loaded:
So instead of hardcoded:
xhr.open('GET', '/hidden-portlet', true);
you will have
xhr.open('GET', '/THIS_IS_DYNAMICALLY_REPLACED_EITHER_ON_SERVER_OR_CLIENT_SIDE_WITH_THE_ADDRES_FROM_URL', true);

how to determine if a web service is up and running

i was trying to call the following web service from my android app, it hung then completed without returning the result:
web service:http://androidexample.com/media/webservice/JsonReturn.php
However when I clicked on the link, it worked fine - the json file displayed. yet it would not work in my app..
but now, it works fine now in my android app, perhaps it was temporarily down is what I am guessing. How can I know if a web service is up and running for an android app to consume ?
Typically, web services are designed to have a status page that can return status text or a HTTP return code to indicate service status.
If it doesn't have that, you can design a function to periodically do a very basic request with a known result to determine state. This is much better than doing a simple ping.
If it was down it would most likely show a HTML error page, which your app would try to parse, which would cause an error.
I had a similar issue, because I needed to know if the user was returning HTML or the correct JSON, to do this I created the ArrayList I was about to use outside of the try/catch of the parse area. You should do the same if you are using a string.
What I mean is, use:
ArrayList<Something> arrayList = new ArrayList<Something>();
String testString = ""; instead of String testString = null;
I was using only ArrayList<Something> arrayList; at one point which is incorrect. If the user then returns HTML, you won't get an error, the user will simply return an empty arraylist or empty string.
You can then plan for that and show some sort of error message. This way you only need one network request but you can still plan for getting the data back, and the server being down.

How to make the autocompletetextfield in Wicket work after the session timed out

I've been playing with the Wicket autocompletetextfield. It has one problem though - when the session times out it stops working if the page itself isn't refreshed. This would be quite confusing for a customer I think, and I guess that it's not meant to work that way. Therefore, how can I make the Wicket autocompletetextfield work even though the session has timed out (and without refreshing the page)
To try it yourself:
Go to http://www.wicket-library.com/wicket-examples-6.0.x/ajax/autocomplete
Write something in the textfield, eg. bel
Wait for 5 minutes (I think that's is the default session timeout they use in the examples) and try again, without refreshing
the page. Now you'll only get a blank textfield.
I think you can't.
The only workaround I know is to set the Ajax error handling strategy to REDIRECT_TO_ERROR_PAGE, evaluate the Referer-Field in the HTTP header in the Error Page and provide a link (or auto redirect) to the page where the timeout occurred.
YourWicketApplication.java
#Override
public void init() {
super.init();
// ...
getExceptionSettings().setAjaxErrorHandlingStrategy(IExceptionSettings.AjaxErrorStrategy.REDIRECT_TO_ERROR_PAGE);
}
YourErrorPage.java:
public YourErrorPage(...) {
// ...
WebRequest request = (WebRequest) getRequest();
String referer = request.getHeader("Referer"));
// ... provide a link/auto redirect to this address
}

execute javascript code in an android.webkit.WebView without loadUrl or XHR

I am writing a phoneGap plugin to allow multitouch on android devices (hoping to get this included in phonegap/callback eventually)
Event delegation is taking ~200ms using the plugin success callback and ~50ms with the WebView.loadUrl('javascript:somecodehere()') call
Unfortunately loadUrl has the side-effect of flickering the soft keyboard which isn't acceptable for a general solution.
Phonegap's Plugin.success uses an internal web server and an XmlHttpRequest object to send data, this method is way too slow.
Is there any 3rd method of sending javascript to the web browser? (or even sending a poke to the javascript engine to cause an event to happen, so that event could check a custom jsInterface object)
Take a look at addJavascriptInterface in the WebView class. It sounds more like what you are looking for.
In you plugin try calling:
this.ctx.sendJavascript(statement);
Not quite as fast as loadUrl but it may be a bit faster than returning a PluginResult.
You could roll your own stripped down message queue with a java object that is basically an arraylist and an accessor, then use addJavascriptInterface to bind it into the javascript context and inject a javascript polling loop that uses setTimeout to call the accessor method of your queue. Whenever you have javascript to execute, just add it to your arraylist. I'm not sure how it would perform, but perhaps it's worth a try?
class JSQueue {
private ArrayList<String> messages;
public String getMessage() {
String message = "";
if(messages.size() >0) {
message = messages.remove(0);
}
return message;
}
public void addMessage(String message) {
messages.add(message);
}
}
JSQueue jsq = new JSQueue();
dc.appMobiCanvas.hiddenView.addJavascriptInterface(jsq, "jsq");
dc.appMobiCanvas.hiddenView.loadUrl("javascript:(function checkJSQ(){eval(jsq.getMessage());setTimeout(checkJSQ, 50);}})();");
//add messages via jsq.addMessage();
It seems we have developed something similar
https://github.com/Philzen/webview-multitouch-polyfill
However, i have never experienced the issue you're describing before, but maybe you would like to test on your device or maybe contribute your expertise to the project. It has already been suggested on the Cordova (Phonegap) Roadmap, so we'll happy about every user and/or contributor to help this cause!

Rerender RichFaces error message after ajax request

I am using custom ajax-called javacode that does some processing on the server. In this process various errors can occure that I add to the FacesContext via addMessage().
I want to display these messages in the same <rich:messages>-tag that I use for my validation errors.
Do you know a way to display these messages in the <rich:messages>-tag after the ajax-request completed?
My initial idea was adding
<a4j:jsFunction name="richDisplayError" reRender="messages" />
to the markup and calling richDisplayError when the request completed, but it seems the messages panel is rerendered empty.
<rich:messages> has ajaxRenderedset to true by default. So the problem lies elsewhere. Perhaps:
you are redirecting, instead of forwarding, and the messages are lost
you aren't actually adding the messages (check with debug)
you are having different/lacking views/subviews
For example, in your page:
<a4j:commandButton value="Action"
limitToList="true"
action="#{mybean.action}"
reRender="mymessages">
</a4j:commandButton>
<a4j:outputPanel ajaxRendered="true">
<h:messages id="mymessages" />
</a4j:outputPanel>
then in you bean:
public void action(){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("hello world"));
}
You need 3 things :
1st : declare your error message, in the "\resources\bundle\errorMessages.properties" file, like this :
errorMsgToDisplay.errName = Your Error Message Here
2nd : declare your BUNDLE variable in the class code :
private static final ResourceBundle BUNDLE = ResourceBundle.getBundle("/bundle/errorMessages");
3rd : Display the message (after an condition for example )
if ( condition ) {
FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_ERROR,
BUNDLE.getString("errorMsgToDisplay.errName"),
BUNDLE.getString("errorMsgToDisplay.errName")));
}

Categories

Resources