springMVC配置action

springMVC配置action

Spring org.springframework.web.servlet.mvc.multiaction.MultiActionController与Struts 的 DispatchAction都是通过

http://.../userAction.do?method=updateUser 的方式来指定执行哪个方法。  
1. public class UserController extends MultiActionController {
   2.     public ModelAndView updateUser(HttpServletRequest request,
   3.             HttpServletResponse response) {
   4.         System.out.println("updateUser");//方便于跟踪执行了哪个方法
   5.         return new ModelAndView("userList","from","updateUser");
   6.     }
   7.      
   8.     public ModelAndView deleteUser(HttpServletRequest request,
   9.             HttpServletResponse response) {
10.         System.out.println("deleteUser");//方便于跟踪执行了哪个方法
11.         return new ModelAndView("userList","from","deleteUser");
12.     }
13. }
Bean配置
<bean name="/updateUser.html" class="com.unmi.UserController"/>
<bean name="/deleteUser.html" class="com.unmi.UserController"/>

org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver类是根据URL样式解析方法名。
<bean id="methodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver"></bean>

这样配置Class用了两次,如果是N个方法那就是N次可以用org.springframework.web.servlet.handler.SimpleUrlHandlerMapping
来简化操作。
<bean id="simpleUrlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

    <property name="mappings">
        <props>
            <prop key="/updateUser.html">updateController</prop>
            <prop key="/deleteUser.html">deleteController</prop>
        </props>
    </property>
</bean>
<bean id="updateController" class="com.xx.action.UpadateController" />
<bean id="deleteController" class="com.xx.action.DeleteController" />

通常情况下我们一个action类用来对应一个页面,所以可以使用通配符的方式来定义,例如两个页面group和user
<bean id="simpleUrlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

    <property name="mappings">
        <props>
            <prop key="/group/*.html">groupController</prop>
            <prop key="/user/*.html">userController</prop>
        </props>
    </property>
</bean>
<bean id="groupController" class="com.xx.action.GroupController" />
<bean id="userController" class="com.xx.action.UserController" />
另外提一下org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver,我们可以写一个类在继承他,重写

protected String getHandlerMethodNameForUrlPath(String urlPath)方法。
    @Override
    protected String getHandlerMethodNameForUrlPath(String urlPath) {
        if (urlPath.endsWith("/")) {
            urlPath = urlPath.substring(0, urlPath.length() - 1);
        }
        return super.getHandlerMethodNameForUrlPath(urlPath);
    }
然后再将bean id="methodNameResolver" class改为继承InternalPathMethodNameResolver类的类比如com.xx.xx包下的A类,我们就写成

com.xx.xx.A就可以了。
别忘了在web.xml里面配置
    <servlet-mapping>
        <servlet-name>action</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

你可能感兴趣的:(spring,bean,mvc,Web,servlet)