我们的目的是为了创建一个简单的关系管理应用,这个程序将用表单获得关系信息,然后将信息打印到控制台上,我们将学习怎么样不活表单数据用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