1.web.xml中配置Spring的servlet和servlet-mapping
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
2.配置spring配置文件application-servlet.xml
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/page/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/login.do">loginAction</prop>
</props>
</property>
</bean>
<bean id="loginAction" class="loginAction">
<property name="commandClass">
<value> LoginActionVo </value>
</property>
<property name="formView">
<value>login</value>
</property>
<property name="sessionForm">
<value>true</value>
</property>
<property name="serviceLocator">
<ref bean="servicelocator" />
</property>
</bean>
3.新建類繼承SimpleFormController﹐並複寫protected Object formBackingObject(HttpServletRequest request) 和 protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response,
Object cmd, BindException ex)。常用結構為
protected Object formBackingObject(HttpServletRequest request){
LoginActionVo loginActionVo = new LoginActionVo ();
request.setAttribute(" loginActionVo", loginActionVo);
return loginActionVo;
}
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response,
Object cmd, BindException ex){
LoginActionVo loginActionVo =(LoginActionVo)cmd;
Map map = new HashMap();
map.put(" loginActionVo", loginActionVo);
request.getSession().setAttribute(this.getFormSessionAttributeName(), loginActionVo);
return new ModelAndView("login",map);
}
4.將jsp頁面參數和VO進行綁定。綁定的方法為頁面元素name和VO對象對應﹐當進行深層次的綁定時﹐要注意﹐在變量的get方法中進行初始化。在servlet2.4容器中可以不用c:out標籤
輸入框綁定﹕<input name="user.name" value = "<c:out value="${loginActionVo.user.name}"/>" type="text" disabled="disabled" size="14" maxlength="14" /></td>
VO為﹕
public class loginActionVo{
private User user;
public User getUser(User user){
if( user == null){
user = new User();
}
return user;
}
}