我們的目的是爲了創建一個簡單的關係管理應用,這個程序將用表單獲得關係信息,然後將信息打印到控制檯上,我們將學習怎麼樣不活表單數據用Spring3MVC
讓我們開始添加關係表單從我們的Spring3MVC Hello World application,打開index.jsp,改變它:
File: WebContent/index.jsp
<
jsp:forward
page
=
"contacts.html"
></
jsp:forward
>
以上的代碼將會使用戶跳轉到contacts.html頁面
創建一個jsp文件,它用來顯示錶單給我們的用戶
File:
/WebContent/WEB-INF/jsp/contact.jsp
<%@taglib
uri="http://www.springframework.org/tags/form" prefix="form"%>
<
html
>
<
head
>
<
title
>Spring
3 MVC Series - Contact Manager</
title
>
</
head
>
<
body
>
<
h2
>Contact
Manager</
h2
>
<
form:form
method
=
"post"
action
=
"addContact.html"
>
<
table
>
<
tr
>
<
td
><
form:label
path
=
"firstname"
>First
Name</
form:label
></
td
>
<
td
><
form:input
path
=
"firstname"
/></
td
>
</
tr
>
<
tr
>
<
td
><
form:label
path
=
"lastname"
>Last
Name</
form:label
></
td
>
<
td
><
form:input
path
=
"lastname"
/></
td
>
</
tr
>
<
tr
>
<
td
><
form:label
path
=
"lastname"
>Email</
form:label
></
td
>
<
td
><
form:input
path
=
"email"
/></
td
>
</
tr
>
<
tr
>
<
td
><
form:label
path
=
"lastname"
>Telephone</
form:label
></
td
>
<
td
><
form:input
path
=
"telephone"
/></
td
>
</
tr
>
<
tr
>
<
td
colspan
=
"2"
>
<
input
type
=
"submit"
value
=
"Add
Contact"
/>
</
td
>
</
tr
>
</
table
>
</
form:form
>
</
body
>
</
html
>
我們將會添加邏輯處理用Spring3來顯示錶單和取得值從表單中,爲了達到這個目的,我們要創建兩個java文件,首先是Contact.java,它是爲了顯示和取得數據從屏幕上,
第二個ContactController.java,他是spring controller class
File: com.dufeng.form.Contact
package
com.dufeng.form;
public
class
Contact {
private
String firstname;
private
String lastname;
private
String email;
private
String telephone;
//..
getter and setter for all above fields.
}
File: com.dufeng.controller.ContactController
package
com.dufeng.controller;
import
com.dufeng
.form.Contact;
import
org.springframework.stereotype.Controller;
import
org.springframework.validation.BindingResult;
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.SessionAttributes;
import
org.springframework.web.servlet.ModelAndView;
@Controller
@SessionAttributes
public
class
ContactController {
@RequestMapping
(value
=
"/addContact"
,
method = RequestMethod.POST)
public
String addContact(
@ModelAttribute
(
"contact"
)
Contact
contact, BindingResult result) {
System.out.println(
"First
Name:"
+ contact.getFirstname() +
"Last
Name:"
+ contact.getLastname());
return
"redirect:contacts.html"
;
}
@RequestMapping
(
"/contacts"
)
public
ModelAndView showContacts() {
return
new
ModelAndView(
"contact"
,
"command"
,
new
Contact());
}
}
程序已經完成,運行ok