ssm框架搭建及验证

上面配置完了maven,接下来完善各层的配置,首先先建立数据库信息存放的文件和mybatis的配置文件(文件名为mybatis-config.xml)

里面的内容是:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/library?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
<?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>
		<!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->
		<setting name="useGeneratedKeys" value="true" />

		<!-- 使用列标签替换列别名 默认:true,查询时可以用别名替代标签 -->
		<setting name="useColumnLabel" value="true" />

		<!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
		<setting name="mapUnderscoreToCamelCase" value="true" />
	</settings>
	
	
</configuration>

然后开始编写dao、service、web的相关配置文件:

spring-dao.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:context="http://www.springframework.org/schema/context"
	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.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 整合mybatis过程 -->
<!-- 1.配置数据库相关参数属性:${url} -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 2.数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 配置连接池属性 -->
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<!-- c3p0的连接池私有属性 -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"></property>
<!-- 关闭连接不自动提交 -->
<property name="autoCommitOnClose" value="false"></property>
<!-- 链接超时时间 -->
<property name="checkoutTimeout" value="10000"></property>
<!-- 失败重试次数 -->
<property name="acquireRetryAttempts" value="2"></property>
</bean>
<!-- 3.配置SqlSessionFactory对象(产生sql会话即sqlsession(可以进行增删改查)的工厂,线程安全),连接时需要连接池 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入 上面配置好的的dataSource-->
<property name="dataSource" ref="dataSource"></property>
<!-- mybatis的配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!-- 扫描entity包,使用别名,扫描这个实体类包和数据库对应起来 -->
<property name="typeAliasesPackage" value="com.gdut.library.entity"></property>
<!-- mapper文件的位置 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory,对应上面的id名 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- Dao接口包 -->
<property name="basePackage" value="com.gdut.libraray.dao"></property>
</bean>
</beans>

spring-service.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"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 扫描service包下所有使用注解的类型 -->
    <context:component-scan base-package="com.gdut.library.service" /> 
    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 配置基于注解的声明式事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

spring-web.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"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
	<!-- 配置SpringMVC -->
	<!-- 1.开启SpringMVC注解模式 -->
	<mvc:annotation-driven />
 
	<!-- 2.静态资源默认servlet配置 (1)加入对静态资源的处理(默认servlet处理):js,gif,png (2)允许使用"/"做整体映射 -->
	<mvc:resources mapping="/resources/**" location="/resources/" />
	<mvc:default-servlet-handler />
 
	<!-- 3.定义视图解析器 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/html/"></property>
		<property name="suffix" value=".html"></property>
	</bean>
	<!-- 文件上传解析器 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="utf-8"></property>
		<!-- 1024 * 1024 * 20 = 20M -->
		<property name="maxUploadSize" value="20971520"></property>
		<property name="maxInMemorySize" value="20971520"></property>
	</bean>
 
	<!-- 4.扫描web相关的bean -->
	<context:component-scan base-package="com.gdut.library.web" />
</beans>

然后我们要把spring配置整合,就需要在web.xml里面配置dispatchservlet

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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-*.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<!-- 默认匹配所有请求交由dispatcher处理 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

 

配置好之后,我们可以尝试编写一些方法来测试了,就拿area这个来测试吧,首先是dao层

 

我们对area进行增删改查的dao接口编写和mapper文件编写

接口:

package com.gdut.library.dao;

import java.util.List;

import com.gdut.library.entity.Area;

public interface AreaDao {
//列出区域
	List<Area> queryArea();
//增加区域
	int insertArea(Area area);
//删除区域
	int deleteArea(long areaId );
//更新区域
	int updateArea(Area area);
//批量删除区域
	int batchDeleteArea(List<Long> areaIdList);
	
	
	
}

mapper文件编写(放在resource下的mapper文件夹)

<?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.gdut.library.dao.AreaDao">
<select id="queryArea" resultType="Area">
select * from tb_area ORDER BY priority DESC
</select>
<insert id="insertArea" parameterType="Area" useGeneratedKeys="true" keyProperty="areaId" keyColumn="area_id">
insert into tb_area (area_name,create_date,priority,last_edit_time,area_desc) values 
(#{areaName},#{createDate},#{priority},#{lastEditTime},#{areaDesc})
</insert>
<update id="updateArea" parameterType="Area">
		update tb_area
		<set>
			<if test="areaName != null">area_name=#{areaName},</if>
			<if test="areaDesc != null">area_desc=#{areaDesc},</if>
			<if test="priority != null">priority=#{priority},</if>
			<if test="lastEditTime != null">last_edit_time=#{lastEditTime}</if>
		</set>
		where area_id=#{areaId}
</update>
	<delete id="deleteArea">
		DELETE FROM
		tb_area
		WHERE
		area_id =
		#{areaId}
	</delete>
<delete id="batchDeleteArea" parameterType="long">
		DELETE FROM
		tb_area
		WHERE area_id IN
		<foreach collection="list" item="areaId" open="(" separator=","
			close=")">
			#{areaId}
		</foreach>
</delete>
</mapper>

我们先编写一个test父类

package com.gdut.library;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/spring-dao.xml","classpath:spring/spring-service.xml"})
public class BaseTest {

}

第一个注解表示该测试类用spring整合junit4的运行配置,第二个是运行时所用的配置文件所在位置,

然后我们编写一个areaDao来验证是否可行

package com.gdut.library.dao;

import static org.junit.Assert.assertEquals;

import java.util.List;

import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.gdut.library.BaseTest;
import com.gdut.library.entity.Area;

public class AreaDaoTest extends BaseTest {
@Autowired
private AreaDao areaDao;

@Test
@Ignore
public void testInsertandUpdateArea() {
	Area area=new Area();
	area.setAreaDesc("测试区域1");
	area.setAreaName("一楼");
	area.setPriority(10);
	assertEquals(1, areaDao.insertArea(area));
	Area area1=new Area();
	area1.setAreaDesc("测试区域2");
	area1.setAreaName("二楼");
	area1.setPriority(5);
	
	assertEquals(1, areaDao.insertArea(area1));
	Area update=new Area();
	update.setAreaId(area1.getAreaId());
	update.setAreaDesc("修改后的区域2");
	assertEquals(1, areaDao.updateArea(update));
	
}
@Test
public void testQueryArea() {
	assertEquals(2,areaDao.queryArea().size());
}



}

测试通过(如果测试不通过的话,估计是spirng和junit的版本不兼容,还有接口包的位置,并且检查mapper文件名是否接口名一致等等)。然后验证service层。

首先定义service层的接口及其方法,然后在service.impl层实现

package com.gdut.library.service;

import java.util.List;

import com.gdut.library.entity.Area;

public interface AreaService {

	List<Area> getAreaList();
	
}
package com.gdut.library.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gdut.library.dao.AreaDao;
import com.gdut.library.entity.Area;
import com.gdut.library.service.AreaService;

@Service
public class AreaServiceImpl implements AreaService {
@Autowired
private AreaDao areaDao;
	
	@Override
	public List<Area> getAreaList() {
		// TODO Auto-generated method stub
		return areaDao.queryArea();
	}

	
}

在测试层代码:

package com.gdut.library.service;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.gdut.library.BaseTest;

public class AreaServiceTest extends BaseTest {
@Autowired
private AreaService areaService;
	@Test
	public void testGetAreaList() {
		assertEquals(2, areaService.getAreaList().size());
	}
	
}

然后是controller验证,测试代码如下

package com.gdut.library.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gdut.library.entity.Area;
import com.gdut.library.service.AreaService;

@Controller
@RequestMapping("/materialmanager")
public class AreaController {
	@Autowired
	private AreaService areaService;
	@ResponseBody
	@RequestMapping("/listarea")
	private Map<String,Object> listArea(){
		Map<String,Object> modelMap=new HashMap<String,Object>();
		try {
			List<Area> areaList=areaService.getAreaList();
			modelMap.put("areaList", areaList);
			modelMap.put("success", true);
		}catch(Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.toString());
		}
		
		return modelMap;
		
	}

	
	
}

最后在启动tomcat,访问相应的路径,

有条件的话可以下载postman这样看结果会清晰一点。

自此,已完成ssm框架的验证,后续文章会一一推出

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值