一直用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. REST,RESTful

    REST(Representational State Transfer)描述了一个架构样式的网络系统. RESTful架构,就是目前最流行的一种互联网软件架构.结构清晰.符合标准.易于理解.扩展方便 ...

  2. C程序员学bash shell容易掉坑的注意点(未完待续)

    shell解释器很娇气,有一点点不合乎规范的编码风格都会让脚本歇菜. 1. 空格该有还是该没有要看情况.该有的时候不能没有!该没有的时候不能有! 变量赋值的等号两边不能有空格. 2. 在shell中是 ...

  3. IE跨域访问问题

    可能出现的症状: 1.跨域无法登录. 2.同一页面请求同一域名SESSION无法获取.(SESSION_ID一直在变) 一般情况下在方法前加上以下代码: header("P3P: CP=CU ...

  4. CentOS添加用户及赋予sudo权限

    在CentOS下添加一个用户假设用户名:username 密码:userpwd 新建用户: adduser username 修改密码: passwd username 根据提示重复输入两遍userp ...

  5. Oracle EBS进化史

    https://blogs.oracle.com/ptian/entry/oracle_ebs%E8%BF%9B%E5%8C%96%E5%8F%B2 通过图表总结了下Oracle EBS的进化历史,回 ...

  6. 记一次troubleshooting(一):奇慢的脚本

    背景: 事情发生的时间是几年前,那时刚从windows server运维的部门调动过来,对linux和数据库还是处于一知半解的状态. 领导找过来说:前任遗留下来的问题你来调查一下,有个客户说他们的日次 ...

  7. 手Q兴趣号的价值在哪里

    拥有5.21亿月活跃用户,如果不做点什么东西出来,实在是浪费至极.如此庞大的用户量,如果能够将内容贡献出来,那将是恐怖的,QQ空间产品就是很好的佐证. QQ群让个体用户能够连接在一起,单个的用户关系链 ...

  8. HTTP协议中POST、GET、HEAD、PUT等请求方法以及一些常见错误

    (来源:http://www.tuicool.com/articles/Ermmmyn) HTTP请求方法: 常用方法: Get\Post\Head (1)Get方法. 取回请求URL标志的任何信息, ...

  9. WebAPI的一种单元测试方案

    大家是如何对webApi写测试的呢? 1.利用Fiddler直接做请求,观察response的内容. 2.利用Httpclient做请求,断言response的内容. 3.直接调用webApi的act ...

  10. 辛巴学院-Unity-剑英陪你零基础学c#系列(一)Hello World

    这不是草稿 辛巴学院:正大光明的不务正业.辛巴学院:攻城狮与荣耀石. 剑英陪你系列又来啦.剑英是一个有大爱的人,热爱每一个程序员,尤其是年轻漂亮的女程序.最近组织朋友们玩了一次即兴团体诗创作,无论怎么 ...