balteo
balteo

Reputation: 24679

Recommended way to display an error message without resorting to @ModelAttribute with Spring MVC

I have the following method skeleton in a Spring MVC application:

@RequestMapping(value = "/activateMember/{token}", method = RequestMethod.GET, produces = "text/html")
public String activateMember(@PathVariable("token") String token) {
...
}

I am trying to display an error message if the token is invalid for some reason. However I have no ModelAttribute in the method arguments and I don't really want one. But of course I can't use an Errors or BindingResults argument because of the absence of a ModelAttribute and its corresponding form.

So my question is:
what is the recommended way to display an error message given the above method signature and without introducing a ModelAttribute?

Upvotes: 1

Views: 129

Answers (1)

madhead
madhead

Reputation: 33412

If the String you've returned from the method is a viewname (Spring default) then simply create a view for this case and do like:

@RequestMapping()
public String activateMember(@PathVariable("token") String token) {
    if(checkToken(token)){
        doProcess();
        return "userprofile";
    } else {
        return "badtoken"
    }
}

In more complicated case you may have a hierarchy of exceptions, related to bad tokens. (Token is expired, token is just incorrect and so on). You can register an @ExceptionHandler in the same controller:

@RequestMapping()
public String activateMember(@PathVariable("token") String token) {
    return activate(token); // This method may throw TokenException and subclasses.
}

@ExceptionHandler(TokenException.class)
public ModelAndView tokenException(TokenException e){
    // some code
    return new ModelAndView("badtoken", "exception", e);
}

Upvotes: 1

Related Questions