工欲善其事,必先利其器,要想使用SpringMVC自然要先把配置文件寫好。
1.web.xml文件
新建web項目之后webRoot目錄下面會有一個web.xml文件,我們先來對其進行配置。
<servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.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>
這里定義了一個servlet,servlet名自己取后面要用到,class固定的,不可改變。
然后就是初始化init后要加載的xml文件,默認名為servlet名-servlet.xml,這個是要加載到
webroot-webinf-classes下的,我們將其放到項目目錄下的src目錄,它會自動加載到classes目錄。
於是我們在src下新建一個xxx-servlet.xml文件
2.springmvc-servlet.xml
這里配置上面所提到的servlet名-servlet.xml文件,放在項目目錄下的src目錄!!!
<?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: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.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!-- spring掃描的包 --> <context:component-scan base-package="com.eco.controllor"/> <!-- DispatcherServlet不處理靜態資源,交給服務器默認的servlet處理 --> <mvc:default-servlet-handler /> <!-- 啟用annotation --> <mvc:annotation-driven /> <!-- 視圖渲染器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- 前綴 --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- 后綴 --> <property name="suffix" value=".jsp" /> </bean> </beans>
鑒於annotation開發的高效率,這里一致使用annotation。
上面視圖渲染器定義,如果要訪問項目名/hello實際上就是訪問項目名/WEB-INF/jsp/hello.jsp,這樣是符合
編程開發的“約定優於配置”原則。就像數據庫有個表student,那么它的持久化類就應該是Student,我想在
瀏覽器訪問項目下的hello頁面,你就應該幫我指向項目名/WEB-INF/jsp/目錄下的hello.jsp頁面。
3.創建JSP頁面
WEB-INF/jsp/目錄下創建hello.jsp頁面,隨便在body中添加幾句話。
4.創建Controller類
@Controller public class Controller { @RequestMapping("/eco") public String hello(){ return "hello"; } @RequestMapping("/hi") public ModelAndView show(){ ModelAndView mv=new ModelAndView(); mv.addObject("msg", "world"); mv.setViewName("hi"); return mv; } }
類名自定義,下面看注解的意思
@Controller注解,聲明這個類是一個控制器Controller,
@RequestMapping("/hello") 這個注解當瀏覽器訪問項目名/eco時,跳轉到(return)到hello.jsp這個頁
面,也可以是其他頁面。下面一個Mapping注解呢,不僅實現了頁面跳轉(hi.jsp),還設置了一個msg
變量,可以在hi.jsp中用el表達式來調用它的值;hello ${msg} 輸出 hello world。
5.測試
接下來在瀏覽器輸入localhost:8080/webmvc/hi
------------------------------------------------------------------------------------------------------------------------------------------------------------------