Select标记始终返回null

时间:2014-03-30 16:49:32

标签: html twitter-bootstrap select playframework

我正在尝试创建一个搜索模块,根据用户选择的条件从数据库中搜索商店详细信息

index.scala.html

@import helper._
@import helper.twitterBootstrap._

@main(Html("Home")) {
  <!-- Main component for a primary marketing message or call to action -->
  <div class="jumbotron">
    <h1>Shop Directory</h1>
    <p>Lets you search a nearby Shop and get to know their location</p>
    <p>Search Shop by Product or Shop name</p>

    <form class="form-inline" action="@routes.SearchController.search()" method="post">
      <input type="text" class="form-inline input-lg" placeholder="Product/Shop name" name="keyword" required="keyword required">

      <select class="form-inline input-lg" id="Select1" name="criteria">
        <option value="">-:Select Criteria:-&nbsp;</option>
        <option value="shop">Shop</option>
        <option value="product">Product</option>
      </select>
      <button class="btn btn-lg btn-primary" role="button">Search</button>
    </form>
  </div>
}

Search.java

package viewmodels;

public class Search {
  public String keyword;
  public String criteria;
}

SearchResult.java

package viewmodels;

import models.Shop;
import play.mvc.Controller;
import java.util.ArrayList;
import java.util.List;

public class SearchResult extends Controller {
  public String criteria;
  public String keyword;

  public List<Shop> shops;

  public SearchResult() {
    shops = new ArrayList();
  }
}

SearchController.java

package controllers;

import models.Product;
import models.Shop;
import play.data.DynamicForm;
import play.data.Form;
import play.mvc.Controller;
import viewmodels.Search;
import viewmodels.SearchResult;
import java.util.List;
import play.mvc.Result;
import static play.data.Form.*;

public class SearchController extends Controller {

  public static Result search() {

    Form<Search> requestData = form(Search.class).bindFromRequest();

    Search datatosearch = requestData.get();
    // String criteria="shop";
    String criteria = datatosearch.criteria;

    SearchResult result = new SearchResult();
    result.criteria = criteria;
    result.keyword = datatosearch.keyword;

    if (criteria == "shop") {
      List<Shop> shops = Shop.findByShopName(datatosearch.keyword);
      result.shops.addAll(shops);
    }
    else if (criteria == "product") {
      List<Shop> shops = Product.findByShopName(datatosearch.keyword);
      result.shops.addAll(shops);
    }

    return ok(views.html.search.results.render(result));
  }
}

如果我在SearchController.java中执行String criteria="shop"String criteria="product",那么它工作正常,这意味着我的模型查询是正确的,但是如果我使用字符串criteria = datatosearch.criteria执行上面的代码,它会显示一个空白的屏幕。

我正在使用游戏框架,我真的很困惑,任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

您正在将字符串与==运算符进行比较,这是一个禁忌号。将字符串比较更改为使用String.equals,这样您实际上是在比较值而不是对象引用。

if (criteria.equals("shop") {
  ...
}
else if (criteria.equals("product") {
  ...
}

您可能还想添加一些验证,以检查criteria是不是NULL