spring 集成rest风格的cxf

来源:互联网 发布:渔趣网淘宝分店卖假货 编辑:程序博客网 时间:2024/05/18 03:13

1、配置web.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/jaxwshttp://cxf.apache.org/schemas/jaxws.xsd   http://cxf.apache.org/jaxrshttp://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>
<jaxrs: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 {@AutowiredUserService userService;@Overridepublic String  insert(UserVo userVo) {List<String> errors = ValidateParamUtils.violation(userVo);if(errors.size() > 0){return StringUtils.join(errors, ", ");}userService.insert(userVo);return "OK";}@Override@AccessRequiredpublic 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 = "";@Beforepublic 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<-------------");}@Afterpublic void endDo(){logger.info("response:" + response);logger.info("---------->TestCase End<-------------");}@Testpublic void testAllUser_GET() {client.path(SERVICE_USER_LIST);client.query("name", "hong");response = client.get(String.class);}@Testpublic 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);}@Testpublic 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@Providerpublic 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) */@Overridepublic 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;}}

参数是捕获的异常,返回值是客户端的响应




0 0
原创粉丝点击