由於項目需要,學習下springMVC,在此簡單記錄一下。
如有十萬個爲什麼,暫且忽略,待以後研究。
本人是基於3.1.1版本開發,如遇jar包版本衝突等其他問題,概不負責。下載地址:上傳此zip資源文件,不知道CSDN爲什麼不給顯示,或許相同的資源太多了吧,
大家可自行去下載,或者進羣,共享裏有。
一:新建web工程,spring001
忽略
二:添加springframework依賴jar包
將dist下的jar全部加進去 然後另加一個commons-logging.jar
三:修改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>/WEB-INF/config/springMVC.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>
默認DispatcherServlet會加載WEB-INF/[DispatcherServlet的Servlet名字]-servlet.xml配置文件,
本示例爲WEB-INF/springMVC-servlet.xml
默認路徑爲WEB-INF下,也可修改爲如下配置
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <!-- <param-value>classpath:conf/springMVC.xml</param-value> -->
- <!-- <param-value>classpath:/conf/springMVC.xml</param-value> -->
- <!-- <param-value>classpath*:/conf/springMVC.xml</param-value> -->
- <!-- 以上三種形式也可以 -->
- <param-value>classpath:conf/springMVC.xml</param-value>
- </init-param>
四:添加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:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- default-lazy-init="true"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
- ">
- <!-- 默認掃描的包路徑 -->
- <context:component-scan base-package="com.itmyhome" />
- <!-- 添加註解驅動 -->
- <mvc:annotation-driven />
- <!-- 定義跳轉的文件的前後綴 -->
- <bean id="viewResolver"
- class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/" /> <!-- 默認放在WebRoot下 -->
- <property name="suffix" value=".jsp" />
- </bean>
- </beans>
base-package後的內容只是包路徑,千萬不能把類名也寫出來 比如com.itmyhome.Login
否則會報如下錯誤
警告: No mapping found for HTTP request with URI [/spring001/login] in DispatcherServlet with name 'springMVC'
五:後臺Action
- package com.itmyhome;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- @Controller
- public class Login {
- @RequestMapping(value="login")
- public String login(){
- System.out.println("*******已經進入*********");
- return "welcome"; //即返回welcome.jsp
- }
- }
六:返回JSP
新建welcome.jsp 裏面隨便寫點內容 如:Hello springMVC!
最後在瀏覽器中輸入地址 驗證 如圖:
工程目錄如下: