框架的使用和學(xué)習(xí),總要從環(huán)境的搭建和第一個實例做起。
1:類庫的引用,新建一個maven項目,將springMVC的依賴添加進來1 <!-- springMVC dependency-->
2 <dependency>
3 <groupId>org.springframework</groupId>
4 <artifactId>spring-webmvc</artifactId>
5 <version>4.0.3.RELEASE</version>
6 </dependency>
2:在web.xml中添加springMVC的控制器
1 <servlet>
2 <servlet-name>demo</servlet-name>
3 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
4 </servlet>
5
6 <servlet-mapping>
7 <servlet-name>demo</servlet-name>
8 <url-pattern>/</url-pattern>
9 </servlet-mapping>
3:添加springMVC的配置文件,注意:文件的名字需要是xxx-servlet,xxx就是剛才web.xml中添加的控制器的名稱
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
4 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
5 xmlns:util="http://www.springframework.org/schema/util"
6 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
7 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
8 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
9 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
10
11 <!-- 激活@Controller模式 -->
12 <mvc:annotation-driven />
13
14 <!-- 對包中的所有類進行掃描,以完成Bean創(chuàng)建和自動依賴注入的功能 需要更改 -->
15 <context:component-scan base-package="com.demo.*" />
16
17 <!-- 默認采用BeanNameViewResolver的請求解析方式,即
18 <bean name="/hello.html" class="XXXpackage.XXXclass"/>
19 的方式進行請求映射,該配置默認開啟,不寫亦可,這里采用注解映射
20 -->
21
22 <!-- 注解方式的請求映射 -->
23 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
24
25 <!-- 視圖的映射,這里需要根據(jù)controller的返回值來確定視圖 -->
26 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
27 <property name="prefix">
28 <value>/WEB-INF/jsp/</value>
29 </property>
30 <property name="suffix">
31 <value>.jsp</value>
32 </property>
33 </bean>
34
35 </beans>
36
4:添加一個控制器 1 package com.duyt.controllor;
2
3 import org.springframework.stereotype.Controller;
4 import org.springframework.web.bind.annotation.RequestMapping;
5
6 //注明當前這個類是控制器,項目啟動時會被掃描
7 @Controller
8 //該類的請求映射,為"/"
9 @RequestMapping("/")
10 public class HelloControllor {
11
12 //該方法的請求映射,需要將類的請求映射和方法的請求映射拼接起來,也就是"/hello"(類的請求映射為"/")
13 @RequestMapping("/hello")
14 public String Hello(){
15
16 //視圖的響應(yīng),根據(jù)配置文件的配置,會在WEB-INF/jsp文件夾中查找以hello為名稱,.jsp結(jié)尾的視圖文件
17 return "hello";
18 }
19 }
20
視圖就省略了,以上就是使用springMVC的流程,這篇就不記錄其他相關(guān)的功能了,傳參,異常,文件上傳等功能后續(xù)再整理,這里就只是記錄一個最簡單的體驗案例。