SpringMVC編程<二>
多業務方法控制器:它是現在推薦使用的註解方式的前身技術
這個類要繼承MultiActionController(已經過時了)
public class MultiContorllerDemo extends MultiActionController {
public void one() {
System.out.println("這是一個空參方法...是不行的");
}
// 要求帶HttpServletRequest request,HttpServletResponse response
public void two(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("業務方法2: 參數必須帶原生的 request和response");
}
public String three(HttpServletRequest req, HttpServletResponse resp,User user) {
System.out.println("業務方法2: 參數必須帶原生的 request和response,還可以帶其他參數");
System.out.println("User:" + user);
//結果頁面--配置文件中配置
return "three";
}
public ModelAndView four(HttpServletRequest req, HttpServletResponse resp,User user) {
System.out.println("業務方法2: 參數必須帶原生的 request和response,還可以帶其他參數");
//把數據自己封裝到結果頁面 ModelAndView
ModelAndView mv= new ModelAndView();
mv.addObject("user", user);//封裝信息
mv.setViewName("four");//結果資源名稱:four
System.out.println("User:" + user);
//結果頁面--配置文件中配置
return mv;
}
public void execute(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("默認方法...");
}
}
我在web.xml中配置了另一個bean.xml
放在src下
在hncu.properties配置文件中寫導向的結果頁面
多方法類中的返回值(String類型),就是在這裏匹配結果頁面
要使用多方法,在bean.xml中配置必要的核心類:
beans.xml
<!-- 啓用Spring(ContextLoaderListener核心類)之後,
項目的bean(業務模塊或MVC模塊),放在哪一個XML中配置都可以,
2者是同一個容器空間
-->
<!-- 如果把bean配置到Spring容器,該核心類,把URL映射成beanName -->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
<!-- 解析方法的核心類 -->
<bean id="methodResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<!-- 沒有指定,就指定默認 -->
<property name="defaultMethodName" value="execute"></property>
<!-- 前面的href就要在?後面加 method=two,也可以改成abc -->
<property name="paramName" value="method"></property>
</bean>
<bean name="/multi" class="cn.hncu.v3.MultiContorllerDemo">
<!-- 一定要配置一個幫我們解析方法的 核心類-->
<property name="methodNameResolver" ref="methodResolver"></property>
</bean>
演示調用:
sp/:代表在web.xml中配置了,這個路徑下都攔截;
multi:代表MultiContorllerDemo的映射路徑名,在beans.xml配置了;
?號後面的method是代表你要調用的方法名;可以在配置文件中更改,改成abc也行
可以在後面傳遞參數。
現在使用的註解技術Annotation
先寫個第一版本:AnnoOneContoller
需要在配置文件中加載核心類:
<!-- 用於處理註解URL核心類 ,識別用了註解的bean -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>
將類加載爲一個bean
<bean id="one" class="cn.hncu.anno.AnnoOneContoller"></bean>
第二個版本可以給類加個子路徑:
@Controller
@RequestMapping(value="/anno2")//帶前綴路徑
public class AnnoTwoContoller {
@RequestMapping(value="/anno_three")
public String two(){
System.out.println("AnnoTwoContoller中的anno_two,帶前綴的路徑");
return "anno_three";
}
}
配置bean
<bean id="two" class="cn.hncu.anno.AnnoTwoContoller"></bean>
也可以不配置單獨的bean,可以直接配置一個自動掃描:
<!-- 自動掃描,幫我們把指定包中的所有bean掃描出來,並創建到Spring容器中 -->
<context:component-scan base-package="cn.hncu"></context:component-scan>
演示: