构建简单的SPRING工程
描述配置一个简单的SPRING工程的步骤,工程中只包含一个控制器MainController。控制器使用方法名解析器,在访问控制器时,需要加上控制器类中的具体方法名。比如MainController控制器的映射地址是main.do,当访问时需要调用main.do?method=showMain(showMain为控制器类中具体存在的一个方法)。
工程代码
1:配置WEB.XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- spring Servlet 参数-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/ApplicationContext.xml
</param-value>
</context-param>
<!-- spring Listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- spring servlet -->
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/ApplicationContext.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
2:配置WEB-INFO/ApplicationContext.xml
需要放在WEB-INFO下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!--方法名解析器 -->
<bean id="methodNameResolver"
class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName">
<value>method</value>
</property>
</bean>
<!-- 控制器,使用方法名解析 -->
<bean name="/main.do" class="controller.MainController">
<property name="methodNameResolver">
<ref bean="methodNameResolver"/>
</property>
</bean>
</beans>
3:创建控制器MainController
控制器集成了MultiActionController
package 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;
/**
* spring控制器
* @author ahopedog
*
*/
public class MainController extends MultiActionController{
public ModelAndView showMain(HttpServletRequest req, HttpServletResponse resp){
System.out.println("调用showMain");
return new ModelAndView("/jsp/main.jsp");
}
}
4:访问控制器
/工程名/main.do?method=showMain