SpringMVC using @ExceptionHandler HTTP Status 500 - Expected session attribute

I would like to use @exceptionhandler to capture an HTTP Status 500 - Expected session attribute. I would like to return a message to the same page i am on showing the user the error.

Can someone point me to an example on how i can handle this exception and return a message to the view instead of redirecting to another page.

This is what i have so far however the item in the view is not getting set with the error message;

    public RedirectView handleHttpSessionRequiredException(Exception ex, HttpServletRequest request) throws Exception
        logger.info("In the handleHttpSessionRequiredException Handler Method");
        String referrer = request.getHeader("referer");
        RedirectView redirectView = new RedirectView(referrer);
        redirectView.addStaticAttribute("errorMessage","Execute A Query Then Retry");
        return redirectView;


<label id="errorMessage" name="errorMessage">${errorMessage}</label>


You can get the referer and forward or redirect to it. E.g.

public String (HttpServletRequest request) {
    String referrer = request.getHeader("referer");
    FlashMap flashMap = RequestContextUtils.getOutputFlashMap(request);
flashMap.put("errorMessage","Execute A Query Then Retry");
    return "redirect:/my/url";

The redirect URL is relative to the application path. You can extract it from the referer.

You can return a ModelAndView from an @ExceptionHandler method by doing something like the following.

public ModelAndView handleIOException(IOException ex) {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("someObject", new SomeObject());
    return modelAndView;

The problem is figuring out the current page you were on before. To my knowledge, there isn't a way to get the current model and view from inside an ExceptionHandler method so you won't have a good way of knowing what view to use.

I think your best bet is to catch and handle the Exception in your controller.

Need Your Help

RSA Encryption returning different output

c# encryption cryptography rsa system.security

I'm new to RSA encryption and I've been trying to learn how exactly it works using .Net's System.Security.Cryptography.

How to add data annotations to partial class?

c# .net data-annotations partial-classes

I have an auto generated class with a property on it. I want to add some data annotations to that property in another partial class of the same type. How would I do that?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.