SpringMVC实现一个controller写多个方法
MultiActionController与ParameterMethodNameResolver
在一个Controller类中定义多个方法,并根据使用者的请求来执行当中的某个方法,相当于Struts的DispatcherAction。使用MultiActionController需要配个MethodNameResolver实例,默认使用ParameterMethodNameResolver,他会根据所给的网址中,最后请求的文件名称来判断执行Controller中的哪一个方法
1.控制器类继承MultiActionController
package com.ljq.web.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; /** * 实现一个controller写多个方法 * * @author Administrator * */ public class MultiController extends MultiActionController { public ModelAndView add(HttpServletRequest request, HttpServletResponse response) { System.out.println("----add----"); return new ModelAndView("/multi", "message", "add"); } public ModelAndView update(HttpServletRequest request, HttpServletResponse response) { System.out.println("----update----"); return new ModelAndView("/multi", "message", "update"); } public ModelAndView query(HttpServletRequest request, HttpServletResponse response) { System.out.println("----query----"); return new ModelAndView("/multi", "message", "query"); } }
2.定义控制方法按如下格式
public ModelAndView add(HttpServletRequest request, HttpServletResponse response) { System.out.println("----add----"); return new ModelAndView("/multi", "message", "add"); }
3.在dispatcher-servlet.xml文件中引入多视图控制
<bean id="paramMethodResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName" value="action"></property>
</bean>
然后注入自己的控制器类
<bean name="/multi" class="com.ljq.web.controller.MultiController">
<property name="methodNameResolver">
<ref bean="paramMethodResolver"/>
</property>
</bean>
4.完善或者添加一个视图(multi.jsp),对应控制器类的跳转
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>实现一个controller写多个方法</title> </head> <body> 本次调用方法是<b>${message }</b> </body> </html>
5.部署,启动
访问路径: http://localhost:8083/springmvc/multi?action=add http://localhost:8083/springmvc/multi?action=update http://localhost:8083/springmvc/multi?action=query