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的方法.第二.继承 ...
随机推荐
- [转载][翻译]Go的50坑:新Golang开发者要注意的陷阱、技巧和常见错误[2]
Golang作为一个略古怪而新的语言,有自己一套特色和哲学.从其他语言转来的开发者在刚接触到的时候往往大吃苦头,我也不例外.这篇文章很细致地介绍了Golang的一些常见坑点,读完全篇中枪好多次.故将其 ...
- UVaLive 2796 Concert Hall Scheduling (最小费用流)
题意:个著名的音乐厅因为财务状况恶化快要破产,你临危受命,试图通过管理的手段来拯救它,方法之一就是优化演出安排,既聪明的决定接受或拒绝哪些乐团的演出申请,使得音乐厅的收益最大化.该音乐厅有两个完全相同 ...
- MySQL之SQL语句零碎总结
一.MySQL中有个ifnull函数,跟Oracle的nvl类似,用法如下: select* from Ta t where ifnull(pro, 0) < 100; 解释:当pro是null ...
- jupyterlab notebook区别
https://juejin.im/entry/5b350e52f265da59bd5ed31e Windows 7(Windows 10)安装后anaconda 命令行jupyter lab 出现4 ...
- jmap的几个操作要慎用
JDK中带有了一堆的工具是可以用来查看运行状况,排查问题的,但对于这些工具还是要比较清楚执行后会发生什么,否则有可能会因为执行了一个命令就导致严重故障,重点讲下影响比较大的jmap. 最主要的危险操作 ...
- javascript 奇技淫巧45招
教程:http://chensd.com/2015-01/45-useful-javascript-tips-tricks-and-best-practices.html 1.上线前检查和压缩代码:用 ...
- Spring Boot 2 实践记录之 MySQL + MyBatis 配置
如果不需要连接池,那么只需要简单的在pom文件中,添加mysql依赖: <dependency> <groupId>mysql</groupId> <arti ...
- Cocos2d-三维拾取Ray-AABB碰撞检测算法【转】
1.三维拾取技术 在3D游戏中通常会有这样的需求,用户可以选取3D世界中的某些物体进行如拖拽等操作,这时便需要程序通过将二维屏幕上的点坐标转换为三维世界中的坐标,并进行比对,这个过程就需要用到三维拾取 ...
- Dalsa线扫相机SDK下载和安装
1.首先去官方网站下载SDK Support Downloads - Teledyne DALSA http://www.teledynedalsa.com/imaging/support/downl ...
- Unity Shader 阶段性反思与总结(一)
Unity Shader 阶段性反思与总结(一) 最近在写Shader的时候,总是感觉力不从心,感觉自己已经看了蛮久的书了,也有一定的积累了,但是一想写什么效果,完完全全就是脑袋一团空白.典型的例子就 ...