restful风格服务的发布
步骤
1 在接口中编写抽象方法以及在的实现类中配置相应的实现方法(rest的方法),示例代码如下:
@Override
@Produces("application/json")//返回值类型
@Consumes("application/x-www-form-urlencoded")//表单提交类型
@Path("rest_ping")//http访问的路径
@GET
public String rest_ping(@BeanParam T_MALL_USER_ACCOUNT user) {//如果传入参数是对象类型的需要在参数类型前加@BeanParam注解
//注意此处的参数应该是从数据库中获取,为了简便就自己创建一个对象作为参数
T_MALL_USER_ACCOUNT u = new T_MALL_USER_ACCOUNT();
u.setYh_mch("qq");
u.setYh_nch("com");
u.setYh_mm("123");
Gson gson = new Gson();
return gson.toJson(u);
}
2 配置rest的风格的参数(在参数对应的类加上相应的注解),示例代码如下:
@XmlRootElement
public class T_MALL_USER_ACCOUNT {
@FormParam("id")
private int id;//编号
@FormParam("yh_mch")
private String yh_mch;//用户名称
@FormParam("yh_nch")
private String yh_nch;//用户昵称
@FormParam("yh_mm")
private String yh_mm;//用户密码
@FormParam("yh_xm")
private String yh_xm;//用户姓名
@FormParam("yh_shjh")
private String yh_shjh;//手机号
@FormParam("yh_yx")
private String yh_yx;//邮箱
@FormParam("yh_tx")
private String yh_tx;//头像
3 发布restful的ws服务端点
①在服务端的pox.xml文件中添加rest的依赖
<!-- 4.rest -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>3.0.5</version>
</dependency>
②spring配置文件的<beans>标签中加入
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
在xsi:schemaLocation=后面添加
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd
③在XML Catalog中配置相应的约束
④spring配置文件中发布restful风格的服务端点:
<!-- rest风格 -->
<jaxrs:server address="/rest_server">
<jaxrs:serviceBeans>
<bean class="com.service.TestServiceImpl"></bean>
</jaxrs:serviceBeans>
</jaxrs:server>
4.测试restful风格的服务接口是否发布成功
①在浏览器端地址栏输入服务端的项目根路径例如:
http://localhost:8080/mall_0417_user_student/
会出下方的页面:
找到restful风格哪个粘贴他的链接:
http://localhost:8080/mall_0417_user_student/rest_server?_wadl
然后修改为:(注意:rest_ping是你接口中的方法,“?yh_mch=123”相当于传入一个参数,yh_mch是你user类中的一个属性)
http://localhost:8080/mall_0417_user_student/rest_server/rest_ping?yh_mch=123
回车,(建议用debug启动服务端的项目)此时可以看到user中已经有数据了,证明发布成功了。