目录
二、配置前端控制器( dispatcherServlet )
三、创建主配置文件 ( applicationContext.xml )
本章实现的功能:
搭建 SpringMvc 开发环境,发送 http://localhost:8080/springmvc01/hello.do?name=zs 请求,响应 JSP 页面。效果如下图:
一、 引入依赖
在 pom.xml 文件中
<!-- 引入 SpringMVC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
二、配置前端控制器( dispatcherServlet )
在 web.xml 文件中
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
这个配置做了2件事:
- 在容器运行时加载 DispatcherServlet 这个类 -->通过 <load-on-startup>1</load-on-startup> 实现
- 告诉Spring容器,我们自定义的主配置文件在哪 -->通过<param-value>classpath*:applicationContext.xml</param-value>
三、创建主配置文件 ( applicationContext.xml )
在 resources 文件夹下,创建 applicationContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置组件扫描-->
<context:component-scan base-package="com.lcy" />
<!-- 配置视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
四、编写控制器类 ( HelloController)
package com.lcy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/hello")
public String sayHello(String name, ModelMap modelMap){
modelMap.put("name", name);
return "hello";
}
}
五、创建响应页面 (hello.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>hello</title>
</head>
<body>
<h1 style="color:yellow"> hello -> ${name} </h1>
</body>
</html>
六、JSP页面热更新
七、可能遇到的问题
解决方法:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>