使用简单的Servlet,集成Web项目
在 Web 项目中使用 Spring 框架,首先要解决在 web 层(这里指Servlet)中获取到 Spring 容器的问题。只要在 web 层获取到了 Spring 容器,便可从容器中获取到 Service 对象。
一、Maven项目目录结构
二、pom文件
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--lomok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<!--单一测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--Spring 依赖-->
<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>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<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>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
</dependency>
<!--监听器依赖项-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
三、实体类
package com.dgs.entity;
import lombok.Data;
@Data
public class Student {
private Integer stuid ;
private String stuname ;
private Integer stuage;
}
四、dao
package com.dgs.dao;
import com.dgs.entity.Student;
public interface StudentDao {
int insertStudent(Student student);
Student selectById(Integer id);
}
<?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">
<!--注意 namespace 后面 跟自己的包路径-->
<mapper namespace="com.dgs.dao.StudentDao">
<insert id="insertStudent">
insert into student (name,age)
values (#{stuname},#{stuage});
</insert>
<select id="selectById" resultMap="studentMap">
select age,name ,id from student
</select>
<resultMap id="studentMap" type="com.dgs.entity.Student">
<id column="id" property="stuid" />
<result column="name" property="stuname" />
<result column="age" property="stuage" />
</resultMap>
</mapper>
五、service
package com.dgs.service;
import com.dgs.entity.Student;
public interface StudentService {
int addStudent(Student student);
}
package com.dgs.service.impl;
import com.dgs.dao.StudentDao;
import com.dgs.entity.Student;
import com.dgs.service.StudentService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
public class StudentServiceImpl implements StudentService {
private StudentDao studentDao;
// set注入
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
// 新增一条数据
@Override
public int addStudent(Student student) {
return studentDao.insertStudent(student);
}
}
六、controller
package com.dgs.controller;
import com.dgs.entity.Student;
import com.dgs.service.StudentService;
import org.springframework.web.context.WebApplicationContext;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
public class AddStudentServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String strName = request.getParameter("name");
String strAge = request.getParameter("age");
WebApplicationContext ctx = null ;
String key = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
ServletContext sc = getServletContext();
Object attr = sc.getAttribute(key);
if (attr != null){
ctx = (WebApplicationContext) attr ;
System.out.println(ctx);
}
StudentService service = (StudentService) ctx.getBean("studentService");
Student student = new Student();
student.setStuname(strName);
student.setStuage(Integer.parseInt(strAge));
service.addStudent(student);
request.setAttribute("student",student);
request.getRequestDispatcher("/show.jsp").forward(request,response);
}
}
七、resources
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>
<!-- 设置日志 -->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--别名-->
<typeAliases>
<package name="com.dgs.entity"/>
</typeAliases>
<!-- 指定其他mapper文件的位置-->
<mappers>
<package name="com.dgs.dao"/>
</mappers>
</configuration>
spring-beans.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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--声明数据源-->
<bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="jdbc:mysql://localhost:3306/dgs_study" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<!--声明SqlSessionFactory-->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="configLocation" value="classpath:mybatis.xml" />
</bean>
<!--声明MapperScannerConfiguration-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="factory"/>
<property name="basePackage" value="com.dgs.dao"/>
</bean>
<!-- 注入变量到容器 -->
<bean id="studentService" class="com.dgs.service.impl.StudentServiceImpl">
<property name="studentDao" ref="studentDao" />
</bean>
<!-- ____________声明事务的控制_____________ -->
<!--1、声明事务管理器
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name="dataSource" ref="myDataSource" />
</bean>
-->
<!--<!–2、声明业务方法的事务属性(隔离级别,传播行为,超时)–>
<!–
id:给业务方法配置事务段代码起个名称,唯一值
transaction-manager:事务管理器的id
–>
<tx:advice id="serviceAdvice" transaction-manager="transactionManager">
<!–
给具体的业务方法增加事务的说明
name:业务方法名称,配置name的值 1:业务方法的名称 2:带有部分通配符的方法名称 3:使用*
propagation:指定传播行为的值
isolation:是否只读,默认false
timeout:超时时间
rollback-for:指定回滚的异常类列表,使用的异常全限定类名称
–>
<tx:attributes>
<tx:method name="add*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception"/>
<tx:method name="modify*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="remove*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
<tx:method name="*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<!–声明切入点表达式,表示那些包中的类,类中的方法参与方法与事务–>
<aop:config>
<!–声明切入点表达式
expression:切入点表达式,表示那些类和类中的方法参与事务
id:切入点表达式的名称:唯一值
–>
<aop:pointcut id="servicePointcut" expression="execution(* *..service..*.*(..))"/>
<!–管理切入点表达式和事务通知–>
<aop:advisor advice-ref="serviceAdvice" pointcut-ref="servicePointcut"/>
</aop:config>-->
</beans>
八、web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>AddStudentServlet</servlet-name>
<servlet-class>com.dgs.controller.AddStudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddStudentServlet</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-beans.xml</param-value>
</context-param>
<!-- 监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
九、前端界面
index.jsp
<%--
Created by IntelliJ IDEA.
User: 15015
Date: 2022/5/23
Time: 16:07
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<div align="center">
<form action="add" method="post">
xingming:<input type="text" name="name"><br/>
nianling:<input type="text" name="age" ><br/>
<input type="submit">
</form>
</div>
</body>
</html>
show.jsp
<%--
Created by IntelliJ IDEA.
User: 15015
Date: 2022/5/23
Time: 16:07
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
/show.jsp 注册成功${student.stuname}
</body>
</html>