SpringMVC——(1)HelloWorld
阿新 • • 發佈:2018-12-13
一、建立專案
1、使用Maven建立J2EE專案
2、加入Maven的jar包依賴
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.0.5.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-servlet-api --> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-servlet-api</artifactId> <version>7.0.42</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.3</version> </dependency>
二、配置專案
1、建立SpringMVC配置檔案
(1)在src/main/resources目錄下新建dispatcherServlet-servlet.xml檔案。
(2)配置自定掃描的包
<!-- 配置自定掃描的包 -->
<context:component-scan base-package="com.starfall.springmvc"></context:component-scan>
(3)配置檢視解析器
<!-- 配置檢視解析器: 如何把 handler 方法返回值解析為實際的物理檢視 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean>
2、在web.xml中配置DispatcherServlet
<servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:dispatcherServlet-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
- <url-pattern>/</url-pattern>會匹配到/login這樣的路徑型url,攔截所有(不包括jsp) (包含.js 、.png 、.css)
- <url-pattern>/*</url-pattern>會匹配所有url:攔截所有的資源 。會出現返回jsp檢視時再次進入spring的DispatcherServlet 類,導致找不到對應的controller所以報404錯。
- 下方會介紹處理靜態資源
3、建立controller測試
@Controller
public class HelloWorld {
@RequestMapping("/helloworld")
public String hello() {
System.out.println("hello world");
return "success";
}
}
新建index.jsp頁面:
新建成功頁:success.jsp