简体   繁体   English

Play Framework 2.4如何在Action Controller中使用return语句

[英]Play Framework 2.4 how to use return statement in Action controller

is there a way to return a value inside Action controller. 有没有一种方法可以在Action控制器内返回值。

I have a method in my User model which returns the number of friends of a given user. 我的用户模型中有一个方法,该方法返回给定用户的朋友数。

def nrOfFriends(current_user: Long): Int = {
    DB.withConnection{ implicit connection =>
        var nr: Int = SQL("select count(*) from friend where user_id_1=" + current_user + " or user_id_2=" + current_user).as(scalar[Int].single)
        nr
    }
} 

In my controller, I just want to return the value from the model 在我的控制器中,我只想从模型中返回值

def freunde() = IsAuthenticated { username => _ =>
    User.findByUsername(username).map { user =>
     var nr: Int = Friend.nrOfFriends(user.id.get)
        Ok(""+nr)

    }.getOrElse(Forbidden)
}

But in the way that is written, it will print "empty string " concatenated with the number 但是以书面形式,它将打印与数字连接的“空字符串”

If I replace Ok(""+nr) with Ok(nr) I receive the following error: 如果我将Ok(“” + nr)替换为Ok(nr),则会收到以下错误:

"Cannot write an instance of Int to HTTP response. Try to define a Writeable[Int]" “无法将Int的实例写入HTTP响应。尝试定义Writeable [Int]”

I need for my action to return a value so that I can pass the value from the action to header.views.html inside the navbar something like that 我需要我的操作返回一个值,以便可以将值从操作传递到导航栏中的header.views.html之类的东西。

   <a href="#">@Freund.freunde Friends</a>

if you want your response to just be the value of nr you can simply call nr.toString : 如果您希望您的响应只是nr的值,则可以简单地调用nr.toString

def freunde() = IsAuthenticated { username => _ =>
    User.findByUsername(username).map { user =>
     var nr: Int = Friend.nrOfFriends(user.id.get)
        Ok(nr.toString)

    }.getOrElse(Forbidden)
}

The error you're getting makes reference to the fact that Int doesn't have an implicit Writeable[Int] in scope. 你得到的错误提到的事实, Int不具有隐含的Writeable[Int]范围。 So play doesn't know how display an Int in an http response. 因此play不知道如何在http响应中显示Int

You can add make Int writeable by putting this in scope: 您可以通过在范围内添加make Int可写:

implicit val intWriteable = play.api.http.Writeable[Int](_.toString.getBytes, None)

Then you would be able to just say: 然后,您可以说:

Ok(nr)

without error. 没有错误。

However, it sounds like you just want the result of nrOfFriends inside an unrelated template. 但是,听起来您只希望将nrOfFriends的结果放在不相关的模板中。 If that's the case, you should be using an Action at all. 在这种情况下,您应该完全使用Action Instead just call your model function inside the template where you need the data. 相反,只需在需要数据的模板内调用模型函数即可。

<a href="#">@User.nrOfFriends(user.id) Friends</a>

Of course you would need to pass in the user to the template as well. 当然,您还需要将用户传递给模板。

You didn't post a full sample of all the code involved in what you are trying to accomplish so I think this is the best I can do for now. 您没有发布要完成的所有代码的完整示例,所以我认为这是目前为止我能做的最好的事情。 Perhaps try posting the base template that your <a> is in. 也许尝试发布<a>所在的基本模板。

An important point is that Action s are for production an HTTP response, and not just plain data internally to the application. 重要的一点是Action是用于产生HTTP响应的,而不仅仅是应用程序内部的普通数据。

An action of a controller handles a request and generates a result to be sent to the client. 控制器的动作处理请求并生成要发送到客户端的结果。 In other words, an action returns a play.api.mvc.Result value, representing the HTTP response to send to the web client. 换句话说,一个操作返回一个play.api.mvc.Result值,该值表示要发送到Web客户端的HTTP响应。 In your example Ok constructs a 200 OK response. 在您的示例中,Ok构造一个200 OK响应。 The body of the response must be one of the predefined types, including text/plain, json, and html. 响应的主体必须是预定义的类型之一,包括text / plain,json和html。 The number of a friends is an integer and is NOT an acceptable type of the body. 朋友的数目是整数,不是可接受的主体类型。 Therefore, a simple way to address this problem is to convert it into a text/plain using .toString() . 因此,解决此问题的简单方法是使用.toString()将其转换为文本/纯文本。

On the other hand, you can define a writer for Int that lets Play know how to convert an integer into a json format. 另一方面,您可以为Int定义编写器,以使Play知道如何将整数转换为json格式。

For more details, please take a look at this https://www.playframework.com/documentation/2.2.x/ScalaActions . 有关更多详细信息,请查看此https://www.playframework.com/documentation/2.2.x/ScalaActions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM