如何解决Play框架中的空指针异常?

时间:2014-02-11 13:55:50

标签: java scala playframework nullpointerexception

我是Play框架的新手。

我正在使用两个表单,即第一种形式我给出两个值并将此值传递给下一个表单,在下一个表单中我想添加这两个数字。但是我在后面的行

中得到了空指针的删除
addition data=addform.get();

        return ok(
                sum_resul.render(data.First_No,data.Second_No)           //(sum was given form name)
                );
        }

我该如何解决这个问题。

这是我的代码

路线

GET     /                           controllers.Application.index()


GET    /Sum_result                  controllers.Application.sumresult()


GET     /assets/*file               controllers.Assets.at(path="/public", file)

Application.java

package controllers;

 import play.mvc.*;
 import play.data.*;                                    
 import static play.data.Form.*;    
 import play.data.validation.Constraints.*;         
 import views.html.*;

 public class Application extends Controller {

public static class addition
{

    @Required @Min(1) @Max(100) 
    public Integer First_No;  

    @Required @Min(1) @Max(100) 
    public Integer Second_No;

}

public static Result index() {
    return ok(index.render(Form.form(addition.class)));
}


public static Result sumresult()
{

Form<addition> addform=form(addition.class).bindFromRequest();
    if(addform.hasErrors())
    {
        return badRequest(index.render(addform));
    }
    else
    {
        addition data=addform.get();

        return ok(
                sum_resul.render(data.First_No,data.Second_No)           
                );
        }


}



}

index.scala

@(additionForm: Form[Application.addition])  

@import helper._

@main(title="The 'addition' Program") {

<h1>Configure Your 'Numbers'</h1>

@form(action=routes.Application.sumresult,args='id ->"additionForm"){           
@inputText(
field=additionForm("First_No"),
args='_label -> "Enter First Number",'placeholder -> "0-100"
)

@inputText(
field=additionForm("Second_No"),
args='_label -> "Enter Second Number",'placeholder -> "0-100"
)

 <p class="buttons">
        <input type="submit">
    <p>


    }
}

sum_resul.scala

@(First_No: Int, Second_No: Int)

@main("Here is the result:") {

<h1>
Sum of @First_No and @Second_No was (First_No+Second_No)
</h1>

<p class="buttons">
    <a href="@routes.Application.index">Back to the form</a>
</p>
}

例外

enter image description here

请帮帮我。提前谢谢。

2 个答案:

答案 0 :(得分:1)

这似乎相当自我解释,data为空,您正在尝试从中检索值。因此,您需要找出它为空的原因。

答案 1 :(得分:0)

if(data.size>0)  
  return ok(
                sum_resul.render(data.First_No,data.Second_No)           //(sum was given form name)
                );