springMVC之多方法訪問

這個和Struts2是一樣的,往往我們在編寫程序的時候,會涉及到很多的方法,很多的模塊,不可能我們每一個方法都要爲其新建一個controller吧,所以這個時候我們往往會將一個模塊的相關方法放到一起,簡化了開發,也方便了管理。那麼在springMVC中該如何進行多方法的訪問呢,請往下看:

1、配置環境搭建(略...)

2、編寫springMVC-xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
       xmlns:mvc="http://www.springframework.org/schema/mvc"  
       xmlns:context="http://www.springframework.org/schema/context"  
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       xsi:schemaLocation="http://www.springframework.org/schema/beans  
            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
            http://www.springframework.org/schema/context   
            http://www.springframework.org/schema/context/spring-context-3.1.xsd  
            http://www.springframework.org/schema/mvc  
            http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"> 
    
    <bean id="/test1/multi" class="com.tgb.web.controller.MultiController">
        <!-- bean引用方法解析器 -->
        <property name="methodNameResolver">
            <ref bean="paramMethodResolver" />
        </property>
    </bean>
    
    <!-- 配置方法解析器 -->
    <bean id="paramMethodResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver" >
        <property name="paramName" value="action"></property>
    </bean>
    
    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/> 
        <property name="suffix" value=".jsp"/> 
    </bean>
 </beans>  
3、編寫controller
package com.tgb.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;
public class MultiController extends MultiActionController {
    public ModelAndView add(HttpServletRequest arg0,
            HttpServletResponse arg1throws Exception{
        System.out.println("----------add()--------------");
        return new ModelAndView("/multi","method","add");
    }
    
    public ModelAndView update(HttpServletRequest arg0,
            HttpServletResponse arg1throws Exception{
        System.out.println("----------update()--------------");
        return new ModelAndView("/multi","method","update");
    }
}
4、編寫返回頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <h2>當前調用方法:${method }</h2>
</body>
</html> 
發佈了159 篇原創文章 · 獲贊 243 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章