開發spring工程建議安裝spring tools sutitejava
新建一個j2ee工程,在其中導入以下包web
commons-logging-1.1.1.jar spring-aop-4.0.0.RELEASE.jar spring-beans-4.0.0.RELEASE.jar spring-context-4.0.0.RELEASE.jar spring-core-4.0.0.RELEASE.jar spring-expression-4.0.0.RELEASE.jar spring-web-4.0.0.RELEASE.jar spring-webmvc-4.0.0.RELEASE.jar standard.jar
在web.xml中加入以下代碼spring
<servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <!-- 表示攔截全部請求 --> <url-pattern>/</url-pattern> </servlet-mapping>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 配置自動掃描包 --> <context:component-scan base-package="me.elin.springmvc.handle"></context:component-scan> <!-- 配置視圖解析器:把handle返回方法解析爲實際物理視圖 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- url映射的前綴 --> <property name="prefix" value="/WEB-INF/views/"></property> <!-- url映射的後綴 --> <property name="suffix" value=".jsp"></property> </bean> </beans>
若是安裝過spring tools suite的話,此處新建springDispatcherServlet-servlet.xml的過程應爲:在WEB-INF中新建 Spring Bean Definition file文件,名爲springDispatcherServlet-servlet.xml,點擊next,勾選上beans、context、mvc,而後點擊finsh。在生成的文件中加入express
<!-- 配置自動掃描包 --> <context:component-scan base-package="me.elin.springmvc.handle"></context:component-scan> <!-- 配置視圖解析器:把handle返回方法解析爲實際物理視圖 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- url映射的前綴 --> <property name="prefix" value="/WEB-INF/views/"></property> <!-- url映射的後綴 --> <property name="suffix" value=".jsp"></property> </bean>
package me.elin.springmvc.handle; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; //表示該類爲控制器類 @Controller //表示該類的url映射路徑爲/Hello @RequestMapping("/Hello") public class Hello { //表示該方法的url映射爲/hello @RequestMapping("/hello") public String hello(){ System.out.println("Hello world"); /** * 該方法的url訪問路徑爲/Hello/hello/,根據類名映射+方法名映射 * 返回的字符串表示指定物理映射路徑爲/WEB-INF/views/success.jsp,根據springDispatcherServlet-servlet.xml中所寫前綴+方法返回字符串+後綴 */ return "success"; } }
<a href="Hello/hello">測試請求</a>