SpringMVC3.2+Spring3.2+Mybatis3.1(SSM~Demo)
SpringMVC+Spring+Mybatis 框架搭建
整个Demo的视图结构:
JAR:
下载地址:http://download.csdn.net/detail/li1669852599/8546059
首先,我是使用MyEclipse工具做的这个例子,整合了Sping 3 、Spring MVC 3 、MyBatis框架,演示数据库采用MySQL数据库。例子中主要操作包括对数据的添加(C)、查找(R)、更新(U)、删除(D)。我在这里采用的数据库连接池是来自阿里巴巴的Druid,至于Druid的强大之处,我在这里就不做过多的解释了,有兴趣的朋友们可以去网上谷歌或者百度一下哦!好了下面我就贴上这次这个演示例子的关键代码:
example目录下是一个基本案例:
BaseController.java
package com.talent.example.controller;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import com.talent.example.model.Base;
import com.talent.example.service.BaseService;
/**
* <p>Title:控制器Controller</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) VISEC 2015</p>
* <P>CreatTime: Mar 25 2015 </p>
* @author Dana丶Li
* @version 1.0
*/
@Controller
public class BaseController {
private BaseService baseService;
private static String pathHead="ViewCenter/TalentBaseExample/"; public BaseService getBaseService(){
return baseService;
}
@Autowired
public void setBaseService(BaseService baseService){
this.baseService = baseService;
} @SuppressWarnings("finally")
@RequestMapping("addInfo")
public String add(Base add,HttpServletRequest request){
try{
add.setId(UUID.randomUUID().toString());
//System.out.println(add.getId() + ":::::" + add.getTname() + ":::::" + add.getTpwd());
String str = baseService.addInfo(add);
//System.out.println(str);
request.setAttribute("InfoMessage", str);
} catch (Exception e){
e.printStackTrace();
//request.setAttribute("InfoMessage", "添加信息失败!具体异常信息:" + e.getMessage());
}finally{
return BaseController.pathHead+"result";
}
} @RequestMapping("getAll")
public String getBaseInfoAll(HttpServletRequest request){
try{
List<Base> list = baseService.getAll();
//System.out.println(list);
request.setAttribute("addLists", list);
return BaseController.pathHead+"listAll";
} catch (Exception e){
e.printStackTrace();
//request.setAttribute("InfoMessage", "信息载入失败!具体异常信息:" + e.getMessage());
return BaseController.pathHead+"result";
}
} @SuppressWarnings("finally")
@RequestMapping("del")
public String del(String tid,HttpServletRequest request){
try {
String str = baseService.delete(tid);
request.setAttribute("InfoMessage", str);
} catch (Exception e) {
e.printStackTrace();
//request.setAttribute("InfoMessage", "删除信息失败!具体异常信息:" + e.getMessage());
} finally{
return BaseController.pathHead+"result";
}
}
@RequestMapping("modify")
public String modify(String tid,HttpServletRequest request){
try {
Base add = baseService.findById(tid);
request.setAttribute("add", add);
return BaseController.pathHead+"modify";
} catch (Exception e){
e.printStackTrace();
//request.setAttribute("InfoMessage", "信息载入失败!具体异常信息:" + e.getMessage());
return BaseController.pathHead+"result";
}
} @SuppressWarnings("finally")
@RequestMapping("update")
public String update(Base add,HttpServletRequest request){
try {
String str = baseService.update(add);
request.setAttribute("InfoMessage", str);
} catch (Exception e) {
e.printStackTrace();
//request.setAttribute("InfoMessage", "更新信息失败!具体异常信息:" + e.getMessage());
} finally {
return BaseController.pathHead+"result";
}
} }
BaseMapper.java
package com.talent.example.dao;
import java.util.List;
import com.talent.example.model.Base;
/**
* <p>Title: DAO BaseMapper</p>
* <p>Description: Base接口</p>
* <p>Copyright: Copyright (c) VISEC 2015</p>
* <P>CreatTime: Mar 25 2015 </p>
* @author Dana丶Li
* @version 1.0
*/
public interface BaseMapper {
int deleteByPrimaryKey(String id); int insert(Base record); int insertSelective(Base record); Base selectByPrimaryKey(String id); int updateByPrimaryKeySelective(Base record); int updateByPrimaryKey(Base record); List<Base> getAll();
}
BaseMapper.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.talent.example.dao.BaseMapper">
<resultMap id="BaseResultMap" type="com.talent.example.model.Base">
<id column="id" property="id" jdbcType="VARCHAR" />
<result column="tname" property="tname" jdbcType="VARCHAR" />
<result column="tpwd" property="tpwd" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List">
id, tname, tpwd
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap"
parameterType="java.lang.String">
select
<include refid="Base_Column_List" />
from tadd
where id = #{id,jdbcType=VARCHAR}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.String">
delete from tadd
where id = #{id,jdbcType=VARCHAR}
</delete>
<insert id="insert" parameterType="com.talent.example.model.Base">
insert into tadd (id, tname,
tpwd
)
values (#{id,jdbcType=VARCHAR}, #{tname,jdbcType=VARCHAR},
#{tpwd,jdbcType=VARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="com.talent.example.model.Base">
insert into tadd
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="tname != null">
tname,
</if>
<if test="tpwd != null">
tpwd,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=VARCHAR},
</if>
<if test="tname != null">
#{tname,jdbcType=VARCHAR},
</if>
<if test="tpwd != null">
#{tpwd,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.talent.example.model.Base">
update tadd
<set>
<if test="tname != null">
tname = #{tname,jdbcType=VARCHAR},
</if>
<if test="tpwd != null">
tpwd = #{tpwd,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=VARCHAR}
</update>
<update id="updateByPrimaryKey" parameterType="com.talent.example.model.Base">
update tadd
set
tname = #{tname,jdbcType=VARCHAR},
tpwd = #{tpwd,jdbcType=VARCHAR}
where id = #{id,jdbcType=VARCHAR}
</update> <select id="getAll" resultMap="BaseResultMap">
SELECT * FROM tadd
</select>
</mapper>
Base.java
package com.talent.example.model;
/**
* <p>Title: MODEL Base</p>
* <p>Description: Base实体类</p>
* <p>Copyright: Copyright (c) VISEC 2015</p>
* <P>CreatTime: Mar 25 2015 </p>
* @author Dana丶Li
* @version 1.0
*/
public class Base{ private String id; private String tname; private String tpwd; public String getId(){
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname == null ? null : tname.trim();
} public String getTpwd() {
return tpwd;
} public void setTpwd(String tpwd) {
this.tpwd = tpwd == null ? null : tpwd.trim();
}
}
BaseServiceImpl.java
package com.talent.example.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.talent.example.dao.BaseMapper;
import com.talent.example.model.Base;
import com.talent.example.service.BaseService;
/**
* <p>Title: DAO BaseMapper</p>
* <p>Description: Base接口</p>
* <p>Copyright: Copyright (c) VISEC 2015</p>
* <P>CreatTime: Mar 25 2015 </p>
* @author Dana丶Li
* @version 1.0
*/
@Service("baseService")
public class BaseServiceImpl implements BaseService{ private BaseMapper baseMapper; public BaseMapper getBaseMapper(){
return baseMapper;
}
@Autowired
public void setBaseMapper(BaseMapper BaseMapper) {
this.baseMapper = BaseMapper;
} @Override
public String addInfo(Base BaseInfo) {
if (baseMapper.insertSelective(BaseInfo) == 1) {
return "添加成功";
}
return "添加失败";
}
@Override
public List<Base> getAll() {
return baseMapper.getAll();
}
@Override
public String delete(String id) {
if (baseMapper.deleteByPrimaryKey(id) == 1) {
return "删除成功";
}
return "删除失败";
}
@Override
public Base findById(String id) {
return baseMapper.selectByPrimaryKey(id);
}
@Override
public String update(Base BaseInfo) {
if (baseMapper.updateByPrimaryKeySelective(BaseInfo) == 1) {
return "更新成功";
}
return "更新失败";
} }
BaseService.java
package com.talent.example.service;
import java.util.List;
import com.talent.example.model.Base;
/**
* <p>Title: DAO BaseService</p>
* <p>Description: BaseService接口</p>
* <p>Copyright: Copyright (c) VISEC 2015</p>
* <P>CreatTime: Mar 25 2015 </p>
* @author Dana丶Li
* @version 1.0
*/
public interface BaseService { String addInfo(Base addInfo); List<Base> getAll(); String delete(String id); Base findById(String id); String update(Base addInfo);
}
接下来主要详述SpringMVC+Spring+Mybatis的配置文件
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
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></display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml;classpath:spring-mybatis.xml</param-value>
</context-param>
<filter>
<description>字符集过滤器</description>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<description>字符集编码</description>
<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>
<listener>
<description>spring监听器</description>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<servlet>
<description>spring mvc servlet</description>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>spring mvc 配置文件</description>
<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>springMvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>15</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>ViewCenter/TalentBaseExample/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
通过Web.xml加载SpringMVC+Spring+Mybatis的配置文件
首先是Spring.xml ,spring-mybatis.xml俩文件
Spring.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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!-- 引入属性文件 -->
<context:property-placeholder location="classpath:com/talent/base/config.properties" />
<!-- 自动扫描(自动注入) -->
<context:component-scan base-package="com.talent.example.service..*" />
</beans>
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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 配置数据源 -->
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" /> <!-- 初始化连接大小 -->
<property name="initialSize" value="0" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20" />
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="20" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000" /> <!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> --> <property name="validationQuery" value="${validationQuery}" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="1800" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true" /> <!-- 监控数据库 -->
<!-- <property name="filters" value="stat" /> -->
<property name="filters" value="mergeStat" />
</bean> <!-- MyBatis文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
<property name="mapperLocations" value="classpath:com/talent/example/mapping/*.xml" />
</bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.talent.example.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean> <!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> <!-- 注解方式配置事物 -->
<!-- <tx:annotation-driven transaction-manager="transactionManager" /> --> <!-- 拦截器方式配置事物 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="append*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="modify*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="repair" propagation="REQUIRED" />
<tx:method name="delAndRepair" propagation="REQUIRED" /> <tx:method name="get*" propagation="SUPPORTS" />
<tx:method name="find*" propagation="SUPPORTS" />
<tx:method name="load*" propagation="SUPPORTS" />
<tx:method name="search*" propagation="SUPPORTS" />
<tx:method name="datagrid*" propagation="SUPPORTS" /> <tx:method name="*" propagation="SUPPORTS" />
</tx:attributes>
</tx:advice> <aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* com.talent.example.service..*Impl.*(..))" />
<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
</aop:config> <!-- 配置Druid监控Spring JDBC -->
<bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
</bean>
<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
<property name="patterns">
<list>
<value>com.talent.example.service.*</value>
</list>
</property>
</bean> <aop:config>
<aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
</aop:config>
</beans>
其次呢是Spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" 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" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
<context:component-scan base-package="com.talent.example.controller" /> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" /> </beans>
以上就是几个关键位置的代码,我全部贴出来了。至于配置文件什么的,由于时间原因没有贴出。如果大家要是感兴趣的话,可以下载我的这个演示项目包,里面的东西都齐全着,导入到MyEclipse上面直接部署到服务器上面就可以运行。数据库就是里面的那个.sql文件。建个库然后将数据导入就是。哦,对了。导完数据后,记得别忘了到config.properties里面去把数据库的连接信息换成你自己哦!
SpringMVC3.2+Spring3.2+Mybatis3.1(SSM~Demo)的更多相关文章
- Maven整合Spring3.0+Mybatis3.2+Struts2.3+查找坐标+jar包依赖(五)
依赖传递 只添加了一个struts2-core依赖,发现项目中出现了很多jar,这种情况 叫 依赖传递
- Spring3 整合MyBatis3 配置多数据源 动态选择SqlSessionFactory
一.摘要 上两篇文章分别介绍了Spring3.3 整合 Hibernate3.MyBatis3.2 配置多数据源/动态切换数据源 方法 和 Spring3 整合Hibernate3.5 动态切换Ses ...
- Spring3.2+mybatis3.2+Struts2.3整合
1.Spring3.2不能用于JDK1.8,只能用于JDK1.7.JDK1.8用spring4.0. 2.导入的jar包 3.目录结构: 4.配置Spring 配置数据库信息: <?xml ve ...
- ssm demo,用户角色权限管理
SSM框架整合 Spring SpringMVC MyBatis 导包: 1, spring 2, MyBatis 3, mybatis-spring 4, fastjson 5, aspectwea ...
- Java学习之SpringBoot整合SSM Demo
背景:在Java Web中Spring家族有着很重要的地位,之前JAVA开发需要做很多的配置,一堆的配置文件和部署调试一直是JavaWeb开发中的一大诟病,但现在Spring推出了SpringBoot ...
- spring3.2+mybatis3.2+maven整合
用maven管理spring+mybatis的项目: 这里主要讲述的是maven中的pom.xml文件的配置,以及在maven构建过程中会碰到的几个问题(我用的是maven4.4的版本): 首先一步一 ...
- SSM demo :投票系统
框架: Spring SpringMVC MyBatis 题目: 投票系统 导包: 1, spring 2, MyBatis 3, mybatis-spring 4, fastjson 5, aspe ...
- Spring3.2+mybatis3.2+Struts2.3整合配置文件大全
0.配置文件目录 1.Spring配置 applicationContext-dao.xml <?xml version="1.0" encoding="UTF-8 ...
- Spring3 整合MyBatis3 配置多数据源 动态选择SqlSessionFactory(转)
1. Spring整合MyBatis切换SqlSessionFactory有两种方法,第一. 继承SqlSessionDaoSupport,重写获取SqlSessionFactory的方法.第二.继承 ...
随机推荐
- hdu-2955(01背包+逆向思维+审题)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2955 思路:注意p和m[i]是被抓的概率,不能直接用,要转换为逃跑的概率,然后将得到的钱视为背包体积再 ...
- win7-64bit下安装Scipy
一直用MAC写python,但京东给的本装的是win7系统,在安装scipy时各种报错,最后错误提示为: no lapack/blas resources found 开始一顿搜,爆栈给出的解决方案是 ...
- 进度条ProgressBar
在本节中,作者只写出了进度条的各种样式,包括圆形.条形,还有自定义的条形,我想如果能让条形进度条走满后再继续从零开始,于是我加入了一个条件语句.作者的代码中需要学习的是handler在主线程和子线程中 ...
- HDU 2504 又见GCD (最大公因数+暴力)
题意:是中文题. 析:a和c的最大公因数是b,也就是说,a和c除了b就没有公因数了.再说就是互质了. 所以先把a除以b,然后一个暴力n,满足gcd(a, n) =1,就结束,就是n倍的c. 代码如下: ...
- Java设计模式 -- 简单工厂模式(SimpleFactory)
一.什么是简单工厂模式 简单工厂模式属于类的创建型模式,又叫做静态工厂方法模式.通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类. 二.模式中包含的角色及其职责 1.工厂(C ...
- (连通图 模板题)迷宫城堡--hdu--1269
链接: http://acm.hdu.edu.cn/showproblem.php?pid=1269 http://acm.hust.edu.cn/vjudge/contest/view.action ...
- Codeforces777E. Hanoi Factory 2017-05-04 18:10 42人阅读 评论(0) 收藏
E. Hanoi Factory time limit per test 1 second memory limit per test 256 megabytes input standard inp ...
- hdu 4996 1~n排列LIS值为k个数
http://acm.hdu.edu.cn/showproblem.php?pid=4996 直接贴bc题解 按数字1-N的顺序依次枚举添加的数字,用2N的状态保存在那个min数组中的数字,每次新添加 ...
- 启用Nginx目录浏览功能的方法
location / { root /data/www/file //指定实际目录绝对路径: autoindex on; ...
- EasyUi 合并单元格占列显示
$("#TableContainer").datagrid({ url: '', method: "get&q ...