參考:https://fangjian0423.gitbooks.io/springmvc-source-minibook/content/SpringMVC-introduction.html
SpringMVC:
使用:
需要在web.xml里配置DispatcherServlet。
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springConfig/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
需要在init-param里加上contextConfigLocation,這是配置spring上下文的配置文件,然后需要注意url-pattern是/不是/*,如果是/*的話可能會造成所有的url都會走springMVC了,把一些原本的.jsp .*這類的給覆蓋掉了
classpath:springConfig/dispatcher-servlet.xml
這個srping配置文件里可以配置掃描包的路徑,<context:component-scan base-package="org.format.demo.controller" />
@RequestMapping
顧名思義,就是請求映射。
我們看到@RequestMapping("/")中的"/"的意義就是contextPath后面的路徑;也就是 http://host:port/contextPath 后面的路徑。 (這里不一定都要以"/"開頭,比如 "/employee", 我們可以寫成 "employee" )
@RequestMapping注解的method參數(shù)
method參數(shù)表示的HTTP請求的方式。常見的有GET,PUT,POST,DELETE等。若請求的方法與后臺編寫的方法不一致,會出現(xiàn)HTTP 405錯誤。
@PathVariable注解
這是一種基于RESTFUL的注解。我們看到detail方法的@RequestMapping的value值/detail/{employeeId},參數(shù)中加入了一個@PathVariable employeeId。 這樣起作用的路徑就根據(jù)employee的Id,即每個員工都有獨立的一個URI路徑資源。 符合RESTFUL架構。Controller的方法參數(shù)
Controller的方法訪問非常靈活。 比如Employee有id,name,age等屬性。 只要我們在前臺傳入name為id,name,age這3個參數(shù),并且接受的方法有一個Employee對象參數(shù),SpringMVC會自動把3個注入到這個對象中。 還有其他一些Integer,Long參數(shù)等,SpringMVC會默認幫我們自動轉化。 同時參數(shù)也可以丟入一些HttpServletRequest,HttpServletResponse,HttpServletSession對象,SpringMVC會自動幫我們注入。 這點非常方便。不帶參數(shù)基于方法的@RequestMapping會被當然基于類的@RequestMapping所作用的地址的默認進入的方法
Final
SpringMVC是一個Web MVC框架。 它的特點是輕便,與Spring無縫整合,上手簡單。它的易用性、可擴展性、安全性均非常理想。