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的方法.第二.继承 ...
随机推荐
- Nginx安装SSL安全证书
1. 在Nginx的安装目录下的config目录下创建cert目录,并且将下载的证书全部文件拷贝到cert目录中.如果申请证书时是自己创建的CSR文件,请将对应的私钥文件放到cert目录下并且命名为2 ...
- C++/C头文件 .h和 .c
在C语言家族程序中,头文件被大量使用.一般而言,每个C++/C程序通常由头文件(header files)和定义文件(definition files)组成.头文件作为一种包含功能函数.数据接口声明的 ...
- 打包python为可执行文件时报错R6034解决方案
R6034 指的是:”An application has made an attempt to load the C runtime library incorrectly. Please cont ...
- spark 写 hbase 数据库,遇到Will not attempt to authenticate using SASL (unknown error)
今日在windows上用spark写hbase的函数 saveAsHadoopDataset 写hbase数据库的时候,遇到Will not attempt to authenticate using ...
- 9) 依赖查询 & 镜像站
依赖查询 http://mvnrepository.com/ Maven仓库查询 http://search.maven.org 仓库 加上这两个,如果使用中央仓库 Eclipse 极有可能会卡死 & ...
- ScrollView嵌套listview ,滚动问题。设置listview不滚动
对于ListView内部的ListView,一般用来展示少量的列表数据. 内部的ListView的高度看起来是一个固定值且无法滑动,这个就比较蛋疼了.. 提供两种解决方案,方案的核心都是重新设置内部L ...
- 一个简单 Go Web MVC 框架实现思路
需要的知识点 为了防止你的心里不适,需要以下知识点: Go 基本知识 Go 反射的深入理解 使用过框架 Go Web 服务器搭建 package main import ( "fmt&quo ...
- Python 实现WC功能
GitHub仓库:https://github.com/15crmor/PAC 项目要求 基本要求 -c 统计文件字符数 (实现) -w 统计文件词数 (实现) -l 统计文件行数(实现) 扩展功能 ...
- 【WP8.1】系统控件的bug及修复方案
最近开发的时候,发现Windows Phone 8.1 Runtime中的两个控件的存在bug的情况,现总结出来,并给出解决方案. 1.Hub控件 Hub控件的顶部默认是可以拖动来切换HubSecti ...
- Mongodb 与 SQL 语句对照表
In addition to the charts that follow, you might want to consider the Frequently Asked Questions sec ...