1. 新建工程
这里和视频中不一样,是在intellij下创建maven项目。
2. 添加jar包
需要添加的jar包有:aop,beans,context,core,expression,web,webmvc以及common-logging
但是因为这些包本身就有依赖关系,所以maven中只需要在pom文件中配置:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
3. 配置web.xml文件
<!-- 配置DispatcherServlet -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置 DispatcherServlet初始化参数,作用是配置springmvc配置文件的位置和名称-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
4. 创建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"
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 http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 首先配置自动扫描的包 -->
<context:component-scan base-package="com.weixuan.springmvc.handlers"></context:component-scan>
<!-- 配置视图解析器,如何把handlers方法的返回值解析成具体的物理视图 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
这里用了很高深的词:试图解析器。
简明来说,就是,这个bean会根据控制器中方法返回的字符串,以及预定义的前缀和后缀,拼接成一个jsp文件的路径。
5. 编写请求处理器
package com.weixuan.springmvc.handlers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
//标识为控制器
@Controller
public class HelloWorld {
/*
* 1、通过@RequestMapping注解来映射请求的url
* 2、返回值会通过视图解析器解析为实际的物理视图
* 3、InternalResourceViewResolver会做如下的解析:
* 通过prefix+returnvalue+suffix的方式得到具体的视图,然后做转发操作
*/
@RequestMapping("/helloworld")
public String Hello() {
System.out.println("HelloWorld!");
return "success";
}
}
6. 请求成功时跳转到的页面
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
</head>
<body>
<h4>Success Page!</h4>
</body>
</html>