Spring+CXF+IBatis 상세 소개 및 다운로드
29734 단어 spring
1.먼저 동적 WEB 프로젝트 를 준비 합 니 다.저 는 그 를 tnserver 라 고 지 었 습 니 다.저 는 먼저 Spring 과 IBatis 의 통합 을 완성 하고 마지막 으로 CXF 를 통합 시 키 며 자원 의 CURD 작업 을 완성 하려 고 합 니 다.
2.Spring 에 필요 한 jar 가방 을 준비 합 니 다.jar 는:
commons-beanutils-1.8.0.jar apache 공용 jarcommons-codec-1.4.jar apache 공용 jarcommons-collections-3.2.jar apache 공용 jarcommons-io-2.0.1.jar apache 공용 jarcommons-lang-2.4.jar apache 공용 jarcommons-lang 3-3.1.jar apache 공용 jarcommons-logging-1.1.1.jar apache 공용 jar6.상기 jar 가방 의 수집 을 완성 하 는 데 많은 시간 이 걸 립 니 다.저 는 앞으로 자원 을 공유 할 수 있 고 무료 로 편리 하 기 를 바 랍 니 다.만약 에 중국 소프트웨어 업계 의 발전 이 더욱 좋 을 것 이 라 고 믿 으 면(좋 은 공 유 는 우 리 를 성장 시 킬 수 있 습 니 다)첨부 파일 에서 저 는 Spring 을 제외 한 jar 다운 로드 를 제공 할 것 입 니 다.만약 당신 이 spring 의 jar 가 필요 하 다 면,spring 홈 페이지 에 가도 됩 니 다.
7.우선 설정
웹.xml,그 중에서 CXFServlet 는 CXF 를 위 한 설정 을 초기 화 합 니 다.(여기 서 모든 요청 을 CXF 에 맡 기 겠 습 니 다."/*")
<?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"
id="WebApp_ID" version="3.0">
<display-name>tnserver</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
8.다음 에 spring 의 프로필 을 만 듭 니 다.여 기 는 spring 의 프로필 을 두 부분 으로 나 누 었 습 니 다.접 두 사 는 모두 같 습 니 다(웹.xml 에서 applicationContext*.xml).각각 applicationContext-core.xml(데이터 원본 저장,주해 및 스 캔,Ibatis 설정,BaseDao 설정),applicationContext-server.xml 로 restful 서 비 스 를 발표 합 니 다.
9.applicationContext-core.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: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.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<!-- -->
<context:annotation-config/>
<!-- -->
<context:property-placeholder location="classpath:conf/jdbc.properties" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.userName}" />
<property name="password" value="${jdbc.password}" />
<property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}" />
<property name="checkoutTimeout" value="${jdbc.checkoutTimeout}" />
<property name="initialPoolSize" value="${jdbc.initialPoolSize}" />
<property name="minPoolSize" value="${jdbc.minPoolSize}" />
<property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
<property name="testConnectionOnCheckin" value="${c3p0.testConnectionOnCheckin}" />
<property name="testConnectionOnCheckout" value="${c3p0.testConnectionOnCheckout}" />
<property name="idleConnectionTestPeriod" value="${c3p0.idleConnectionTestPeriod}" />
<property name="automaticTestTable" value="${c3p0.automaticTestTable}" />
</bean>
<!-- ibatis2.x SqlMapClient-->
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:SqlMapConfig.xml"/>
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- annotation -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
<bean id="defaultBaseDao" class="cn.thinknet.database.ibatis.DefaultBaseDaoImpl">
<property name="sqlMapClient" ref="sqlMapClient" />
</bean>
<!-- -->
<context:component-scan base-package="cn.thinknet.common.service" />
<tx:annotation-driven/>
</beans>
10.applicationContext-server.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:cxf="http://cxf.apache.org/core"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<jaxrs:server id="healthRestful" address="/health">
<jaxrs:serviceBeans>
<ref bean="healthRestfulBean" />
</jaxrs:serviceBeans>
</jaxrs:server>
<bean id="healthRestfulBean" class="cn.tn.restful.third.health.HealthRestful"></bean>
11.spring 설정 은 여기까지 입 니 다.다음 에 저 는 주 해 를 사용 하여 주 입 했 습 니 다.이제 Ibatis 설정 SqlMapConfig.xml 를 만 듭 니 다.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<!-- <settings cacheModelsEnabled="true" enhancementEnabled="true"
lazyLoadingEnabled="true" maxRequests="32" maxSessions="10"
maxTransactions="5" useStatementNamespaces="false" /> -->
<!-- this put xxxx_sqlMap.xml files -->
sqlMap resource="conf/mappings/health_sqlMap.xml" />
</sqlMapConfig>
12.관심 이 있다 면 log4j 의 프로필 log4j.properties 를 계속 설정 할 수 있 습 니 다.
#-------------------------------- #log4j.rootLogger=DEBUG, stdout, fileout log4j.rootLogger=INFO, stdout, fileout #log4j.logger.test=info #log4j.logger.org.apache.jasper = DEBUG #log4j.logger.org.apache.catalina.startup.TldConfig = DEBUG #log4j.logger.org.apache.catalina.session.ManagerBase = DEBUG log4j.logger.com.fiscal = INFO log4j.logger.com.system = INFO log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.fileout=org.apache.log4j.RollingFileAppender log4j.appender.fileout.File=${catalina.home}/logs/tnserver.log log4j.appender.fileout.MaxFileSize=10000KB log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH\:mm\:ss} \:%m%n log4j.appender.fileout.layout=org.apache.log4j.PatternLayout log4j.appender.fileout.layout.ConversionPattern=[%-5p]_%d{yyyy-MM-dd HH\:mm\:ss} \:%m%n
13.이상 은 기본적으로 spring+ibatis+CXF RS 통합 을 완 성 했 습 니 다.다음은 인 스 턴 스 를 출력 하 겠 습 니 다.
14.자바 클래스 만 들 기:HealthRestful.java:
package cn.tn.restful.third.health;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.QueryParam;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import cn.thinknet.common.service.common.CommonService;
import cn.thinknet.common.service.third.health.HealthService;
import cn.thinknet.utils.exception.AKBaseException;
import cn.thinknet.utils.others.AKJsonValues;
/**
* ,
* @author ***
* @date 2014/05/21
*/
public class HealthRestful
{
@Autowired
private HealthService healthService;
@Autowired
private CommonService commonService;
/**
*
* @param data
* @return String
*/
@POST
public String saveHealthData(String data)
{
boolean flag = true;
try
{
JSONObject jo = JSONObject.fromObject(data);
String deviceId = jo.get("deviceId").toString();
// ID
flag = commonService.validateDeviceId(deviceId);
if (flag)
{
Object obj = jo.get("data");
Map<String,String> map = commonService.getUserAndCardRelation();
//
healthService.addHealth(deviceId, obj,map);
}
}
catch (AKBaseException akbe)
{
akbe.writeToLogger();
flag = false;
}
if (flag)
{
//
return AKJsonValues.getStatusSuccess().toString();
}
else
{
return AKJsonValues.getStatusFailed().toString();
}
}
/**
*
* @param userName
* @param examProject
* @param page
* @return json
*/
@GET
public String queryDoor(@QueryParam("userName")
String userName, @QueryParam("examProject")
String examProject, @QueryParam("page")
String page)
{
Boolean flag = true;
JSONArray ja = new JSONArray();
JSONObject jo = new JSONObject();
try
{
int pageIndex = NumberUtils.toInt(page);
//
ja = healthService.queryHealth(userName, examProject, pageIndex);
}
catch (AKBaseException akbe)
{
akbe.writeToLogger();
flag = false;
}
if (flag)
{
//
jo.put(AKJsonValues.STATUS_KEY, AKJsonValues.STATUS_SUCCESS);
jo.put("list", ja);
}
else
{
//
jo.put(AKJsonValues.STATUS_KEY, AKJsonValues.STATUS_FAILED);
jo.put("list", "");
}
return jo.toString();
}
}
15.service 계층 코드 HealthService.java:
package cn.thinknet.common.service.third.health;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.thinknet.database.ibatis.BatisBaseDao;
import cn.thinknet.utils.date.AKDateUtil;
import cn.thinknet.utils.exception.AKBaseException;
import cn.thinknet.utils.others.AKPagination;
import cn.thinknet.utils.vo.third.health.HealthVo;
/**
*
*
* @date 2014/05/21
*
* @author ****
*/
@Service("healthService")
public class HealthService
{
@Autowired
private BatisBaseDao baseDao;
/**
*
*
* @param deviceId
* @param data
* @throws AKBaseException
*/
public void addHealth(String deviceId, Object data, Map<String, String> map)
throws AKBaseException
{
if (MapUtils.isNotEmpty(map))
{
return;
}
try
{
// Json
JSONArray ja = JSONArray.fromObject(data);
JSONObject jo = null;
HealthVo hv = null;
for (Object obj : ja)
{
// JSON
jo = JSONObject.fromObject(obj);
hv = new HealthVo();
hv.setCardNo(jo.getString("cardNo"));
//
hv.setUserName(map.get(jo.getString("cardNo")));
hv.setDeviceId(deviceId);
hv.setExamProject(jo.getString("examProject"));
hv.setExamValue(jo.getString("examValue"));
hv.setExamUnit(jo.getString("examUnit"));
hv.setExamStatus(jo.getInt("examStatus"));
hv.setExamTime(AKDateUtil.stringConvertDate(
jo.getString("examTime"), AKDateUtil.DATEFORMAT002));
//
baseDao.add("third_health_insert", hv);
}
}
catch (AKBaseException ake)
{
throw new AKBaseException(ake);
}
}
/**
*
*
* @param userName
* @param examProject
* @param
* @return JSONArray
* @throws AKBaseException
*/
@SuppressWarnings("unchecked")
public JSONArray queryHealth(String userName, String examProject,
int pageIndex) throws AKBaseException
{
List<HealthVo> hList = null;
JSONObject jo = null;
JSONArray ja = new JSONArray();
try
{
Map<String, Object> params = new HashMap<String, Object>();
pageIndex = pageIndex == 0 ? 1 : pageIndex;
params.put(AKPagination.MYSQL_PAGE_ROW_NUMBER_KEY, (pageIndex - 1)
* AKPagination.MYSQL_PAGE_SIZE_KEY);
params.put(AKPagination.MYSQL_PAGE_ROW_SIZE_KEY,
AKPagination.MYSQL_PAGE_SIZE_KEY);
params.put("userName", userName);
params.put("examProject", examProject);
hList = (List<HealthVo>) baseDao.queryPagination(
"third_health_select", params);
// JSON
if (CollectionUtils.isNotEmpty(hList))
{
for (HealthVo hv : hList)
{
jo = new JSONObject();
jo.put("cardNo", hv.getCardNo());
jo.put("examProject", hv.getExamProject());
jo.put("examValue", hv.getExamValue());
jo.put("examUnit", hv.getExamUnit());
jo.put("examStatus", hv.getExamStatus());
jo.put("examTime",
AKDateUtil.dateConvetStringByFormat(
hv.getExamTime(), AKDateUtil.DATEFORMAT002));
ja.add(jo);
}
}
}
catch (AKBaseException ake)
{
throw new AKBaseException(ake);
}
return ja;
}
}
16.데이터 에 접근 하 는 인터페이스 와 기본 구현 클래스,인터페이스 클래스 BatisBaseDao.java 를 보 여 줍 니 다.
package cn.thinknet.database.ibatis;
import java.io.Serializable;
import java.util.List;
import cn.thinknet.utils.exception.AKSQLException;
/**
*
*
* @author
*
* CreateTime 2013-03-10
*/
public interface BatisBaseDao extends Serializable
{
/**
*
*
* @param sqlId IBatis SQL Id
* @param obj
*
* @throws AKSQLException SQL
*/
void add(String sqlId, Object obj) throws AKSQLException;
/**
*
*
* @param sqlId IBatis SQL Id
* @param params
*
* @throws AKSQLException SQL
*/
void delete(String sqlId, Object params) throws AKSQLException;
/**
* ,
*
* @param sqlId IBatis SQL Id
* @param params
*
* @throws AKSQLException SQL
*
* @return List<Object>
*/
List<?> query(String sqlId, Object params) throws AKSQLException;
/**
* ,
*
* @param sqlId IBatis SQL Id
* @param params
*
* @throws AKSQLException SQL
*
* @return List<Object>
*/
List<?> queryPagination(String sqlId, Object params)
throws AKSQLException;
/**
* ,
*
* @param sqlId IBatis SQL Id
* @param params
*
* @throws AKSQLException SQL
*
* @return List<Object>
*/
int queryCount(String sqlId, Object params) throws AKSQLException;
/**
*
*
* @param sqlId IBatis SQL Id
* @param params
*
* @throws AKSQLException SQL
*
* @return List<Object>
*/
Object queryOneModel(String sqlId, Object params) throws AKSQLException;
/**
*
*
* @param sqlId IBatis SQL Id
* @param params
*
* @throws AKSQLException SQL
*
* @return List<Object>
*/
List<?> queryAll(String sqlId) throws AKSQLException;
/**
*
*
* @param sqlId IBatis SQL Id
* @param updateObj
*
* @throws AKSQLException SQL
*/
void update(String sqlId, Object updateObj) throws AKSQLException;
}
클래스 DefaultBaseDaoImpl.java 구현:
package cn.thinknet.database.ibatis;
import java.util.List;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import cn.thinknet.utils.exception.AKSQLException;
/**
*
*
* @author lishizeng
*
* CreateTime 2013-03-10
*/
public class DefaultBaseDaoImpl extends SqlMapClientDaoSupport implements BatisBaseDao
{
private static final long serialVersionUID = -2493529163246756507L;
/**
*
*
* @param sqlId IBatis SQL Id
* @param obj
*
* @throws AKSQLException SQL
*/
@Override
public void add(String sqlId, Object obj) throws AKSQLException
{
try
{
this.getSqlMapClientTemplate().insert(sqlId, obj);
}
catch (Exception sqle)
{
throw new AKSQLException(sqle.getMessage(), sqle.getCause());
}
}
/**
*
*
* @param sqlId IBatis SQL Id
* @param params
*
* @throws AKSQLException SQL
*/
@Override
public void delete(String sqlId, Object params) throws AKSQLException
{
try
{
this.getSqlMapClientTemplate().delete(sqlId, params);
}
catch (Exception sqle)
{
throw new AKSQLException(sqle.getMessage(), sqle.getCause());
}
}
/**
* ,
*
* @param sqlId IBatis SQL Id
* @param params
*
* @throws AKSQLException SQL
*
* @return List<Object>
*/
@Override
public List<?> query(String sqlId, Object params) throws AKSQLException
{
List<?> list = null;
try
{
list = this.getSqlMapClientTemplate().queryForList(sqlId,
params);
}
catch (Exception sqle)
{
throw new AKSQLException(sqle.getMessage(), sqle.getCause());
}
return list;
}
/**
*
*
* @param sqlId IBatis SQL Id
* @param params
*
* @throws AKSQLException SQL
*
* @return List<Object>
*/
@Override
public List<?> queryAll(String sqlId) throws AKSQLException
{
List<?> list = null;
try
{
list = this.getSqlMapClientTemplate().queryForList(sqlId);
}
catch (Exception sqle)
{
throw new AKSQLException(sqle.getMessage(), sqle.getCause());
}
return list;
}
/**
*
*
* @param sqlId IBatis SQL Id
* @param updateObj
*
* @throws AKSQLException SQL
*/
@Override
public void update(String sqlId, Object updateObj) throws AKSQLException
{
try
{
this.getSqlMapClientTemplate().update(sqlId, updateObj);
}
catch (Exception sqle)
{
throw new AKSQLException(sqle.getMessage(), sqle.getCause());
}
}
/**
* ,
*
* @param sqlId IBatis SQL Id
* @param params
*
* @throws AKSQLException SQL
*
* @return List<Object>
*/
@Override
public List<?> queryPagination(String sqlId, Object params)
throws AKSQLException
{
List<?> list = null;
try
{
list = this.getSqlMapClientTemplate().queryForList(sqlId,
params);
}
catch (Exception sqle)
{
throw new AKSQLException(sqle.getMessage(), sqle.getCause());
}
return list;
}
/**
* ,
*
* @param sqlId IBatis SQL Id
* @param params
*
* @throws AKSQLException SQL
*
* @return List<Object>
*/
@Override
public int queryCount(String sqlId, Object params) throws AKSQLException
{
int count = 0;
try
{
count = Integer.valueOf(this.getSqlMapClientTemplate()
.queryForObject(sqlId, params).toString());
}
catch (NumberFormatException e)
{
count = 0;
}
catch (Exception e)
{
throw new AKSQLException(e.getMessage(), e.getCause());
}
return count;
}
/**
*
*
* @param sqlId IBatis SQL Id
* @param params
*
* @throws AKSQLException SQL
*
* @return List<Object>
*/
@Override
public Object queryOneModel(String sqlId, Object params)
throws AKSQLException
{
try
{
return this.getSqlMapClientTemplate().queryForObject(sqlId,
params);
}
catch (Exception e)
{
throw new AKSQLException(e.getMessage(), e.getCause());
}
}
}
20.어떤 jar 가방 이나 어디 에 모 르 는 것 이 있 으 면 메 일 로 보 내 주세요[email protected],나 는 가능 한 한 너 를 도 울 것 이다.)
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
thymeleaf로 HTML 페이지를 동적으로 만듭니다 (spring + gradle)지난번에는 에서 화면에 HTML을 표시했습니다. 이번에는 화면을 동적으로 움직여보고 싶기 때문에 입력한 문자를 화면에 표시시키고 싶습니다. 초보자의 비망록이므로 이상한 점 등 있으면 지적 받을 수 있으면 기쁩니다! ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.