基于Spring注解 + MyBatis + Servlet 实现数据库交换的小小Demo
第一步 创建web 项目,这一步省略,有不会的可以参考之前发布的文档
第二步 配置pom.xml文件
<dependencies>
<!-- Spring常用依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--aop相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--注解-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<!-- Mysq连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<!--MyBatis核心依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!-- spring+mybatis集成依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<!--整合一下 web-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!-- servlet服务 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--logback 日志-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!--log4j 日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.logback-extensions</groupId>
<artifactId>logback-ext-spring</artifactId>
<version>0.1.4</version>
</dependency>
</dependencies>
<!--下面这一步配置到build标签里-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
<include>**/*.ini</include>
</includes>
</resource>
</resources>
配置数据库连接信息 db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
jdbc.username=root
jdbc.password=123456
配置web.xml
<!-- 配置日志 logback -->
<context-param>
<param-name>logbackConfigLocation</param-name>
<param-value>classpath:logback.xml</param-value>
</context-param>
<listener>
<listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class>
</listener>
<!--这个监听器 帮助加载spring 配置文件,创建spring 容器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
配置logback.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<Target>System.out</Target>
<Encoding>UTF-8</Encoding>
<encoder>
<pattern>%d{yyyy-MM-dd_HH:mm:ss.SSS} %5p [%t] [%c{1}]:%L - %m%n
</pattern>
</encoder>
</appender>
<appender name="logfile"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<Encoding>UTF-8</Encoding>
<encoder>
<pattern>%d %p [%t] [%c]:%L - %m%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>log/%d{yyyy-MM-dd-HH'.log'}</fileNamePattern>
</rollingPolicy>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.remoting" level="WARN" />
<logger name="org.springframework.scheduling.quartz" level="WARN" />
<logger name="org.springframework.data.jpa" level="DEBUG" />
<logger name="org.cometd" level="WARN" />
<logger name="ch.qos.logback" level="WARN" />
<logger name="com.springapp.mvc" level="DEBUG" />
<!-- 指定到mapper包 -->
<logger name="com.hui.mapper" level="DEBUG"></logger>
<root level="ERROR">
<appender-ref ref="stdout" />
<appender-ref ref="logfile" />
</root>
</configuration>
配置applicationContext.xml 里面的bean
<?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: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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--基于注解的形式 管理 bean-->
<!--扫描 com.hui下的全部组件-->
<context:component-scan base-package="com.hui"></context:component-scan>
<!--掌握 基于 AspectJ 的 注解 的 AOP实现 配置-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<!--配置文件参数化(参数占位符)-->
<context:property-placeholder location="classpath:db.properties" />
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!--Mysql 连接的 基本配置-->
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000"/>
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000"/>
</bean>
<!-- 工厂bean:生成SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--数据源属性-->
<property name="dataSource" ref="dataSource"></property>
<!--mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--扫描mapper 接口 自动创建mapper层代理对象 交给spring管理-->
<property name="basePackage" value="com.hui.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
</beans>
配置myBatis核心配置文件mybatis-config.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>
<typeAliases>
<!--自动扫描包,将原类名作为别名-->
<package name="com.hui.pojo" />
</typeAliases>
<mappers>
<!--扫描resources xml 映射文件-->
<package name="com.hui.mapper"/>
</mappers>
</configuration>
创建实体类对象User
/**
* @author 二手Java程序员
* @since 2023/4/23 19:25
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private String password;
private String sex;
private Date birthday;
private Date registTime;
}
创建LoginServlet响应前端的数据
/**
* @author 二手Java程序员
* @since 2023/4/23 19:29
*/
@WebServlet("/login") // 注解指定服务访问地址
public class LoginServlet extends HttpServlet {
private UserService userService;
@Override
public void init() throws ServletException {
//但是 这里 我们又想拿到 spring管理的bean 所以 采用下面这种方式
WebApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
userService = applicationContext.getBean("userService", UserService.class);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username);
System.out.println(password);
User user = new User();
user.setName(username);
user.setPassword(password);
System.out.println(user);
User result = userService.login(user);
System.out.println(result);
}
}
创建UserService 接口
/**
* @author 二手Java程序员
* @since 2023/4/23 19:27
*/
public interface UserService {
User login(User user);
}
创建UserMapper接口
/**
* @author 二手Java程序员
* @since 2023/4/23 19:30
*/
public interface UserMapper {
User login(User user);
}
创建UserServiceImpl 接口实现类
/**
* @author 二手Java程序员
* @since 2023/4/23 19:28
*/
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User login(User user) {
System.out.println("UserServiceImpl"+ user);
return userMapper.login(user);
}
}
按照这样的方式进行拼接信息
输入后会查询数据库,把查询结果返回控制台
注意:文章来源:https://www.toymoban.com/news/detail-432142.html
主要的思路而不是代码的实现,思路重要!思路!思路!思路!文章来源地址https://www.toymoban.com/news/detail-432142.html
到了这里,关于基于Spring注解 + MyBatis + Servlet 实现数据库交换的小小Demo的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!