<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>spring3_test</display-name> <servlet> <servlet-name>spring</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
很少解釋,因此的請求都會交給org.springframework.web.servlet.DispatcherServlet取處理。java
3.在web.xml同級到目錄下建立一個spring-servlet.xml文件<?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" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 把標記了@Controller註解的類轉換爲bean --> <context:component-scan base-package="com.mvc.test" /> <!-- 啓動Spring MVC的註解功能,完成請求和註解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <!-- 對模型視圖名稱的解析,即在模型視圖名稱添加先後綴 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/view/" p:suffix=".jsp" /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8" /> </beans>
package com.mvc.test; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloController { @RequestMapping("/hello") public String helloWord(Model model) { String message = "Hello World, Spring 3.0!"; model.addAttribute("message", message); return "/login/hello"; } }這裏到參數model是spring mvc傳過來到,若是你須要傳遞一個參數,能夠這樣寫 <a href="hello.do?mess=hello">在controller中接收時到方法修改成 public String helloWorld(Model model,String mess){} 若是須要用到request,那在參數列表中加上HttpServletRequest request便可。 6.在spring-servlet.xml中對模型視圖到解析是這樣寫到:p:prefix="/WEB-INF/view/" p:suffix=".jsp",因此咱們在WEB-INF下建立目錄view,controller中return "/login/hello",因此再在view下建立一個login目錄,在login下建立一個hello.jsp。controller中添加了一個變量message,因此在hello.jsp中簡單打印一下便可:你好: ${message } 7.運行項目,基於spring mvc到helloworld就OK了。