一、创建Java Web Application项目
1、在Web Application项目下创建一个module,自定义名字,在module——src——web——WEB-INF目录下创建lib文件夹,将spring框架所需的jar包放入其中,再全部选中jar包进行添加。
2、在module的src目录下,创建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 http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
然后创建好model、dao、impl、service层之后,在xml文件中依次进行数据库连接、创建jdbcTemplate对象来自动注入dataSource、扫描注解、创建dao层对象、创建service对象共5个部分的创建,基本操作可仿照如下:
<!-- 1.提供数据库的连接 : dataSource源 目的是为了连接数据库 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/db_java1ssm?useSSL=true&characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean>
<!-- 2.创建jdbcTemplate对象来自动注入dataSource -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 3.扫描注解:扫面Spring包中的注解 -->
<context:component-scan base-package="com.spring" />
<!-- 4. 创建dao层对象 -->
<bean id="springDao" class="com.spring.dao.impl.SpringDaoImpl" />
<!-- 5.创建service层对象 -->
<bean id="springService" class="com.spring.service.impl.SpringServiceImpl" />
3、在impl中写增删改查的具体实现操作,接下来展示以下新增和修改的代码案例:
//应用AOP
@Autowired
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public boolean addSpring(Spring spring) {
boolean flag = false;
try {
String sql = "insert into tb_spring values(0,?,?,?)";
int update = jdbcTemplate.update(sql, spring.getName(), spring.getSex(),spring.getAge());
if (update > 0) {
flag = true;
}else {
flag = false;
}
}catch (Exception e){
e.printStackTrace();
flag = false;
}
return flag;
}
@Override
public boolean updSpring(Spring spring) {
try {
String sql = "update tb_spring set name=?, sex=?, age=? where id=?";
int update = jdbcTemplate.update(sql, spring.getName(), spring.getSex(),spring.getAge(),spring.getId());
if (update > 0) {
return true;
}else {
return false;
}
}catch (Exception e) {
e.printStackTrace();
return false;
}
}
类似于这种,字段名都可以在数据库里自行设置的,可以从以上的代码中看出数据库的连接操作不需要在每一个方法中书写,spring框架已经把数据库连接的方法写好,直接通过模板调用,节省了代码量和时间,也使代码看起来整洁明了很多