Spring-MVC入门(二):后端控制器

发表于:2011-3-09 09:37

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:86asm(JavaEyeblog)    来源:51Testing软件测试网采编

  概述此步要点:(1)继承SimpleFormController类(2)构造器中调用setCommandClass方法绑定定命令对象(这里为User类)(3)转换formbean为User类进行业务逻辑操作

  步骤二:配置web.xml(和前面HelloWorld实例一样,在此省略)

  步骤三:配置spmvc-servlet.xml文件,代码如下:

  Xml代码

  • <bean id="viewResolver"  class="org.springframework.web.servlet.view.InternalResourceViewResolver">    
  •     <property name="prefix" value="/WEB-INF/page/" />    
  •     <property name="suffix" value=".jsp" />    
  • bean>    
  •     
  • <bean id="simpleUrlHandlerMapping"   class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">    
  •     <property name="mappings">    
  •         <props>    
  •             <prop key="/reg.do">regControlprop>                    
  •         props>    
  •     property>    
  • bean>    
  • <bean id="regControl" class="com.asm.RegControl">bean>
  •   步骤四:根据配置文件完善相应页面在index.jsp设定表单填写页面,主要代码如下:

  • <form action="<%=request.getContextPath()%>/reg.do" method="post"> 
  •  
  •     用户名:<input type="text" name="username"><br/> 
  •  
  •     年龄:<input type="text" name="age"><br/> 
  •  
  •     <input type="submit"> 
  •  
  •     form>
  •   /page/hello.jsp,主要代码如下:

  • <body> 
  •  
  •     世界,你好!(WEB-INF/page)  
  •  
  •     用户名:${user.username }  
  •  
  •     年龄:${user.age }  
  •  
  • body>
  •   步骤五:启动服务器,访问到首页,填写表单完成测试。

      3、细研SimpleController控制器在RegControl.java中增加如下代码:

      Java代码

  • protected Object formBackingObject(HttpServletRequest request) throws Exception {     
  •         System.out.println("formBackingObject方法执行-->01");     
  •         setCommandClass(User.class); //也可在此处调用setCommandClass方法     
  •         return super.formBackingObject(request);     
  •     }     
  •     
  •     protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {     
  •         System.out.println("initBinder方法执行-->02");     
  •         super.initBinder(request, binder);     
  •     }     
  •          
  •     protected void onBind(HttpServletRequest request, Object command) throws Exception {     
  •         System.out.println("onBind方法执行-->03");     
  •         super.onBind(request, command);     
  •     }     
  •          
  •     protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors)     
  •             throws Exception {     
  •         System.out.println("onBindAndValidate方法执行-->04");     
  •         super.onBindAndValidate(request, command, errors);     
  •     }
  • 52/5<12345>
    《2023软件测试行业现状调查报告》独家发布~

    关注51Testing

    联系我们

    快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

    法律顾问:上海兰迪律师事务所 项棋律师
    版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
    投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

    沪ICP备05003035号

    沪公网安备 31010102002173号