SpringMVC實現一個controller寫多個方法
阿新 • • 發佈:2019-02-04
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 classMultiController 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