前言
PM学习JAVA笔录,共勉~
提示:以下是本篇文章正文内容,下面案例可供参考
一、整合前置环境
用eclipse创建好maven web工程,整合tomcat server,准本一个home.jsp放入…/webapp/WEB-INF/pages目录下。
二、整合步骤
1.配置依赖
仅提供了整合Spring MVC需要的依赖,前置环境的依赖不在此案例提供:
<!-- SpringMVC的jar包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
2.添加SpringMVC核心配置文件 - springmvc-config.xml
此配置文件里的全量内容如下:
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 1.配置前端控制器放行静态资源(html/css/js等,否则静态资源将无法访问) -->
<mvc:default-servlet-handler/>
<!-- 2.配置注解驱动,用于识别注解(比如@Controller) -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 3.配置需要扫描的包:spring自动去扫描 base-package 下的类,
如果扫描到的类上有 @Controller、@Service、@Component等注解,
将会自动将类注册为bean
-->
<context:component-scan base-package="com.centim.controller"></context:component-scan>
<!-- 4.配置内部资源视图解析器
prefix:配置路径前缀
suffix:配置文件后缀
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
3.添加Java测试文件
package com.centim.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/hello")
public String HelloSpringMVC() {
System.out.println("helloSpringMVC");
return "home";
}
}
4.测试入口及测试结果期望
测试入口:
http://localhost:8080/HelloSpringMVC/hello
测试结果期望:
正常跳转到 home page 页面
总结
<font color=#881030
Spring MVC整合关键点是在添加其核心springmvc-config.xml配置文件,重点关注配置文件中的注释讲解。