1. 创建Web项目
如何创建Web项目请查看这篇文章: IDEA + Maven创建并运行Web项目
2. 添加依赖
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!-- spring web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
3. 添加index界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Hello</title>
</head>
<body>
Hello World
</body>
</html>
4. 编写Service
public class UserService
{
public void save()
{
System.out.println("save running");
}
}
5. 添加Spring核心配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userService" class="site.zhouyun.service.UserService"></bean>
</beans>
6. 编写Controller
public class UserController extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
// 通过Spring web提供的工具获取web应用上下文环境
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
UserService userService = (UserService) applicationContext.getBean("userService");
userService.save();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
doGet(req, resp);
}
}
7. 修改web.xml
<!-- 初始化参数 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>userController</servlet-name>
<servlet-class>site.zhouyun.controller.UserController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>userController</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>