SSM环境搭建(接口编程方式)
一直用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框架整合成功!

浙公网安备 33010602011771号