1. 程式人生 > 其它 >SpringMVC基於註解開發的步驟

SpringMVC基於註解開發的步驟

基於xml配置

.1準備好以下相關jar包

 

 

 .2建立Maven專案使用骨架  (這裡選擇第二個以webapp結尾的非第一個)

 

 

給專案起個名字

 

 

這裡可以更改maven本地倉庫(依賴包所存放的地方)的路徑和配置檔案,當前為預設

 

 

建立完後如圖

隨後右鍵專案名建立資料夾

按住Ctrl依次選擇下圖檔案

 

 

 此時專案結構圖如下

 

在WEB-INF下建立lib,將之前下載的jar包貼上進去

 

 

 緊接著如圖匯入依賴

 

 

 

 

選擇當前目錄下lib下的所有jar包,點選OK

 

 

 

開啟WEB-INF目錄下的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">

<!--註冊DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<!--關聯springmvc的配置檔案-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>

<!--classpath:springmvc-servlet.xml
在/src/main/resources 下建立Springmvc的配置檔案-->


</init-param>

<!--設定啟動級別 1 表示伺服器啟動,專案也跟著啟動-->
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://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="cn.spring02"/>


<!-- Spring MVC不處理靜態資源 -->
<mvc:default-servlet-handler />

<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類

package cn.spring02;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MVC02 {
@RequestMapping("/h2")
//表示需要訪問的路徑
public String show(Model model){
model.addAttribute("ASC","DS");
return "h2";
//需要與 @RequestMapping("/h2")中的字串保持一致
}
}
建立jsp頁面 位於WEB-INF/jsp/路徑下(自行建立)

 

啟動tomcat輸入/h2結果如下