在这个例子将会学习怎样使用spring annotations填充一个表单。带annotation的Controller类如下:
package com.zcl.spring.formtag;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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;
@Controller
@RequestMapping("/userRegistration.html")
@SessionAttributes("user")
public class UserController{
private UserService userService ;
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
@ModelAttribute("countryList")
public List<Country> populateCountryList(){
return userService.getAllCountries() ;
}
@ModelAttribute("communityList")
public List<Community> populateCommunityList(){
return userService.getAllCommunities() ;
}
@RequestMapping(method = RequestMethod.GET)
public String showUserForm(ModelMap model){
User user = new User() ;
model.addAttribute("user", user);
return "userForm" ;
}
public String onSubmit(@ModelAttribute("user")User user){
userService.add(user) ;
return "redirect:userSuccess.html" ;
}
}
populateCountryList() 和 populateCommunityList()方法分别用来填充country和community,@ModelAttribute annotation用于方法上时表示包含着模型层的应用数据。所以它会在表单加载前被调用。这和覆写继承SimpleFormController的referenceData()相似。用于最后使用了重定向到UserSuccess.html所以我们还需要一个UserSuccessController。
package com.zcl.spring.formtag;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class UserSuccessController {
@RequestMapping("/userSuccess.html")
public String redirect(){
return "userSuccess" ;
}
}
在重新配置一下dispather-servlet.xml文件。
<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="userService" class="com.zcl.spring.formtag.UserServiceImpl" />
<context:component-scan base-package="com.zcl.spring.formtag" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
</beans>
其他地方基本和我们前面做的差不多。运行结果一致。