jackysee
jackysee

Reputation: 2061

Redirect at @ResponseBody?

I have something for ajax login through spring security:

@RequestMapping(value="/entry.html", method=RequestMethod.GET)
public String getEntry(){
    return isAuthenticated()? "redirect:/logout.jsp":"entry";
}

@RequestMapping(value="/postLogout.html", method=RequestMethod.GET)
public @ResponseBody String getPostLogout(){
    return "{success:true, logout:true, session:false}";
}

The flow is that when receive a call to /entry.html, it will check and choose to

I would like to know if I can use @ResponseBody in getEntry() without using an jsp to write just a json value?

Upvotes: 3

Views: 4373

Answers (1)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299068

The easiest way to return JSON from Spring is through Jackson.

I'd create a custom return Object:

public class MyReturnObject{
private boolean success;
private boolean session;
private boolean logout;
// + getters and setters
// + 3-arg constructor
}

and write the controller method like this:

@RequestMapping(value="/postLogout.html", method=RequestMethod.GET)
@ResponseBody 
public MyreturnObject getPostLogout(){
    return new ReturnObject(true,true,false);
}

Spring+Jackson will take care of serializing the Object to JSON and setting the correct mime type. See this previous answer of mine for a full working version.

Upvotes: 1

Related Questions