SpringMVC-03-HelloSpringMVC(註解版)
阿新 • • 發佈:2020-09-02
註解版步驟
-
新建一個module,新增web的支援
-
由於Maven可能存在資源過濾的問題,我們將配置完善pom.xml
<build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
-
在pom.xml檔案引入相關的依賴
主要有Spring框架核心庫、SpringMVC、servlet、JSTL等,我們在父依賴中已經引入了!
-
配置web.xml
注意點:
- 注意web.xml版本問題,要最新版;
- 註冊DispatcherServlet
- 關聯SpringMVC的配置檔案
- 啟動級別為1
- 對映路徑為/【不要用/*】
-
配置springmvc配置檔案和檢視解析器
我們把所有檢視都存放在/WEB-INF/目錄下,可以保證檢視安全,因為這個目錄下的檔案,客戶端不能直接訪問。
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--自動掃描包 讓指定包下的註解生效 由IOC容器統一管理--> <context:component-scan base-package="com.kuang.controller"/> <!--讓spring mvc不處理靜態資源 .css .js --> <mvc:default-servlet-handler/> <!--annotation-driven幫助我們自動完成handlermapper和adapter例項的注入--> <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>
-
建立Controller
@Controller @RequestMapping("/hello") public class HelloController { //真實訪問地址:專案名/hello/h1 @RequestMapping("/h1") public String Hello(Model model){ model.addAttribute("msg","Hello SpringMVC annotation!"); return "hello"; //會被檢視解析器處理 } }
-
建立檢視層
檢視可以直接取出並展示從Controller帶回的資訊,可以通過EL表示取出Model中存放的值或者物件;
-
配置Tomcat執行
小結
實現步驟其實很簡單:
- 新建一個web專案
- 匯入相關jar包
- 編寫web.xml,註冊DispatcherServlet
- 編寫springmvc配置檔案
- 建立對應的控制類,controller
- 完善前端檢視和controller之前的對應
- 配置tomcat,測試執行除錯。
springMVC必須配置的三大件:
- 處理器對映器
- 處理器介面卡
- 檢視解析器
通常只需要手動配置檢視解析器,而處理器對映器和處理器介面卡只需要開啟註解驅動即可,省去了大段的xml配置。