由于自己也是初学者,还不太会用maven,故手动下载jar包,配置导入非常麻烦
1、首先在创建项目时,spring和mybatis均要勾选
2、配置tomcat:若是创建的web项目,此时tomcat的名字是默认的tomcat版本
注意一定要配置项目发布的上下文名称
3、详解导入的jar包
根据tomcat的版本(8.5.40)导入其lib包:保险起见,导入所有包而不只是servlet-api和jsp-api包
导入连接数据库的jar包
导入spring整合mybatis的jar包,注意以下软件的版本号
MyBatis-Spring | MyBatis | Spring | Java |
2.0 | 3.5+ | 5.0+ | 8+ |
1.3 | 3.4+ | 3.22+ | 6+ |
1.3.0 (我的) | 3.5.1(我的) | 4.3.18(我的) | 11(我的) |
导入mybatis的所有jar包:一个mybatis-3.5.1包和12个jar包
导入spring的jar包:系统下载了大部分可用包,但是要借助tomcat封装的监听器,帮助加载spring的配置文件时,还需要spring-framework-4.3.18.RELEASE\libs\spring-web-4.3.18.RELEASE.jar包,由于idea下载的spring是4.3.18,故需要在https://repo.spring.io/webapp/#/artifacts/browse/tree/General/libs-release-local/org/springframework/spring/4.3.8.RELEASE/spring-framework-4.3.8.RELEASE-dist.zip下载全部dist包,解压找到对应的spring-web包,导入项目
修复Problems
4、有些包没有加入到out里的lib下,需要修复Problems
5、tomcat的web.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 上下文参数 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- spring配置文件 -->
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 封装了一个监听器,帮助加载Spring的配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
6、servlet测试:从ServletContext读取ApplicationContext
package servlet;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import service.AirportService;
import service.impl.AirportServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(value = "/airport")
public class AirportServlet extends HttpServlet {
private AirportService airportService;
@Override
public void init() throws ServletException {
//实例化service接口
//Tomcat启动自动加载xml文件
System.out.println(getServletContext());
ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
airportService = ac.getBean("airportService", AirportServiceImpl.class);
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("list", airportService.show());
req.getRequestDispatcher("index.jsp").forward(req, resp);
}
}