3

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

  • redirect to /logout.jsp => handled by spring security and then redirect to /postLogout.html => response JSON
  • resolve to view entry, which is a jsp contain only a json string

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

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
jackysee
  • 2,051
  • 4
  • 32
  • 38

1 Answers1

1

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.

Community
  • 1
  • 1
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588