I used the Manolo Santos example with Spring MVC as follows:
Annotate the Flash class with @Component and add a boolean to indicate whether the message should be displayed for another request.
@Component
public class Flash {
private static final String INFO = "info";
private static final String SUCCESS = "success";
private static final String ERROR = "error";
private static final String WARNING = "warning";
private static final String NOTICE = "notice";
private final Map msgs = new HashMap ();
private boolean isKept; // keep msg for one more request (when the controller method redirects to another)
private void message (String severity, String message) {
msgs.put (message, severity);
}
public void info (String message) {
this.message (INFO, message);
}
public void success (String message) {
this.message (SUCCESS, message);
}
public void notice (String message) {
this.message (NOTICE, message);
}
public void warning (String message) {
this.message (WARNING, message);
}
public void error (String message) {
this.message (ERROR, message);
}
public boolean isEmptyMessage () {
return msgs.isEmpty ();
}
public void clear () {
msgs.clear ();
isKept = false;
}
public Map getMessage () {
return msgs;
}
public boolean isKept () {
return isKept;
}
public void keep () {
isKept = true;
}
public void unKeep () {
isKept = false;
}
}
Use the interceptor to add a flash message to the model object.
public class FlashMessageInterceptor extends HandlerInterceptorAdapter {
@Resource
Flash flash
@Override
public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if (! flash.isKept ()) {
modelAndView.addObject ("flash", flash);
}
}
@Override
public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
if (flash.isKept ()) {
flash.unKeep ();
}
else {
flash.clear ();
}
}
}
In your controller, if you have a method that redirects to another method, you can simply say: flush.keep () to display a flash message.
@Controller
public class ComputerCampLove {
@Resource
private flash flash;
@RequestMapping (method = RequestMethod.GET)
public String takeMeToAnotherPlace (Model model) {
flash.info ("Fa-fa-fa!");
flash.keep ();
return "redirect: somewhere";
}
}
Mads lundeland
source share