Java “返回HTTP状态”;“创建”;在游戏中!框架
我在一出戏中有一个Java “返回HTTP状态”;“创建”;在游戏中!框架,java,rest,playframework,http-status-codes,playframework-1.x,Java,Rest,Playframework,Http Status Codes,Playframework 1.x,我在一出戏中有一个动作!框架控制器,该控制器应返回HTTP状态代码已创建,并将客户端重定向到已创建对象的位置 public class SomeController extends Controller { public static void create() { Something something = new Something(); something.save(); response.status = StatusCode.C
动作!框架控制器,该控制器应返回HTTP状态代码已创建
,并将客户端重定向到已创建对象的位置
public class SomeController extends Controller {
public static void create() {
Something something = new Something();
something.save();
response.status = StatusCode.CREATED; // Doesn't work!
show(something.id);
}
public static void show(long id) {
render(Something.findById(id));
}
}
另见
上面的代码返回状态代码302 Found
,而不是201 Created
。我该怎么做才能让Play返回正确的状态(以及位置标题)?发生这种情况的原因是,一旦您创建了您的某物,您就通过调用Show
操作来告诉Play显示您的某物
为了实现这一点,play正在执行重定向(以保持其RESTful状态),告诉浏览器,由于调用create()
操作,它现在必须重定向到show()
操作
所以,你有两个选择
不呈现响应,让客户端处理创建响应后的响应(不理想)
不调用show(),只需在create()方法中自己呈现它
要使用选项2,它可能如下所示:
public static void create() {
Something something = new Something();
something.save();
response.status = StatusCode.CREATED;
renderTemplate("Application/show.html", something);
}
在Play framework中设置状态代码的示例代码:
Response.current().status=Http.StatusCode.CREATED 在play框架中,调用另一个操作会执行重定向,除非调用的操作不是公共的。
因此,以下是解决方案之一:
public class SomeController extends Controller {
public static void create() {
Something something = new Something();
something.save();
response.status = StatusCode.CREATED; // Doesn't work!
show(something.id);
}
private static void show(long id) {
render(Something.findById(id));
}
}
创建的201
应与解决方案2不会出现的位置
标题一起发送。你能解释一下解决方案1吗?我不明白。解决方案1不好。它基本上是说,在您的请求创建之后,然后是request show(),因此您的流是由客户端(即javascript)决定的,而不是在您的操作中由服务器端决定的。我已经检查了Play(1.2.3)的源代码,重定向对象有一个默认为302的代码。它有一个构造函数来提供不同的代码,但是这个构造函数似乎没有在框架中使用。