Jake
Jake

Reputation: 26107

How to pass errors in Spring Controller/Model to a view file

How do I pass errors to a view file from a Controller implemented using Spring MVC? These errors are not form errors. Just business logic errors that will be shown inside a div in the "JSP" view.

Here is the controller action I have:

@RequestMapping(method = RequestMethod.POST)
public String processLoginForm(HttpServletRequest request, LoginForm loginForm, 
BindingResult result, @SuppressWarnings("rawtypes") Map model) 
{
    loginForm = (LoginForm) model.get("loginForm");

    String gotoURL = request.getParameter("gotoURL");

    if (gotoURL == null || gotoURL == "") 
    {
        String errorMessage = "No Redirect URL Specified"; 
        return "loginerror";//loginerror is the view file I want to pass my error to.
    }
    model.put("loginForm", loginForm);
    return "loginsuccess";
}

Thanks,

Upvotes: 2

Views: 8925

Answers (3)

Deepak N
Deepak N

Reputation: 21

You can use Spring support for exception handling..

HandlerExceptionResolver or @ExceptionHandler

@adarshr

Link

Hope it will be of some use.

Upvotes: 1

sreeprasad
sreeprasad

Reputation: 3260

Your method is

public String processLoginForm(HttpServletRequest request, LoginForm loginForm, BindingResult result, @SuppressWarnings("rawtypes") Map model)

The method @The New Idiot explained is

public String processLoginForm(HttpServletRequest request, LoginForm loginForm, BindingResult result, ModelMap model)

See that the Map model is replaced with ModelMap model

If you use this method, then you can use model.addAttribute to add error messages

Upvotes: 2

AllTooSir
AllTooSir

Reputation: 49362

Change your method signature :

public String processLoginForm(HttpServletRequest request, LoginForm loginForm,
                 BindingResult result, ModelMap model)

You can put the error message in the ModelMap and forward it to the loginerror page.

if (gotoURL == null || "".equals(gotoURL)) 
{
    final String errorMessage = "No Redirect URL Specified"; 
    modelMap.addAttribute("errorMessage ", errorMessage);
    return "loginerror";//loginerror is the view file I want to pass my error to.
}

You can fetch that in the div using EL.

<div>${errorMessage}</div>

Upvotes: 6

Related Questions