springMVC第一個案例---hellospringMVC ...
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>
6.測試