在 Web 项目中使用 Spring 框架,首先要解决在 web 层(这里指 Servlet)中获取到 Spring容器的问题。只要在 web 层获取到了 Spring 容器,便可从容器中获取到 Service 对象。
Web 项目使用 Spring 的问题
代码结构
新建一个 Maven Project
类型 maven-archetype-webapp
配置文件pom.xml,jar
<dependencies>
<!-- 单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- spring核心ioc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- 做spring事务用到的-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- mybatis的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!-- mybatis-spring两者集成的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<!-- 阿里公司的数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<!-- servlet依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- jsp依赖 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
<build>
<!-- 目的是将src/main/java目录中的xml文件包含到输出结果中。输出到classes目录中-->
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<!-- 指定jdk的版本-->
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
定义 index 页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>页面标题</title>
</head>
<body>
<p>注册学生</p>
<form action="reg" method="post">
<table>
<tr>
<td>id:</td>
<td><input type="text" name="id"></td>
</tr>
<tr>
<td>姓名:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>email:</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="注册学生"></td>
</tr>
</table>
</form>
</body>
</html>
定义 RegisterServlet
public class RegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String strId=request.getParameter("id");
String strName=request.getParameter("name");
String strEmail=request.getParameter("email");
String strAge=request.getParameter("age");
//创建spring的容器对象
String config="applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(config);
System.out.println("容器对象的信息========"+ac);
StudentService service = (StudentService)ac.getBean("studentService");
Student student=new Student();
student.setId(Integer.parseInt(strId));
student.setName(strName);
student.setEmail(strEmail);
student.setAge(Integer.parseInt(strAge));
service.addStudent(student);
//给一个jsp页面
request.getRequestDispatcher("/result.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
成功界面
<html>
<head>
<title>Title</title>
</head>
<body>
result.jsp注册成功!!!
</body>
</html>
配置tomcat
web.xml如果不是4.0版本的,可以把web.xml文件删除。
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">
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.b204.controller.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/reg</url-pattern>
</servlet-mapping>
</web-app>
接口及其映射文件
public interface StudentDao {
int insertStudent(Student student);
List<Student> selectStudents();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.b204.dao.StudentDao">
<insert id="insertStudent">
insert into student values(#{id},#{name},#{email},#{age})
</insert>
<select id="selectStudents" resultType="com.b204.entity.Student">
select id,name,email,age from student order by id desc
</select>
</mapper>
实体:
public class Student {
//属性名和列名一致,方便
private Integer id;
private String name;
private String email;
private Integer age;
//getter/setter/toString
}
业务层接口及其实现类:
public interface StudentService {
int addStudent(Student student);
List<Student> queryStudents();
}
public class StudentServiceImpl implements StudentService {
//引用类型
private StudentDao studentDao;
//使用set注入,赋值
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
public int addStudent(Student student) {
int res = studentDao.insertStudent(student);
return res;
}
@Override
public List<Student> queryStudents() {
List<Student> students = studentDao.selectStudents();
return students;
}
}
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: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 https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 声明数据源DataSource,作用是连接数据库的配置内容
-->
<!-- 把数据库的配置信息,写在一个独立的文件,编译-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 使用属性配置文件中的数据,语法${key}-->
<bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- set注入给DruidDataSource提供连接数据库信息-->
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- 最大连接数-->
<property name="maxActive" value="${jdbc.maxActive}"/>
</bean>
<!-- 声明的是mybatis中提供的SqlSessionFactoryBean类,这个类内部创建SqlSessionFactory的-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- set注入,把数据库的连接池赋给了dataSource属性-->
<property name="dataSource" ref="myDataSource"/>
<!-- mybatis主配置文件的位置
configLocation属性是Resource类型,读取配置文件
它的赋值 使用value,指定文件的路径,使用classpath:表示文件的位置
-->
<property name="configLocation" value="classpath:mybatis.xml"/>
</bean>
<!-- 创建dao对象,使用SqlSession的getMapper(StudentDao.class)
org.mybatis.spring.mapper.MapperScannerConfigurer在内部调用getMapper()生成每个dao接口的代理对象
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定SQLSessionFactory对象的id-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 指定报名,报名是dao接口所在的包名
MapperScannerConfigure会扫描这个包中的所有接口,把每个接口都执行一次getMapper()
方法,得到每个接口的dao对象。创建好的dao对象放入spring的容器中。
dao对象的名称是接口名称的首字母小写
-->
<property name="basePackage" value="com.b204.dao"/>
</bean>
<!-- 声明service-->
<bean id="studentService" class="com.b204.service.impl.StudentServiceImpl">
<property name="studentDao" ref="studentDao"/>
</bean>
</beans>
mybatis.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--这里映射的是mapper.xml文件,如果有多个mapper文件,记得修改此处-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!-- 设置别名-->
<typeAliases>
<!-- name:实体列的所在的包名-->
<package name="com.b204.entity"/>
</typeAliases>
<mappers>
<!-- name:是包名,这个包中的所有的mapper.xml一次都能加载-->
<package name="com.b204.dao"/>
</mappers>
</configuration>
结果:
数据库信息: