标签:spring springmvc mybatis ssm 框架搭建
最近项目中用到了spring+mybatis框架,闲暇之余,自己就想搭一套SSM(spring+springMVC+mybatis)的框架,结果发现并没有自己想象的那么简单,看了网上的很多教程,最多的就是那个用maven搭建的SSM,起初自己也想用maven搭建,后来出现种种问题,就没用,直接用jar包,下次熟练了再用maven搭一个。废话不说,直接开始。
####################################
# Database ConnectivityProperties
####################################
driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://127.0.0.1\:3306/ssm?useUnicode\=true&characterEncoding\=UTF-8
username=root
password=123456
#\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
#\u5b9a\u4e49LOG\u8f93\u51fa\u7ea7\u522b
log4j.rootLogger=DEBUG,INFO,Console,File
#\u5b9a\u4e49\u65e5\u5fd7\u8f93\u51fa\u76ee\u7684\u5730\u4e3a\u63a7\u5236\u53f0
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#\u53ef\u4ee5\u7075\u6d3b\u5730\u6307\u5b9a\u65e5\u5fd7\u8f93\u51fa\u683c\u5f0f\uff0c\u4e0b\u9762\u4e00\u884c\u662f\u6307\u5b9a\u5177\u4f53\u7684\u683c\u5f0f
log4j.appender.Console.layout =org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH\:mm\:ss} \:%m%n
#\u6587\u4ef6\u5927\u5c0f\u5230\u8fbe\u6307\u5b9a\u5c3a\u5bf8\u7684\u65f6\u5019\u4ea7\u751f\u4e00\u4e2a\u65b0\u7684\u6587\u4ef6
log4j.appender.File = org.apache.log4j.RollingFileAppender
#\u6307\u5b9a\u8f93\u51fa\u76ee\u5f55
log4j.appender.File.File = logs/ssm.log
#\u5b9a\u4e49\u6587\u4ef6\u6700\u5927\u5927\u5c0f
log4j.appender.File.MaxFileSize= 10MB
# \u8f93\u51fa\u6240\u4ee5\u65e5\u5fd7\uff0c\u5982\u679c\u6362\u6210DEBUG\u8868\u793a\u8f93\u51faDEBUG\u4ee5\u4e0a\u7ea7\u522b\u65e5\u5fd7
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
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=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.logger.com.ibatis = DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource= DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner= DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate= DEBUG
log4j.logger.java.sql.ResultSet= INFO
log4j.logger.org.apache = INFO
log4j.logger.java.sql.Connection= DEBUG
log4j.logger.java.sql.Statement= DEBUG
这个文件就是用来完成spring和mybatis的整合的。这里面也没多少行配置,主要的就是 自动扫描,自动注入,配置数据库 。
<?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:annotation-config />
<!-- 自动扫描 -->
<context:component-scan base-package="com.ws"/>
<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!-- <propertyname="location" value="classpath:jdbc.properties" />-->
<property name="locations">
<list>
<value>classpath:log4j.properties</value>
<value>classpath:jdbc.properties</value>
</list>
</property>
</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>
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource"ref="dataSource" />
<property name="configLocation"value="classpath:sqlMapConfig.xml" />
<property name="typeAliasesPackage"value="com.ws.poi" />
<!-- mapper配置路径 -->
<!-- 自动扫描mapper.xml文件 -->
<!-- mapper配置路径 -->
<property name="mapperLocations">
<list>
<!-- 表示在com.ws.map包或以下所有目录中,以-mapper.xml结尾所有文件 -->
<value>classpath:com/ws/mapper/**/*.xml</value>
</list>
</property>
</bean>
<!-- 扫描Mapper中的抽象类 ,实例化之后会自动装配-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage"value="com.ws.mapper" />
<property name="markerInterface"value="com.ws.mapper.SqlMapper" />
</bean>
<!-- (事务管理)transaction manager, use JtaTransactionManager forglobal tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource"ref="dataSource" />
</bean>
</beans>
CREATE TABLE `user` (
`id` int NULL AUTO_INCREMENT ,
`name` varchar(30) NULL ,
`password` varchar(20) NULL ,
`age` int NULL ,
PRIMARY KEY (`id`)
)
;
package com.ws.poi.user;
import java.io.Serializable;
/**
*@descriptionTODO
*@time 2015-8-18 下午2:26:30
*@author weis
*@version 1.0
**/
public class User implements Serializable{
private static final long serialVersionUID = 704975107463848089L;
private Integer id;
private String name;
private String password;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
UserService:
package com.ws.service.user;
import java.util.List;
import com.ws.poi.user.User;
/**
*@description TODO
*@time 2015-8-18 下午2:29:02
*@author weis
*@version 1.0
**/
public interface UserService<T> {
publicUser getUserById(Integer id);
publicList<User> getUserList();
}
UserServiceImpl:
package com.ws.service.user.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.ws.dao.user.UserDao;
import com.ws.poi.user.User;
import com.ws.service.user.UserService;
/**
*@description TODO
*@time 2015-8-18 下午2:29:50
*@author weis
*@version 1.0
**/
@Service
public class UserServiceImpl<T extends User>implements UserService<T> {
@Resource
privateUserDao<User> dao;
publicUser getUserById(Integer id) {
//TODO Auto-generated method stub
returndao.getUserById(id);
}
publicList<User> getUserList() {
//TODO Auto-generated method stub
returndao.getUserList();
}
}
UserDao:
package com.ws.dao.user;
import java.util.List;
import com.ws.poi.user.User;
/**
*@description TODO
*@time 2015-8-18 下午2:31:15
*@author weis
*@version 1.0
**/
public interface UserDao<T> {
/**
*
* @Description:
* @param id
* @return
* @return User
* @author weis
* @date 2015-8-18下午2:31:33
*/
publicUser getUserById(Integer id);
publicList<User> getUserList();
}
UserDaoImpl:
package com.ws.dao.user.impl;
import java.util.List;
import javax.annotation.Resource;
importorg.springframework.stereotype.Repository;
import com.ws.dao.user.UserDao;
import com.ws.mapper.user.UserMapper;
import com.ws.poi.user.User;
/**
*@description TODO
*@time 2015-8-18 下午2:31:58
*@author weis
*@version 1.0
**/
@Repository
public class UserDaoImpl<T extendsUser> implements UserDao<T> {
@Resource
privateUserMapper<User> mapper;
publicUser getUserById(Integer id) {
//TODO Auto-generated method stub
returnmapper.getUserById(id);
}
publicList<User> getUserList() {
//TODO Auto-generated method stub
returnmapper.getUserList();
}
}
UserMapper:
package com.ws.mapper.user;
import java.util.List;
import com.ws.mapper.SqlMapper;
import com.ws.poi.user.User;
/**
*@description TODO
*@time 2015-8-18 下午2:33:46
*@author weis
*@version 1.0
**/
public interface UserMapper<T>extends SqlMapper{
/**
*
* @Description:
* @param id
* @return
* @return User
* @author weis
* @date 2015-8-18下午2:33:57
*/
publicUser getUserById(Integer id);
publicList<User> getUserList();
}
user-mapper.xml
<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTDMapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace和定义的Mapper接口对应,并实现其中的方法 -->
<mapper namespace="com.ws.mapper.user.UserMapper">
<resultMap id="UserResultMap" type="com.ws.poi.user.User" >
<result property="id"column="id"/>
<result property="name"column="name"/>
<result property="password"column="password"/>
<result property="age"column="age"/>
</resultMap>
<select id="getUserById" parameterType="int" resultType="User"resultMap="UserResultMap">
select * from user where id = #{id}
</select>
<select id="getUserList" resultMap="UserResultMap" resultType="User">
select * from user
</select>
</mapper>
package com.ws.mapper;
public interface SqlMapper{
}
<?xml version="1.0"encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTDConfig 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置设置 -->
<settings>
<!-- 配置全局性 cache 的 ( 开 / 关) default:true -->
<setting name="cacheEnabled"value="true"/>
<!-- 是否使用懒加载关联对象 同 hibernate中的延迟加载一样 default:true -->
<setting name="lazyLoadingEnabled"value="true"/>
<!-- [当对象使用延迟加载时属性的加载取决于能被引用到的那些延迟属性,否则,按需加载(需要的是时候才去加载)] -->
<setting name="aggressiveLazyLoading"value="true"/>
<!-- 是否允许单条sql返回多个数据集 (取决于驱动的兼容性) default:true -->
<setting name="multipleResultSetsEnabled"value="true"/>
<!-- 是否可以使用列的别名 (取决于驱动的兼容性) default:true-->
<setting name="useColumnLabel"value="true"/>
<!--允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。 default:false-->
<setting name="useGeneratedKeys"value="false"/>
<!--指定 MyBatis 如何自动映射数据基表的列 NONE:不隐射 PARTIAL:部分 FULL:全部-->
<setting name="autoMappingBehavior"value="PARTIAL"/>
<!-- 这是默认的执行类型
SIMPLE :简单
REUSE:执行器可能重复使用prepared statements 语句
BATCH:执行器可以重复执行语句和批量更新
-->
<setting name="defaultExecutorType"value="SIMPLE"/>
<!-- 设置驱动等待数据响应的超时数 默认没有设置-->
<setting name="defaultStatementTimeout"value="25000"/>
<!-- [是否启用行内嵌套语句 defaut:false]-->
<setting name="safeRowBoundsEnabled"value="false"/>
<!-- [是否启用 数据中 A_column 自动映射到 java类中驼峰命名的属性 default:fasle] -->
<setting name="mapUnderscoreToCamelCase"value="false"/>
<!-- 设置本地缓存范围 session:就会有数据的共享 statement:语句范围 (这样就不会有数据的共享 ) defalut:session -->
<setting name="localCacheScope"value="SESSION"/>
<!-- 设置但JDBC类型为空时,某些驱动程序要指定值,default:other -->
<setting name="jdbcTypeForNull"value="OTHER"/>
<!-- 设置触发延迟加载的方法 -->
<setting name="lazyLoadTriggerMethods"value="equals,clone,hashCode,toString"/>
</settings>
<!-- 别名 -->
<typeAliases>
<typeAlias type="com.ws.poi.user.User"alias="User" />
</typeAliases>
</configuration>
package com.junit.test;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
import com.ws.poi.user.User;
import com.ws.service.user.UserService;
/**
*@descriptionTODO
*@time 2015-8-18 下午2:42:51
*@author weis
*@version 1.0
**/
public class TestMybatis {
private static Logger logger = Logger.getLogger(TestMybatis.class);
private ApplicationContextac = null;
privateUserService<User> userService = null;
@SuppressWarnings("unchecked")
@Before
public void before() {
ac = newClassPathXmlApplicationContext("spring-mybatis.xml");
userService = ac.getBean(UserService.class);
}
@Test
public void test1() {
User user = userService.getUserById(1);
System.out.println(user.getName());
logger.info("值:"+user.getName());
}}
<?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">
<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="com.ws.controller" />
<!--避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter"/> <!--JSON转换器 -->
</list>
</property>
</bean>
<!-- 定义跳转的文件的前后缀,视图模式配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个可用的url地址 -->
<property name="prefix"value="/WEB-INF/jsp/" />
<property name="suffix"value=".jsp" />
</bean>
<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="utf-8" />
<!-- 文件大小最大值 -->
<property name="maxUploadSize" value="10485760000" />
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="40960" />
</bean>
</beans>
<?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/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype CreatedWeb Application</display-name>
<!-- Spring和mybatis的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</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>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
package com.ws.controller.user;
import java.util.List;
import javax.annotation.Resource;
importjavax.servlet.http.HttpServletRequest;
importorg.springframework.stereotype.Controller;
import org.springframework.ui.Model;
importorg.springframework.web.bind.annotation.RequestMapping;
import com.ws.poi.user.User;
import com.ws.service.user.UserService;
/**
*@description TODO
*@time 2015-8-24 下午5:46:55
*@author weis
*@version 1.0
**/
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
privateUserService<User> service;
@RequestMapping("/showUser")
public String toIndex(HttpServletRequest request,Model model){
User user = this.service.getUserById(1);
model.addAttribute("user", user);
return "user";
}
@RequestMapping("/showUser1")
public String getUserList(HttpServletRequest request,Model model){
List<User> users = this.service.getUserList();
if(users.size()>0){
User user = users.get(0);
model.addAttribute("user",user);
}
return "user";
}
}
<%@ page language="java"import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path =request.getContextPath();
String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP ‘user.jsp‘ starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet"type="text/css" href="styles.css">
-->
</head>
<body>
${user.name}
</body>
</html>
至此简易项目环境搭建完成。
http://download.csdn.net/detail/weisong530624687/9046689
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:spring springmvc mybatis ssm 框架搭建
原文地址:http://blog.csdn.net/weisong530624687/article/details/47984993