簡體   English   中英

JSP-在編輯實體時如何在下拉菜單中設置指定的選定值?

[英]JSP - How to set specify the selected value in a dropdown when editing an entity?

當我編輯實體時,我想在下拉列表中設置類別的選定值。 但我無法按照我嘗試的方式進行操作。 我是Spring MVC的新手,但是我敢肯定,有一種更好的方法可以將模型映射到視圖。 你能提供一些例子嗎?

editMeal.jsp

    <%@ include file="/WEB-INF/template/taglibs.jsp"%>
<div class="container">
    <%@ include file="menu.jsp"%>

    <form:form commandName="editForm" method="post"
        class="form-horizontal form-width">

        <fieldset>
            <legend>Edit meal</legend>
            <div class="form-group">
            <input class="hidden" type="text" value="${idmeal}" hidden="true"
                    name="idmeal" />
                <label for="name" class="col-lg-2 control-label">Name</label>
                <div class="col-lg-10">
                    <input type="text" class="form-control" id="name"
                        placeholder="Name" name="name" value="${name }">
                </div>
            </div>          
            <div class="form-group">
                <label for="select" class="col-lg-2 control-label">Category</label>
                <div class="col-lg-10">
                    <select name="idCategory" class="form-control">
                        <option value="NONE">Select category</option>
                        <c:forEach items="${categories}" var="curCategory">
                            <c:choose>
                                <c:when test="${curCategory eq category}">
                                    <option value= "${category.text}" selected="selected">${category.value}</option>
                                </c:when>
                                <c:otherwise>
                                    <option value="${category.text}">${category.value}</option>
                                </c:otherwise>
                            </c:choose>
                        </c:forEach>
                    </select>
                </div>
            </div>          
            <div class="form-group">
                <label for="shortName" class="col-lg-2 control-label">Short name</label>
                <div class="col-lg-10">
                    <input type="text" class="form-control" id="shortName"
                        placeholder="Short name" name="shortName" value="${shortName }">
                </div>              
            </div>

            <div class="form-group">
                <label for="description" class="col-lg-2 control-label">Description</label>
                <div class="col-lg-10">
                    <input type="text" class="form-control" id="description"
                        placeholder="Description" name="description" value="${description }">
                </div>
            </div>

            <div class="form-group">
                <label for="price" class="col-lg-2 control-label">Price</label>
                <div class="col-lg-10">
                    <input type="text" class="form-control" id="price"
                        placeholder="Price" name="price" value="${price }">
                </div>

            </div>

            <div class="form-group">
                <div class="col-lg-10 col-lg-offset-2">
                    <a class="btn btn-warning"
                        href="http://localhost:8080/Catering/index/meals">Cancel</a>
                    <button type="submit" class="btn btn-warning">Submit</button>
                </div>
            </div>
        </fieldset>
    </form:form>
</div>

DropDownListItem.java

public class DropDownListItem {

   private String text;
   private String value;


   public DropDownListItem(String t, String n) {
      text = t;
      value = n;
   }
   //getters and setters
}

MealController.java

package catering.web.controller;
import java.util.ArrayList;
import java.util.List;    
import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;    
import catering.web.data_access.CategoryDataAccess;
import catering.web.data_access.MealDataAccess;
import catering.web.data_access.MealSummaryDataAccess;
import catering.web.helper.DropDownListItem;
import catering.web.mapper.MealMapper;
import catering.web.model.Category;
import catering.web.model.Meal;
import catering.web.model.MealSummary;
import catering.web.view_model.MealViewModel;

@Controller
public class MealController {

    protected static Logger logger = Logger.getLogger("controller");    

    @RequestMapping(value = "meals", method = RequestMethod.GET)
    public String mealsPage(Model model, Authentication authentication){

        logger.debug("Received request to show meals page(GET)");

        List<MealSummary> meals = MealSummaryDataAccess.getMeals();

        model.addAttribute("username", "You are logged in as " + authentication.getPrincipal());
        model.addAttribute("list", meals);

        return "meals";
    }

    @RequestMapping(value = "addMeal", method = RequestMethod.GET)
    public String addMealGet(Model model, Authentication authentication){

        populateModel(model);
        model.addAttribute("username", "You are logged in as " + authentication.getPrincipal());
        model.addAttribute("addForm", new MealViewModel());
        return "addmeal";
    }


    @RequestMapping(value = "addMeal", method = RequestMethod.POST)
    public String addMealPost(@ModelAttribute("addForm") MealViewModel mealVM, Model model, Authentication authentication){

        populateModel(model);
        model.addAttribute("username", "You are logged in as " + authentication.getPrincipal());

        Meal meal = MealMapper.mapMealVMToMeal(mealVM);

        MealDataAccess.insertMeal(meal);

        return "redirect:meals";
    }

    @RequestMapping(value = "editMeal", method = RequestMethod.GET)
    public String editMealGet(@RequestParam int id, Model model, Authentication authentication) {



        logger.debug("Received request to show edit user page(GET)");   

        model.addAttribute("username", "You are logged in as " + authentication.getPrincipal());
        populateModel(model);

        Meal meal = MealDataAccess.getMealById(id);
        MealViewModel mealMV = MealMapper.mapMealToMealVM(meal);

        model.addAttribute("idmeal", mealMV.getIdMeal() );
        model.addAttribute("name",mealMV.getName());
        model.addAttribute("category",mealMV.getIdCategory());
        model.addAttribute("shortName", mealMV.getShortName() );
        model.addAttribute("description", mealMV.getDescription() );
        model.addAttribute("price", mealMV.getPrice() );

        return "editmeal";
    }

    @RequestMapping(value = "deleteMeal", method = RequestMethod.POST)
    public String deleteMeal(@ModelAttribute("delete") @RequestParam int id){

        logger.debug("Received request to delete meal page(POST)");     

        MealDataAccess.deleteMeal(id);


        return "redirect:meals";
    }       

    private void populateModel(Model model){

        List<Category> cats = CategoryDataAccess.getCategories();
        List<DropDownListItem> categories = new ArrayList<DropDownListItem>();
        for(Category cat : cats){
            categories.add(new DropDownListItem(Integer.toString(cat.getIdCategory()),cat.getName()));
        }
         model.addAttribute("categories", categories);

    }

}

MealViewModel.java

public class MealViewModel {

   private int idMeal;
   private String name;
   private String shortName;
   private String description;
   private String idCategory;
   private float price;
   //getters and setters

}

為此,您將必須使用以下標記庫:

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>

編寫選擇標簽,如下所示:

<form:form commandName="editMeal" method="post"
    class="form-horizontal form-width">
    <-- other code -->
    <form:select id="categoryList" path="idCategory">
            <c:forEach items="${categories}" var="cat">
                <form:option  value="${category.text}" label="${category.value}"  />
            </c:forEach>
    </form:select>  
</form:form>

路徑將是模型屬性editMeal中的屬性,該屬性將用於設置列表中的值。 如下所示在控制器中設置editMeal屬性:

model.addAttribute("editMeal", mealMV);

您可以使用spring spring:bind標簽來嘗試一下,

<spring:bind path="idCategory">
<select name="idCategory" class="form-control">
                        <option value="NONE">Select category</option>
                        <c:forEach items="${categories}" var="curCategory">
                            <c:choose>
                                <c:when test="${curCategory eq modelAttribute.idCategory}">
                                    <option value= "${curCategory}" selected="true">${curCategory}</option>
                                </c:when>
                                <c:otherwise>
                                    <option value="${curCategory}">${curCategory}</option>
                                </c:otherwise>
                            </c:choose>
                        </c:forEach>
                    </select>
</spring:bind>

希望這可以幫助 !!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM