一、下載
先去Spring官網看下springframework的最新版本號,或者是就用你想要下的版本,替換下面url中的版本號,就可以了
http://repo.springsource.org/libs-release-local/org/springframework/spring/4.2.1.RELEASE/spring-framework-4.2.1.RELEASE-dist.zip
再下一個依賴包apache commons logging
百度上搜一下,應該就有下載的
二、配置
我用的開發(fā)工具是eclipse for javaEE
打開新建一個web項目, Dynamic web module version 選擇2.5或者3.0以上double沒關系,選擇3.0以上的不要直接finish,一步一步的next,直到看到Generate web.xml deployment descripter選項,請打上勾,finish
在web.xml中配置
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 這個是設置spring配置文件路徑的,可以不配置-->
<!-- <init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:S.xml</param-value>
</init-param> -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
在WEB-INF下新建springMVC-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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
</beans>
三、spring HelloWorld項目###
在springMVC-servlet.xml文件beans標簽內加上
<!-- 視圖分解器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前綴 -->
<property name="prefix" value="/"></property>
<!-- 后綴 -->
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 啟用spring mvc 注解 -->
<context:annotation-config />
<!-- 設置使用注解的類所在的jar包 -->
<context:component-scan base-package="controllers"></context:component-scan>
<!-- 完成請求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
spring控制器返回的是一個字符串,最后產生的url是前綴+字符串+后綴
在工程src目錄下新建一個controllers包,再新建一個類
package controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class TestController {
@RequestMapping("/welcome")
public String welcome(){
return "welcome";
}
}
新建一個welcome.jsp文件
然后啟動tomcat,把工程發(fā)布到tomcat,打開瀏覽器,輸入http://localhost:8080/(項目名稱)/welcome 回車