rest版的webservice

  为了学习app做打算 今天就自学了下webservice,rest应该是其中一种 还有种就是soap,目前就先举个rest的demo吧

 准备ws的jar和spring的jar,如何要连接数据的话就自行准备这边就不提供了

 下载jar:http://download.csdn.net/detail/taopeng_100/7827035

 下载好jar之后将其放入lib下就可以进行配置了

 创建个项目 名叫wsTest

  首先配置spring配置文件spring-source.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:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:jaxrs="http://cxf.apache.org/jaxrs"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
         http://www.springframework.org/schema/aop 
         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
         http://www.springframework.org/schema/jee
         http://www.springframework.org/schema/jee/spring-jee-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">
    <context:annotation-config />
    <context:component-scan base-package="com.tp.soft.web.*" />
    
    <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="restServiceContainer" address="/rest">
        <jaxrs:serviceBeans>
            <bean class="com.tp.soft.web.ws.impl.LoginServiceImpl" />
        </jaxrs:serviceBeans>
        <jaxrs:extensionMappings>
            <entry key="json" value="application/json" />
            <entry key="xml" value="application/xml" />
        </jaxrs:extensionMappings>
        <jaxrs:languageMappings>
            <entry key="en" value="en-gb"></entry>
        </jaxrs:languageMappings>
        <jaxrs:providers>
            <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
        </jaxrs:providers>
    </jaxrs:server>
</beans>

然后在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" 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_2_5.xsd"
    version="2.5">
    <display-name>webService</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-source.xml</param-value>
    </context-param>
    <servlet>
        <display-name>CXFServlet</display-name>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/ws/*</url-pattern>
    </servlet-mapping>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>

然后就是写接口了

package com.tp.soft.web.ws;

import java.util.Map;

import javax.jws.WebService;

@WebService
public interface LoginService {
    public abstract Map<String, Object> doLogin(String username, String password);
}

实现类做了个很简单的传入账号密码 返回一个账号密码对象的json代码:

package com.tp.soft.web.ws.impl;

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

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.tp.soft.web.common.entity.Result;
import com.tp.soft.web.entity.User;
import com.tp.soft.web.ws.LoginService;

@Path("/loginService")
public class LoginServiceImpl implements LoginService{

    @POST
    @Path(value="/login")
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, Object> doLogin(@FormParam(value="username") String username, @FormParam(value="password") String password) {
        Result result = new Result();
        if(username.equals("zs") && password.equals("123")){
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("user", user);
            result.setMap(map);
            return map;
        }
        return null;
    }

}

此时可以直接通过浏览器访问地址:http://xxx.xxx.xx.x:8081/wsTest/ws/rest/loginService/login?username="zs"&password="123" 特别注意这边访问的是通过get的 如果要能访问就要讲@POST改成@GET

 

服务器写好了,下面就来写客服端的代码,客户端主要就是获取user对象的json,代码如下:

package com.tp.soft.client;


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

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;


public class A {
    public static void main(String[] args) {
        String url = "http://122.226.178.54:8081/wsTest1/ws/rest/loginService/login";
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        NameValuePair[] data = {new NameValuePair("username", "zs"), new NameValuePair("password", "123")};
        method.setRequestBody(data);
        try {
            int statusCode = client.executeMethod(method);
            if(statusCode == 200){
                String strJson = method.getResponseBodyAsString();
                System.out.println(strJson);
                Gson gson = new GsonBuilder().create();
                Map<String, User> map = gson.fromJson(strJson, new TypeToken<Map<String, User>>(){}.getType());
                System.out.println(map.get("user").getUsername());
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

运行下就能看到结果了

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。