开发者

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

  • redirect to /logout.jsp => handled by spring security and then redirect to /postLogout.html => resp开发者_StackOverflow社区onse 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜