1. 程式人生 > >SpringMVC之Ambiguous mapping(模稜兩可的對映)

SpringMVC之Ambiguous mapping(模稜兩可的對映)

1、web.xml和核心配置檔案的編輯見上篇http://blog.csdn.net/u010101142/article/details/55005330;

2、還是HelloController類:

package com.slz.hello.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/hello")
public class HelloController {
	@RequestMapping(path={"/hello","/slz.html","/*/benboba.php","/**/baboben.aspx","/ab*.htm"})
	public ModelAndView hello(){
		System.out.println("Hello World!");
		ModelAndView mav = new ModelAndView();
		mav.setViewName("hello");///WEB-INF/hello.jsp
		return mav;
	}
	
	@RequestMapping(path={"index"})
	public ModelAndView index(){
		System.out.println("Hello Index!");
		ModelAndView mav = new ModelAndView();
		mav.setViewName("index");///WEB-INF/index.jsp
		return mav;
	}
	
	@RequestMapping(path={"index","indexAmbiguous"})//呼叫時報錯,Ambiguous mapping,模稜兩可的對映
	public ModelAndView indexAmbiguous(){
		System.out.println("Hello Index!");
		ModelAndView mav = new ModelAndView();
		mav.setViewName("index");///WEB-INF/index.jsp
		return mav;
	}
	
//	@RequestMapping(path={"index"})	//啟動時報錯,Ambiguous mapping,模稜兩可的對映
//	public ModelAndView indexAmbiguous02(){
//		System.out.println("Hello Index!");
//		ModelAndView mav = new ModelAndView();
//		mav.setViewName("index");///WEB-INF/index.jsp
//		return mav;
//	}

}
3、注意如果方法(不一定在同一個類)的RequestMapping路徑中存在相同的path值(預設訪問方法為get,比如index()和indexAmbiguous02()),啟動時會報Ambiguous Mapping異常;也會有呼叫時才報Ambiguous Mapping異常,比如index()和indexAmbiguous();

4、新建MethodAmbiguousController:

package com.slz.hello.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MethodAmbiguousController {
	//啟動沒問題,
	//testMethod01和testMethod02方法共存時,則:執行getMethod方法,根據方法型別選擇執行的方法
	//testMethod03方法與其他兩個方法共存時,則:執行getMethod方法,根據請求型別報錯//(Ambiguous handler methods mapped for HTTP path 'http://localhost:8080/mvc/getMethodAmbiguous')
	@RequestMapping(path="getMethodAmbiguous",method=RequestMethod.GET)
	public ModelAndView testMethod01(){
		System.out.println("getMethodAmbiguous");
		return null;
	}
	@RequestMapping(path="getMethodAmbiguous",method=RequestMethod.POST)
	public ModelAndView testMethod02(){
		System.out.println("getMethodAmbiguous");
		return null;
	}
	@RequestMapping(path="getMethodAmbiguous",method={RequestMethod.GET,RequestMethod.POST})
	public ModelAndView testMethod03(){
		System.out.println("getMethodAmbiguous");
		return null;
	}
}


總結:出現Ambiguous Mapping異常時,找到同一請求路徑對映到兩個方法的地方,修改即可~