1.导入jar包
commons-logging-1.1.1.jar
jackson-annotations-2.5.4.jar
jackson-core-2.5.4.jar
jackson-databind-2.5.4.jar
spring-aop-4.1.6.RELEASE.jar
spring-beans-4.1.6.RELEASE.jar
spring-context-4.1.6.RELEASE.jar
spring-core-4.1.6.RELEASE.jar
spring-expression-4.1.6.RELEASE.jar
spring-tx-4.1.6.RELEASE.jar
spring-web-4.1.6.RELEASE.jar
spring-webmvc-4.1.6.RELEASE.jar
2.配置web.xml-配置分发器,在web.xml文件添加如下代码
<servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
3.添加springMVC配置文件,添加到web-inf目录下,名称规范:[dispatcherServlet]-servlet.xml,本案例为:springMVC-servlet.xml
4.编写控制器类HelloController,实现Controller接口
package com.ahd.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; public class HelloController implements Controller{ public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception { // TODO Auto-generated method stub ModelAndView mv=new ModelAndView(); //设置要显示到视图的信息 mv.addObject("msg", "hello springmvc"); //设置视图名称 mv.setViewName("hello"); return mv; } }
5.编写springMVC配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置handlerMapping --> <bean class=" org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean> <!-- 配置handlerAdapter --> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean> <!-- 配置渲染器 --> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <!-- 将视图名 渲染后视图的前缀 --> <property name="prefix" value="/WEB-INF/jsp/"/> <!-- 渲染后视图的后缀 --> <property name="suffix" value=".jsp"/> <!-- 例:视图名为:hello 渲染后:/WEB-INF/jsp/hello.jsp 该页面--> </bean> <!-- 配置请求和处理器 --> <bean name="/hello.do" class="com.ahd.controller.HelloController"></bean>
</beans>