项目完整结构图:
1.pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xqlee.dev.project.ssm</groupId>
<artifactId>demo-ssm</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>demo-ssm Maven Webapp</name>
<url>http://maven.apache.org</url>
<profiles>
<profile>
<id>jdk-1.8</id>
<!-- 另外一种激活方式 -->
<activation>
<activeByDefault>true</activeByDefault>
<jdk>1.8</jdk>
</activation>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
<com.fasterxml.jackson.jaxrs.version>2.4.1</com.fasterxml.jackson.jaxrs.version>
</properties>
</profile>
</profiles>
<!-- 属性版本 -->
<properties>
<junit.version>4.12</junit.version>
<spring.version>4.1.7.RELEASE</spring.version>
<mybatis.version>3.2.6</mybatis.version>
<org.slf4j.version>1.7.2</org.slf4j.version>
<mysql.driver.version>5.1.32</mysql.driver.version>
<com.fasterxml.jackson.jaxrs.version>2.4.1</com.fasterxml.jackson.jaxrs.version>
<commons-fileupload.version>1.3.1</commons-fileupload.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- 测试所需 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- spring core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- MySQL数据库驱动 导入 start -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.driver.version}</version>
</dependency>
<!-- MySQL数据库驱动 导入 end -->
<!-- 导入dbcp的jar包,数据库连接池 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<!-- el 标签库 -->
<!-- standard.jar -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<!-- /el 标签库 -->
<!-- 处理json -->
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-xml-provider</artifactId>
<version>${com.fasterxml.jackson.jaxrs.version}</version>
</dependency>
<!-- 文件上传下载 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<!-- slf4j 和 log4j合用的Maven配置 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
</dependencies>
<build>
<finalName>demo-ssm</finalName>
</build>
</project>
2.整合spring mybaties 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-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">
<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
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>
<!-- ========================================针对myBatis的配置项============================== -->
<!-- 配置sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 实例化sqlSessionFactory时需要使用上述配置好的数据源以及SQL映射文件 -->
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描me/gacl/mapping/目录下的所有SQL映射的xml文件, 省掉Configuration.xml里的手工配置 value="classpath:com/mapper/*.xml"指的是classpath(类路径)下com.mapping包中的所有xml文件
UserMapper.xml位于com.mapping包下,这样UserMapper.xml就可以被自动扫描 -->
<property name="mapperLocations"
value="classpath:com/xqlee/dev/project/ssm/mapping/*.xml" />
<!-- 加载mybatis.cfg.xml文件 -->
<property name="configLocation" value="classpath:mybatis.cfg.xml"></property>
</bean>
<!-- 配置扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描com.dao这个包以及它的子包下的所有映射接口类 -->
<property name="basePackage" value="com.xqlee.dev.project.ssm.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!-- ========================================分隔线========================================= -->
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
3.mybatis.cfg.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>
</configuration>
4.jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test
username=root
password=root
initialSize=0
maxActive=20
maxIdle=20
minIdle=1
maxWait=60000
5.log4j.properties
log4j.rootLogger=INFO,Console,File
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
log4j.appender.File = org.apache.log4j.RollingFileAppender
log4j.appender.File.File = logs/ssm.log
log4j.appender.File.MaxFileSize = 10MB
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
6.spring-context.xml,spring容器启动配置
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd ">
<context:annotation-config />
<import resource="classpath:spring-mybatis.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
7.spring-mvc.xml,springMVC配置类
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd ">
<!-- 自动扫描controller包下所有 -->
<context:component-scan base-package="com.xqlee.dev.project.ssm" />
<!-- 注解驱动 -->
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<!-- 资源管理不拦截 -->
<mvc:resources location="/resources/" mapping="/resources/**" />
<mvc:resources location="/upload/" mapping="/upload/**" />
<!-- 内部资源视图解析器 prefix + logicName + suffix /WEB-INF/jsps/ + index + .jsp -->
<bean id="internalResourceViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/pages/" />
<!-- 后缀 -->
<property name="suffix" value="" />
</bean>
<!-- 处理在controller中使用注解@ResponseBody标签返回JSON数据 Start -->
<!-- 注意[由于我在pom.xml引入的是2.4.1版本]:所以class=org.springframework.http.converter.json.MappingJackson2HttpMessageConverter -->
<!-- [如果pom.xml引入的是1.xx版本]class=org.springframework.http.converter.json.MappingJacksonHttpMessageConverter -->
<bean id="mappingJackson2HttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>text/json;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJackson2HttpMessageConverter" />
</list>
</property>
</bean>
<!-- JSON数据处理 End -->
<!-- 上传图片/文件需要配置 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="-1" /><!-- -1表示没有限制 -->
<property name="maxInMemorySize" value="4096" />
</bean>
</beans>
8.User.java
package com.xqlee.dev.project.ssm.pojo;
public class User {
private int id;
private String name;
private String password;
private int age;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password
* the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age
* the age to set
*/
public void setAge(int age) {
this.age = age;
}
}
9.UserMapper.java
package com.xqlee.dev.project.ssm.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.xqlee.dev.project.ssm.pojo.User;
public interface UserMapper {
User findById(@Param("id")int id);
List<User> findList(@Param("name")String name);
}
10.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.xqlee.dev.project.ssm.dao.UserMapper">
<resultMap id="BaseMap" type="com.xqlee.dev.project.ssm.pojo.User">
<id column="id" property="id" jdbcType="INTEGER" /><!-- 注意这里的jdbcType参考mybaties官方文档 -->
<result column="name" property="name" jdbcType="VARCHAR" />
</resultMap>
<!-- mapper代理开发方式,namespace的值必须是对应接口的全类名 -->
<select id="findById" parameterType="int"
resultType="com.xqlee.dev.project.ssm.pojo.User">
select * from t_user where id = #{id}
</select>
<select id="findList" resultMap="BaseMap" parameterType="java.util.Map">
select * from t_user u where 1=1
<if test="name != null"> and u.name like
CONCAT('%',#{name,jdbcType=VARCHAR},'%') </if>
</select>
</mapper>
11.UserService.java
package com.xqlee.dev.project.ssm.service;
import java.util.List;
import com.xqlee.dev.project.ssm.pojo.User;
public interface UserService {
User getById(int id);
List<User> findList(String name);
}
12.UserServiceImp.java
package com.xqlee.dev.project.ssm.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xqlee.dev.project.ssm.dao.UserMapper;
import com.xqlee.dev.project.ssm.pojo.User;
@Service("userService")
public class UserServiceImp implements UserService {
@Autowired
UserMapper userMapper;
@Override
public User getById(int id) {
return userMapper.findById(id);
}
@Override
public List<User> findList(String name) {
// TODO Auto-generated method stub
return userMapper.findList(name);
}
}
13.Test.java
package com.xqlee.dev.project.ssm;
import java.util.List;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.xqlee.dev.project.ssm.pojo.User;
import com.xqlee.dev.project.ssm.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring-context.xml" })
public class Test {
@Autowired
UserService userService;
@org.junit.Test
public void test1() {
User user = userService.getById(1);
System.out.println(user.getName());
List<User> users=userService.findList("");
for(User u:users){
System.out.println("name:"+u.getName()+" id:"+u.getId());
}
}
}
14.测试表以及测试数据
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
`password` varchar(255) NOT NULL,
`age` int(4) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*Data for the table `user_t` */
insert into `t_user`(`id`,`name`,`password`,`age`) values (1,'测试1','123456',24);
insert into `t_user`(`id`,`name`,`password`,`age`) values (2,'测试2','123456',25);
insert into `t_user`(`id`,`name`,`password`,`age`) values (3,'测试3','123456',26);
15.执行测试:
看到上图的结果,表示spring+mybaties已经完成整合,接下来将springMVC整合进来就OK了。
16.配置web.xml,整合上面的springMVC+spring+mybaties
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<!-- 字符集处理 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- spring 核心配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置缓存清除监听器,负责处理由 JavaBean Introspector 功能而引起的缓存泄露 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- springMVC配置 -->
<servlet>
<servlet-name>springMVCSerlet</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>
</servlet>
<servlet-mapping>
<servlet-name>springMVCSerlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 添加下面容器,防止同一个服务器部署多个项目web.root冲突 -->
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>springMVC4</param-value>
</context-param>
<!-- session timeout -->
<session-config>
<!-- 分钟 -->
<session-timeout>60</session-timeout>
</session-config>
<!-- log4j配置 -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>60000</param-value>
</context-param>
<!--添加监听 -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- /log4j配置 -->
<!-- welcome page -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- session copy -->
<distributable />
</web-app>
17.WEB-INF目录下创建pages目录,并且在里面创建一个hello.jsp
hello.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>hello</title>
</head>
<body>
Hello ,<B>${name }</B>
</body>
</html>
18.创建UserController.java
package com.xqlee.dev.project.ssm.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.xqlee.dev.project.ssm.pojo.User;
import com.xqlee.dev.project.ssm.service.UserService;
@Controller
public class UserController {
@Autowired
UserService userService;
@RequestMapping("/hello/{id}.html")
public String hello(@PathVariable(value="id") int id, Model model) {
User user = userService.getById(id);
model.addAttribute("name", user.getName());
return "hello.jsp";
}
}
上面内容创建完成后,将项目添加到tomcat或者其他容器中,启动项目
上图是tomcat的启动日志,圈出来的是我们在UserController写的一个访问类
下面在浏览器中输入地址:
说明:访问地址 /hello/1.html
1表示后台control中接受到的用户id的参数值。
之所以页面显示的测试1,是因为前面我们已经将测试数据导入数据库,id等于1的用户刚好名称叫测试1
至此SSM三大框架整合基础完成。
https://www.leftso.com/article/72.html