手动创建1个基于注解的springmvc项目
眾所周知, SpringMvc有4個基本組件
DispatcherServlet -> 中央調度器, 使用前端設計模式攔截所有的url請求
HandlerMapping -> 分發不同的url到各個不同的controller處理
HanlderAdapter -> 調用controller去處理url請求
ViewReslover -> 處理視圖(jsp頁面)
在基于xml配置的springmvc項目中,
我們會將DispatcherServlet 配在WEB-INF/web.xml中(父容器)
會把HandlerMapping / HandlerAdapter/ ViewReslover 配置在 springmvc配置文件中。(子容器)
下面將會使用注解方式去重新創建1個springmvc項目
Step1 打開eclipse 創建1個新的Dynamic web project
Step2 往project內的 WEB-INF/lib folder導入下列spring 的jar包
大部分都能在 .m2 里的repository folder找到, 如果沒有可以利用別的maven project下載。
commons-logging-1.1.1.jarspring-aop-4.1.4.RELEASE.jarspring-aspects-4.1.4.RELEASE.jarspring-beans-4.1.4.RELEASE.jarspring-context-4.1.4.RELEASE.jarspring-core-4.1.4.RELEASE.jarspring-expression-4.1.4.RELEASE.jarspring-tx-4.1.4.RELEASE.jarspring-web-4.1.4.RELEASE.jarspring-webmvc-4.1.4.RELEASE.jarStep3 初步編寫web.xml 文件
在WEB-INF 文件夾創建1個web.xml 文件, 如上圖
內容如下, 注意我注解指定了spring 配置文件的位置和文件名
Step4 添加springmvc 配置文件
<?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"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd"><!-- Annotation scanning --><context:component-scan base-package="com.home.controller"></context:component-scan><!-- below mvc dom actullay includes the default Handlermapping and HandlerAdapter --><!-- org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping --><!-- org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter --><mvc:annotation-driven></mvc:annotation-driven></beans>注意, 在springmvc 配置文件中, 我們并沒有配置具體的controller類。
而是配置了一行注解, context:component-scan 將會在某個包里掃描注解了@Controller的類并放入容器.
同時, 我們也不需再單獨配置handlerMapping 和 HandlerAdapter
只需要引入springmvc命名空間和 mvc:annotation-driven</mvc:annotation-driven> 這個mvc注解驅動。
注意在demo方法返回了1個jsp fullpath
相應地要在WEB-INF里添加jsp文件夾以及demo1.jsp
執行項目, 訪問http://localhost:8080/springmvc_annotation/demo
成功執行
Step5 添加springmvc 配置,放行靜態文件
當前, DispatcherServlet會攔截所有url, 只放行*.jsp
項目中,我們其實想放行其他一切靜態文件, 例如js,css,images等
我們現在WEB-INF下添加文件夾resources, 放入1個js文件
在springmvc配置文件加入如下靜態資源定義
意思是主要url 符合 resources/** 規則 (例如 /resourcce/js/123/12.js …等)
則不會被DispatcherServlet攔截, 而會在location /WEB-INF/resources 里尋找靜態資源文件.
啟動項目, 訪問http://localhost:8080/springmvc_annotation/resources/js/jquery-2.1.1.js
成功訪問
到這里, springmvc的基本框架建立完成
總結
以上是生活随笔為你收集整理的手动创建1个基于注解的springmvc项目的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 手动创建1个基于xml配置的spring
- 下一篇: 想和高手侃侃而谈C++引用?看这一篇就够