2013-04-21 82 views
0

我知道這應該很簡單,但是在嘗試了幾件事情後我仍然卡住了。 我只是試圖在我的jsp中顯示一個基本的下拉列表。春天版本是3,所以我想要一切工作與註釋。簡單的JSP-Spring 3下拉列表不起作用

JSP形式與下拉列表:

<form:form method="post" commandName="countryForm"> 
        <table> 
         <tr> 
          <td>Country :</td> 
          <td><form:select path="country"> 
            <form:option value="Select" label="Select" /> 
           </form:select> 
          </td> 

         <tr> 
          <td colspan="3"><input type="submit" /></td> 
         </tr> 
        </table> 
       </form:form> 

CountryForm.java是與一個單獨的字符串的屬性的「國家」的純對象,以其getter和setter。

控制器誰用GET請求涉及如下:

@Controller 
public class CountryFormController { 

@RequestMapping(value = "MainView", method = RequestMethod.GET) 
    public String showForm(Map model) { 
     CountryForm cform = new CountryForm(); 
     model.put("countryForm", cform); 
     return "MainView"; 
    } 
} 

然而,當我重定向到JSP 「的MainView」 我得到的典型錯誤:

org.apache.jasper.JasperException: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'countryForm' available as request attribute 
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502) 
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:424) 
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313) 

我在做什麼錯誤?

回答

0

Spring TagLib中的select標籤需要提供集合,地圖或選項數組。我不確定你會喜歡這些,所以我會做一些假設。

您需要在控制器中包含一個集合,地圖或對象數組。理想情況下,您將擁有一個Country類,併爲一組國家創建新實例。對於使用你的代碼的例子,我剛剛創建了一個靜態的國家列表。將列表添加到您的模型,然後修改select標記,將options設置爲${countries}。假設countryCountryForm中的String類型的字段,並且具有適當的get/set方法,則表單在提交時應該與數據綁定到字段。

控制器

@Controller 
public class CountryFormController { 

@RequestMapping(value = "MainView", method = RequestMethod.GET) 
    public String showForm(Map model) { 

     List<CountryForm> cfs = new ArrayList<CountryForm>(); 
     cfs.add("United States"); 
     cfs.add("Canada"); 
     model.put("countries", cfs); 
     model.put("countryForm", cform); 
     return "MainView"; 
    } 
} 

JSP

<form:select path="countryForm.country" options="${countries}"/> 
+0

謝謝,我已經試過了,但不斷拋出同樣的錯誤,指向「countryForm」(似乎仍然沒有被綁定)... – Hauri 2013-04-21 19:00:47

+0

@Hauri countryForm上的字段有getter/setter方法嗎? – 2013-04-21 19:53:45

+0

是的,我擁有它們,當然。我知道這應該是簡單的,但我已經嘗試了幾個選項,並總是得到相同的錯誤。 – Hauri 2013-04-21 21:47:15

0

我在GitHub示例代碼,試試吧一個讓我知道。看看landing.jspUserController

<form:select path="users[${status.index}].type" > 
    <form:option value="NONE" label="--- Select ---"/> 
    <form:options itemValue="name" itemLabel="description" /> 
</form:select> 

HTH