springMVC(5) springMVC一个controller写多个方法

  • Post author:
  • Post category:其他




上面的例子都是实现

Controller,


实现


handleRequest


方法,我们想像


struts2


那样一个


action


里有多个方法怎么办?



可以继承

MultiActionController


类,在类里写多个方法。


spring-servlet.xml


里需要配置


ParameterMethodNameResolver





MultiController:

package com.xdy.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 request,
			HttpServletResponse response) throws Exception {
		System.out.println("---add---");
		return new ModelAndView("/welcome","method","add");
	}

	public ModelAndView update(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("---update---");
		return new ModelAndView("/welcome","method","update");
	}
}



spring-servlet.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	<bean name="/multi" class="com.xdy.controller.MultiController">
		<property name="methodNameResolver" ref="parameterMethodNameResolver"></property>
	</bean>
	
	<bean id="parameterMethodNameResolver" 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>




welcome.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>springMVC中一个controller中写多个方法</title>
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
  </head>
  <body>
    <h1>一个controller中写多个方法</h1>
    	方法名称是:${method }
  </body>
</html>



版权声明:本文为xiongwt原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。