一、开发依赖包
二、修改web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<!-- DispatcherServlet的配置用插件来完成
注意事项:
1.初始化参数:告知当前的springmvc的配置文件路径
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
2.配置当前service映射,url-pattern修改为/
-->
<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:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
改配置模板可以安装spring插件后按Alt+/ 选择倒数第二个
三、编写springmvc.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 配置
@Controller
@Service
-->
<context:component-scan base-package="com.springmvc.hendler"></context:component-scan>
<!-- 视图解析器:逻辑视图,物理视图
逻辑视图 hello
通过视图解析器转化为如下
物理视图 /hello.jsp
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
四、控制器
SpringMvc框架允许一个普通的加了@Controller标签的Java类来作为控制器
package com.springmvc.hendler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloWorldHandler {
/**
* 控制器处理请求的业务方法的格式
* public String 方法名称(){
*
* }
* String:当前方法处理完毕之后,所要返回的逻辑视图名称。
*
* */
@RequestMapping(value="/hello")
public String hello() {
System.out.println("走到了hello方法中。。。。");
return"success";
}
}
五、程序运行流程
点击index页面的hello超链接会跳转到success页面
<a href="hello">HELLO WORLD</a> 点击后回去寻找hello的连接 交由HelloWorldHandler.class中的
来完成,该方法先是在控制台输出语句 后返回字符 success通过springmvc.xml配置文件下的
视图解析器解析为 /success.jsp 物理地址成功找到并跳转页面
六、注意
<context:component-scan base-package="com.springmvc.hendler"></context:component-scan>
base-package="*" 填星号会出现错误
java.io.FileNotFoundException: class path resource [org/springframework/cache/jcache/config/AbstractJCacheConfiguration.class] cannot be opened because it does not exist