1、新建一个Dynamic Web Project , 项目名ssm_1
2.对ssm3添加Gradle支持 , 右击项目—>Configure—>Add Gradle Nature
3.将Gradle文件复制到项目根目录.右击项目—>Gradle—>Refresh Gradle Project
4.在Java Resources 下添加 resources和src 目录 用于存放配置文件,在WEB-INF下建文件classes
目前为止,项目结构如图
整合spring-MVC
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
<!-- Spring和mybatis的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<!-- log4J配置文件 -->
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>classpath:log4.properties</param-value>
</context-param>
<!-- 设定刷新日志配置文件的时间间隔,这里设置为10s -->
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>10000</param-value>
</context-param>
<!-- 加载Spring框架中的log4j监听器Log4jConfigListener -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- 为避免项目间冲突,定义唯一的 webAppRootKey -->
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>spmvc</param-value>
</context-param>
<!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止Spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- Spring MVC servlet -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
在resources下新建类型为xml的文件,取名为spring-mvc.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="com.cheese.controller" />
<mvc:annotation-driven/>
<!-- 定义跳转的文件的前后缀,视图模式配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/views/" p:suffix=".jsp" >
<property name="order" value="1"/>
</bean>
</beans>
在resources下新建类型为file的文件,取名为log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file springmvc.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=${catalina.base}/logs/ssm.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug,stdout,file
5.
5.1 把 src 和 resources 添加到build path,右击项目,点properties、
Default output folder 设置成 ssm_1/WebContent/WEB-INF/classes
5.2.把src 、 resources 、 WebContent目录添加到 Deployment and Assembly
6.整合Spring-Mybatis
6.1.在resources下新建类型为file的文件,取名为jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/base1
username=btuser
password=t123
#\u5B9A\u4E49\u521D\u59CB\u8FDE\u63A5\u6570
initialSize=0
#\u5B9A\u4E49\u6700\u5927\u8FDE\u63A5\u6570
maxActive=20
#\u5B9A\u4E49\u6700\u5927\u7A7A\u95F2
maxIdle=20
#\u5B9A\u4E49\u6700\u5C0F\u7A7A\u95F2
minIdle=1
#\u5B9A\u4E49\u6700\u957F\u7B49\u5F85\u65F6\u95F4
maxWait=60000
这里我因为一个疏忽,花了我很久的时间去找错误,就是在每一行之前都不能留空格。
这里我因为一个疏忽,花了我很久的时间去找错误,就是在每一行之前都不能留空格。
在resources下新建类型为xml的文件,取名为spring-mybatis.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自动扫描 -->
<context:component-scan base-package="com.cheese" />
<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="${initialSize}"></property>
<!-- 连接池最大数量 -->
<property name="maxActive" value="${maxActive}"></property>
<!-- 连接池最大空闲 -->
<!-- <property name="maxIdle" value="${maxIdle}"></property>
--> <!-- 连接池最小空闲 -->
<property name="minIdle" value="${minIdle}"></property>
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="${maxWait}"></property>
</bean>
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:com/cheese/mapping/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.cheese.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
6.2.创建com.cheese.pojo包
创建user.java
package com.cheese.pojo;
public class User {
private int userId;
private String userName;
private String password;
private String name;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
6.3创建com.cheese.dao包
创建UserMapper接口
package com.cheese.dao;
import java.util.List;
import java.util.Map;
import com.cheese.pojo.User;
public interface UserMapper {
//插入操作
public int insert(Map<String, Object> map);
//更新操作
public int update(Map<String, Object> map);
//删除操作
public int delete(Map<String, Object> map);
//验证用户密码,并返回单个用户
public User getUser(User user);
//查询单个用户
public User getUserInfo(User user);
//查询多个用户
public List<User> getUserList();
}
6.4在resources文件夹下创建com.cheese.mapping包,在com.cheese.mapping文件夹下创建userMapper.xml
<?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.cheese.dao.UserMapper">
<!--
id:唯一标识一个statement
#{}:表示一个占位符,如果#{}中传入简单类型的参数,#{}中的名称随意
parameterType:输入参数的类型,通过#{}接收parameterType输入的参数
resultType:输出结果类型,不管返回是多条还是单条,指定单条记录映射的pojo类型
resultMap:输出结果类型
-->
<insert id="insert" parameterType="map">
insert into t_user(userid,username,password,name)
values(#{id},#{username},#{password},#{name})
</insert>
<update id="update" parameterType="map">
update t_user set username=#{userName},name=#{name},password=#{password} where userid=#{userId}
</update>
<delete id="delete" parameterType="map">
delete from t_user where userid=#{userId}
</delete>
<!--根据用户名称查询用户信息,可能返回多条 ${}:表示sql的拼接,通过${}接收参数,将参数的内容不加任何修饰拼接在sql中。-->
<select id="getUser" parameterType="com.cheese.pojo.User" resultType="com.cheese.pojo.User">
select u.username,u.name,u.password from t_user u where u.username=#{userName}
and u.password=#{password}
</select>
<select id="getUserInfo" parameterType="com.cheese.pojo.User" resultType="com.cheese.pojo.User">
select u.userid,u.username,u.name,u.password from t_user u where u.username=#{userName}
</select>
<select id="getUserList" resultType="com.cheese.pojo.User">
select userid,username,password,name from t_user
</select>
</mapper>
6.5在src文件夹下创建com.cheese.service包,在该包下创建UserService接口
package com.cheese.service;
import java.util.List;
import java.util.Map;
import com.cheese.pojo.User;
public interface UserService {
public void addUser(Map<String,Object> map);
public int updateUser(Map<String, Object> map);
public User getUser(User user);
public User getUserInfo(User user);
public List<User> getUserList();
}
6.6在src文件夹下创建com.cheese.service.impl包,在该包下创建UserService接口,Service接口的实现类放在该包下
在该包下新建UserServiceImpl.java
package com.cheese.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cheese.dao.UserMapper;
import com.cheese.pojo.User;
import com.cheese.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;//UserMapper 是接口
public void addUser(Map<String,Object> map) {
userMapper.insert(map);//调用接口的方法
}
public int updateUser(Map<String, Object> map) {
return userMapper.update(map);
}
public User getUser(User user) {
return this.userMapper.getUser(user);
}
public User getUserInfo(User user) {
return this.userMapper.getUserInfo(user);
}
public List<User> getUserList(){
return this.userMapper.getUserList();
}
}
7.测试 mybatis
TestMybatis执行前表中的记录
在src文件夹下创建com.cheese.test包,新建测试类Junit4Test.java、TestMybatis.java
Junit4Test.java
package com.cheese.test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
@RunWith(value = SpringJUnit4ClassRunner.class) // 测试运行器
@ContextConfiguration(locations = { "classpath:spring-mybatis.xml" }) // 加载配置文件
@TransactionConfiguration(transactionManager="transactionManager",defaultRollback=true)
public class Junit4Test{}
TestMybatis.java
package com.cheese.test;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import com.cheese.pojo.User;
import com.cheese.service.UserService;
public class TestMybatis extends Junit4Test{
@Autowired
private UserService userService;
@Test
@Transactional
@Rollback(false)//防止事务自动回滚
public void test() {
testUser();
}
private void testUser() {
//add
Map<String,Object> map = new HashMap<String,Object>();
map.put("username", "jerry");
map.put("password", "sl311");
map.put("name", "Jerry bruce");
userService.addUser(map);
User user = new User();
user.setUserName("jerry");//userName, password 作为查询条件
user.setPassword("sl311");
user = this.userService.getUser(user);
System.out.println(user.getName());
}
}
项目结构
在 TestMybatis.java 中 右键 -> run as -> Junit Test
执行后的代码