一直用ssm在开发项目,之前都是直接copy别人的项目,今天趁着项目刚刚交付,自己搭建一下ssm环境,做个记录

一、创建项目、引入jar包,因为版本不一样,就不贴出这部分的内容了。个人平时的习惯是,先将核心jar包引入,在测试是如果有需要添加的,在额外加入,一堆jar包也不太好记。

二、首先项目中配置spring

1、项目web.xml中配置

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 通过上下文参数指定spring配置文件的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

2、构建项目结构如下图(代码见下方):

2.1实体类User

public class User {
private int id;
private String name;
private int age;
//getters、setters
}

2.2   UserDao 对实体类的操作,其中的方法名称和Mapper中对应的id一样

public interface UserDao {

	public List<User> findAll();

	public User findById(int id);

	public void addUser(User u);

	public void deleteUser(int id);

	public void updateUser(User u);
}

2.3 UserMapper.xml,其中就是对应dao层的具体操作,包括其中的sql语句,类似与其中接口的实现,只不过这个实现是mybatis自己去实现的

<?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用于绑定Dao接口的,mybatis为映射文件定义了一个代理接口,以后全部通过这个接口来和映射文件交互,而不再是使用以前方法 -->
<mapper namespace="com.ssm.dao.UserDao">
<!-- 查找 -->
<select id="findAll" resultType="user">
select * from user
</select> <!-- 根据主键查找 -->
<select id="findById" parameterType="int" resultType="user">
select * from user where id = #{id}
</select> <!-- useGeneratedKeys="true" keyProperty="id" 用户获取添加后的主键 -->
<insert id="addUser" parameterType="user" useGeneratedKeys="true"
keyProperty="id">
insert into user values (#{id},#{name},#{age})
</insert> <!-- 删除 -->
<delete id="deleteUser" parameterType="int">
delete from user where id = #{id}
</delete> <!-- 修改 -->
<update id="updateUser" parameterType="user">
update user
set name = #{name},age= #{age}
where id = #{id}
</update>
</mapper>

2.4   userService,用户的业务操作,注意这里userDao接口,mybatis MapperScannerConfigurer生成代理注入到Spring(spring文件中),所以我们没有不需要为dao层添加注解@Repository进行注入

@Service
public class UserService { @Resource
private UserDao userDao; public List<User> findAll() {
return userDao.findAll();
} public User findById(int qid) {
return userDao.findById(qid);
} public void addUser(User u) {
userDao.addUser(u);
} public void deleteUser(int id) {
userDao.deleteUser(id);
} public void updateUser(User u) {
userDao.updateUser(u);
}
}

2.5    applicationContext.xml文件中,主要是sqlSessionFactory和事物的配置,里边有详细的配置注释,这里不再赘述

<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "> <!-- 注解驱动 -->
<mvc:annotation-driven />
<!-- 组件扫描 -->
<context:component-scan base-package="com.ssm"></context:component-scan> <!-- 定义数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm" />
<property name="user" value="root" />
<property name="password" value="root" />
<property name="initialPoolSize" value="10" />
<property name="maxPoolSize" value="50" />
<property name="minPoolSize" value="10" />
</bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath:com/ssm/mapper/*.xml"></property>
</bean> <!-- mybatis MapperScannerConfigurer 自动扫描 将Mapper接口生成代理注入到Spring -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssm.dao" /> <!--没有必要去指定SqlSessionFactory或SqlSessionTemplate, 因为MapperScannerConfigurer将会创建
MapperFactoryBean,之后自动装配。 但是,如果你使 用了一个以上的DataSource,那 么自动装配可能会失效。
这种情况下,你可以使用sqlSessionFactoryBeanName或sqlSessionTemplateBeanName
属性来设置正确的 bean名称来使用。 -->
<!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> -->
</bean> <!-- 事务管理器 -->
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean> <!-- 配置事物的传播特性 (事物通知) -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="find*" read-only="true" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice> <aop:config>
<aop:advisor pointcut="execution(* com.area.service.*.*(..))"
advice-ref="txAdvice" />
</aop:config>
</beans>

2.6  mybatis的配置文件,这个主要是对全局的配置进行一个设置

<?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>
<settings>
<setting name="cacheEnabled" value="true" />
</settings>
<typeAliases>
<typeAlias alias="user" type="com.ssm.pojo.User" />
</typeAliases> </configuration>

2.7   测试类:

public class TestSSM {

	private static ApplicationContext act;
private static SqlSessionFactory sqlSessionFactory;
private static SqlSession sqlSession; @BeforeClass
public static void before() throws IOException {
act = new ClassPathXmlApplicationContext("applicationContext.xml");
sqlSessionFactory = (SqlSessionFactory) act
.getBean("sqlSessionFactory");
sqlSession = sqlSessionFactory.openSession();
} @Test
public void testFindAll() {
UserService userService = (UserService) act.getBean("userService");
List<User> list = userService.findAll();
for (User u : list) {
System.out.println(u.toString());
} } @Test
public void testFindById() {
UserService userService = (UserService) act.getBean("userService");
User u = userService.findById(3);
System.out.println(u);
} @Test
public void testDeleteUser() {
UserService userService = (UserService) act.getBean("userService");
userService.deleteUser(3);;
} @Test
public void testAddUser() {
UserService userService = (UserService) act.getBean("userService");
User u = new User();
u.setName("123");
u.setAge(33);
userService.addUser(u);
} @Test
public void testUpdateUser() {
UserService userService = (UserService) act.getBean("userService");
User u = new User();
u.setName("123");
u.setAge(33);
u.setId(2);
userService.updateUser(u);
} @AfterClass
public static void after() throws IOException {
sqlSession.close();
} }

各个测试方法均测试通过,说明我们的spring + mybatis环境整合成功。

三、整合springmvc或者struts(这里介绍springmvc)

1、web.xml中配置springmvc

<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:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
<url-pattern>*.do</url-pattern>
</servlet-mapping>

2. springmvc.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-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.area.controller" />
<!--避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<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>

3.  编写controller层

@Controller
public class UserController {
@Resource
private UserService userService; @RequestMapping("/test")
public void test() {
List<User> list = userService.findAll();
for (User u : list) {
System.out.println(u);
}
} }

通过浏览器测试:

OK,一切正常!ssm框架整合成功!

SSM环境搭建(接口编程方式)的更多相关文章

  1. Java开发学习心得(一):SSM环境搭建

    目录 Java开发学习心得(一):SSM环境搭建 1 SSM框架 1.1 Spring Framework 1.2 Spring MVC Java开发学习心得(一):SSM环境搭建 有一点.NET的开 ...

  2. 黑马eesy_15 Vue:04.Vue案例(ssm环境搭建)

    黑马eesy_15 Vue:02.常用语法 黑马eesy_15 Vue:03.生命周期 黑马eesy_15 Vue:04.Vue案例(ssm环境搭建) 黑马eesy_15 Vue:04.综合案例(前端 ...

  3. 026 SSM综合练习02--数据后台管理系统--数据库表创建及SSM环境搭建

    1.数据库准备 本项目我们Oracle数据库,Oracle 为每个项目创建单独user,oracle数据表存放在表空间下,每个用户有独立表空间. (1)采用数据库管理员账号:SYSTEM,再配合数据库 ...

  4. 本人亲测-SSM环境搭建(使用eclipse作为示例,过程挺全的,可作为参考)

    本人亲测-SSM环境搭建(使用eclipse作为示例,过程挺全的,可作为参考) 本人亲测-SSM环境搭建(使用eclipse作为示例,过程挺全的,可作为参考) 本人亲测-SSM环境搭建(使用eclip ...

  5. 小程序开发之后台SSM环境搭建(一)

    1.新建web项目 打开eclipse,选择file-->New-->Dynamic web Project ,填写项目名字,一直点击next,勾选Generate web.xml dep ...

  6. SpringMVC 学习 十 SSM环境搭建(三)springMVC文件配置

    SpringMVC文件配置的详细过程,可以查看springMVC环境搭建的注解配置篇<springMVC学习三 注解开发环境搭建> <?xml version="1.0&q ...

  7. maven+eclipse+ssm 环境搭建和启动

    该类工程环境搭建和启动方法 ------------------------------------------------------------------------------- 配置 jdk ...

  8. 微信开发之SSM环境搭建

    首先,感谢大神的文章,地址:http://blog.csdn.net/zhshulin/article/details/37956105# 第一步:新建maven项目 如有需要,查看之前的文章:从配置 ...

  9. Maven + SSM环境搭建

    Maven + SSM 之前Maven+SSM都是照着搭建的,自己想写点什么的时候发现搭建的过程不清楚. 于是花了时间边整理思路边搭建,并把搭建过程记录下来. 视频看来终觉浅,还是需要自己动手实践,捋 ...

随机推荐

  1. 转 :meta name的含义:<META http-equiv=Content-Type content="text/html; charset=gb2312">

    meta是什么?meta其实是html语言head区的一个辅助性标签.在几乎所有的网页里,我们都可以看到类似下面这段html代码:<META http-equiv=Content-Type co ...

  2. linux 匹配字符串是否为数字

    #!/bin/bash ## 方法1 a=1234;echo "$a"|[ -n "`sed -n '/^[0-9][0-9]*$/p'`" ] &&a ...

  3. VS2013安装部署项目

    打开vs2013/2015菜单扩展和更新,查找Installer,找到Microsoft Visual Studio 2015 Installer Projects并下载安装. 安装之后模板中即有“安 ...

  4. css横向导航条

    css横向导航条有两种方法 1. ul li a li{float:left} #navlist li, #navlist a{height:44px;display:block;} a{width: ...

  5. 使用getopt()处理命令行参数

    假设有一程序 testopt,其命令行选项参数有: -i            选项 -l            选项 -r           选项 -n <值> 带关联值的选项 则处理 ...

  6. 【整理】--C++变量概述

    1.变量概述及特殊变量初始化 a.引用 b.常量 c.静态 d.静态常量(整型) e.静态常量(非整型) 初始化:常量和引用,必须通过参数列表进行初始化. 静态成员变量的初始化也颇有点特别,是在类外初 ...

  7. PPC MPC85xx e500学习笔记

    powerpc的内存体系结构 E500内核中包含内存管理单元MMU,其包含两个查找表(TLB0 Transaction Lookside Buffer)和TLB1来实现虚拟地址和物理地址的转化,其中T ...

  8. wordpress搬家换域名

    很多朋友开始接触wordpress都是在本地安装调试好了,再上传到服务器正常运营,我也是一样当我在本地测试好了准备将网站上线,在搬家到服务器的时候遇到过的一些问题,记录分享一下我是如何为wordpre ...

  9. smartroute简单集成集群聊天通讯

    在制定一个规模比较多大的聊天应用时,往往需要制定部署多个应用服务,其一可以保障服务的可靠性,其二可以增加用户负载量.但制定这样一种应用体系是一件复杂的事情,毕竟同一群体的用户实际上会在不同的服务器接入 ...

  10. 让.NET xml序列化支持Nullable

    .NET的序列化,关于契约类的生成我们都是通过xsd.exe,对于值类型的可空判断是通过声明同名+Specified的bool属性来判断,比如: public class Person { publi ...