spring 통합 rest 스타일 cxf

10169 단어 springCXFREST
1. 웹. xml 설정
	<!-- cxf -->
	<servlet>
		<servlet-name>cxf</servlet-name>
		<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
		<init-param>
			<param-name>config-location</param-name>
			<param-value>classpath:spring-cxf.xml</param-value>
		</init-param>
		<load-on-startup>2</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>cxf</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>
	<welcome-file-list>

2、spring-cxf.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:jaxws="http://cxf.apache.org/jaxws" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
	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-3.2.xsd
       http://cxf.apache.org/jaxws	http://cxf.apache.org/schemas/jaxws.xsd
	   http://cxf.apache.org/jaxrs	http://cxf.apache.org/schemas/jaxrs.xsd
	   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

	<import resource="classpath:META-INF/cxf/cxf.xml" />
	<context:component-scan base-package="com.wei.service" />
	<aop:aspectj-autoproxy proxy-target-class="true" />

	<jaxrs:server address="/wei">
		<jaxrs:serviceBeans>
			<ref bean="userFacadeImpl" />
		</jaxrs:serviceBeans>
		<jaxrs:providers>
			<bean class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider" />
<!-- 			<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/> -->
			<bean class="com.wei.service.facade.exception.InvokeFaultExceptionMapper" /> 
		</jaxrs:providers>
		<jaxrs:extensionMappings>
			<entry key="json" value="application/json" />
			<entry key="xml" value="application/xml" />
		</jaxrs:extensionMappings>
		<jaxrs:languageMappings>
			<entry key="en" value="en-gb" />
		</jaxrs:languageMappings>
	</jaxrs:server>
</beans>
< jaxs: server > 이 라벨 은 여러 개 를 맞 출 수 있 습 니 다.
3. 인터페이스 와 실현
package com.wei.service.facade;

import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.wei.dao.entity.User;
import com.wei.service.facade.vo.CommonResonse;
import com.wei.service.vo.UserVo;


@Path("/user")
public interface UserFacade {

	@POST
	@Path("/addUser")
	@Consumes({MediaType.APPLICATION_JSON})
	@Produces("application/json; charset=UTF-8")
	String  insert( UserVo user);
	@POST
	@Path("/listUser")
	@Consumes({MediaType.APPLICATION_JSON})
	@Produces("application/json; charset=UTF-8")
	CommonResonse<User>  select(@NotNull UserVo user) ;
}
package com.wei.service.facade.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wei.dao.entity.User;
import com.wei.service.UserService;
import com.wei.service.facade.UserFacade;
import com.wei.service.facade.vo.CommonResonse;
import com.wei.service.validate.AccessRequired;
import com.wei.service.validate.ValidateParamUtils;
import com.wei.service.vo.UserVo;

@Component(value="userFacadeImpl") 
public class UserFacadeImpl implements UserFacade {

	@Autowired
	UserService userService;
	@Override
	public String  insert(UserVo userVo) {
		List<String> errors = ValidateParamUtils.violation(userVo);
		if(errors.size() > 0){
			return StringUtils.join(errors, ", ");
		}
		userService.insert(userVo);
		return "OK";
	}
	@Override
	@AccessRequired
	public CommonResonse<User>  select(UserVo userVo) {
		CommonResonse<User> commonResonse = new CommonResonse<User>();
		List<String> errors = ValidateParamUtils.violation(userVo);
		if(errors.size() > 0){
			return new CommonResonse<User>();
		}
//		return userService.select(userVo);
//		      ,      
//		RowBounds rowbound =new RowBounds(1,5);
//		return userService.selectPageMapper(userVo, rowbound);
		User user =new User();
		BeanUtils.copyProperties(user, userVo);
		List<User> selectByName = userService.select(user);
		commonResonse.setResult(selectByName);
		return commonResonse;
	}
	public static void main(String[] args) {
		char[] cc={'1','2'};
		String.valueOf(cc);
	}
}

3. 노출 된 서비스 와 테스트 보기
package com.wei.dao;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.core.MediaType;

import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.jaxrs.ext.form.Form;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.wei.dao.entity.User;
import com.wei.service.vo.UserVo;

public class RestfulCXFTestCase {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	/**   URL */
	private static final String SERVICE_URL = "http://localhost:8080/wei-web/rest/wei/";
	/**     */
	private static final String SERVICE_USER_ADD = "user/addUser";
	private static final String SERVICE_USER_LIST = "user/listUser";
	private String APPLICATION_JSON="application/json";
	private WebClient client;
	/**   JSON */
	Object response = "";

	@Before
	public void initData() {
		client = WebClient.create(SERVICE_URL);
		client.accept(MediaType.APPLICATION_JSON);
		client.type(MediaType.APPLICATION_JSON);
		client.form(new Form());
		logger.info("---------->TestCase start<-------------");
	}
	@After
	public void endDo(){
		logger.info("response:" + response);
		logger.info("---------->TestCase End<-------------");
	}

	@Test
	public void testAllUser_GET() {

		client.path(SERVICE_USER_LIST);
		
		client.query("name", "hong");

		response = client.get(String.class);

	}

	@Test
	public void testaddUser_POST() {

		client.path(SERVICE_USER_ADD);
		
		Form f = new Form();
		f.set("name", "   ");
		f.set("password", "11223344");
		f.set("createDate", new Date());
//		User user=new User();
//		user.setName("weiwei");
//		f.set("user", user);
		
		response = client.post(f, String.class);
	}
	
	@Test
	public void testaddUser_JSON() {
		client.path(SERVICE_USER_ADD);
		Map<String,Object> user = new HashMap<String,Object>();
		user.put("name","xiaoxiao");
		user.put("password","323232");
		UserVo userv=new UserVo();
		userv.setName("xiaoName");
		userv.setPassword("87887");
//		httpJsonPost(SERVICE_URL+SERVICE_USER_ADD,user);
		httpJsonPost(SERVICE_URL+SERVICE_USER_ADD,userv);
	}
	
	private  void httpJsonPost(String serviceURL,Object requestBody){
		StringEntity entity = new StringEntity(JSON.toJSONString(requestBody), "UTF-8");
		HttpPost httpPost = new HttpPost(serviceURL);
		httpPost.addHeader(HTTP.CONTENT_TYPE, MediaType.APPLICATION_JSON);
		httpPost.setEntity(entity);
		try {
			CloseableHttpResponse resp = HttpClients.createDefault().execute(httpPost);
			response =EntityUtils.toString(resp.getEntity());
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

상자 보기 서비스 노출 성공 여 부 는 URL 뒤에 만 추가 하 시 겠 습 니까?wadl 을 사용 하면 브 라 우 저 에 접근 할 수 있 습 니 다.
4. 프레임 이상 캡 처
package com.wei.service.facade.exception;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import org.springframework.stereotype.Component;

@Component
@Provider
public class InvokeFaultExceptionMapper implements ExceptionMapper<Exception> {

	private static final String INVOCATION_TARGET_EXCEPTION = "java.lang.reflect.InvocationTargetException";

	/** (non-Javadoc)
	 * @see javax.ws.rs.ext.ExceptionMapper#toResponse(java.lang.Throwable)
	 */
	@Override
	public Response toResponse(Exception ex) {
		ResponseBuilder resp = Response.status(Response.Status.NOT_ACCEPTABLE);  
		if(INVOCATION_TARGET_EXCEPTION.equals(ex.getLocalizedMessage())){
			Map<String,String> m=new HashMap<String,String>();
			m.put("406", "      ");
			resp.entity(m); 
		}else {
			resp.entity(ex); 
		}
		resp.type("application/json;charset=UTF-8");  
		ex.printStackTrace();
		resp.language(Locale.SIMPLIFIED_CHINESE);  
		Response response = resp.build();  
		return response;

	}

}

매개 변 수 는 캡 처 의 이상 이 고 반환 값 은 클 라 이언 트 의 응답 입 니 다.

좋은 웹페이지 즐겨찾기