Rest-based webservice and rest-based webservice

Source: Internet
Author: User

Rest-based webservice and rest-based webservice

To learn about the app, I learned webservice by myself today. rest should be one of the other types, namely soap. Now let's take a rest demo first.

Prepare ws jar and spring jar. If you want to connect the data, you have to prepare the data here.

Download jar: http://download.csdn.net/detail/taopeng_100/7827035

After downloading the jar file, put it in lib to configure it.

Create a project named wsTest

First configure the spring config file spring-source.xml Code as follows:

 

<?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>

Configure in web. xml with the following code:

<?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>

Then the interface is written.

package com.tp.soft.web.ws;import java.util.Map;import javax.jws.WebService;@WebServicepublic interface LoginService {    public abstract Map<String, Object> doLogin(String username, String password);}

The implementation class implements a simple json code for passing in the account password and returning an account password object:

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;    }}

At this point you can access the address directly through the browser: http://xxx.xxx.xx.x: 8081/wsTest/ws/rest/loginService/login? Username = "zs" & password = "123" Special Note: If you access the service through get, change @ POST to @ GET if you want to access the service.

 

After the server is ready, the following code is written for the customer service. The client mainly obtains the json of the user object, and the code is as follows:

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();        }    }}

Run the command to view the result.

 


What is the best way to develop a WebService server in java? What are the differences between different technologies?

In the project, we use the cxf method to implement webService. There are three ways to implement webService.
Axis2 -- Xfire -- cxf
Why is it necessary to use cxf to implement webService? It is because cxf is an upgraded version of xfire and is applicable to java,
Xfire/cxf features higher performance than axis2 and easier integration with spring, while axis2 supports more languages with lower performance than cxf, therefore, cxf is used to transmit data between two projects. To ensure the Security of webservice, we adopt the WS-Security standard-based Security verification (using the CXF callback function ).

How does java write the webservice server?

Java Web services are divided into SOAP-based and REST-based. The following is a SOAP-based example. Only Versions later than JDK6u4 can be compiled.
First, compile a Web Service interface:
@ WebService @ SOAPBinding (style = Style. RPC) public interface TimeServer {@ WebMethod String getTimeAsString (); @ WebMethod long getTimeAsElapsed ();} Then write the Web Service implementation:
Import java. util. date; import javax. jws. webService; @ WebService (endpointInterface = "test. timeServer ") public class TimeServerImpl implements TimeServer {public String getTimeAsString () {return new Date (). toString ();} public long getTimeAsElapsed () {return new Date (). getTime () ;}} finally starts the Web Service:
Public class TimeServerPublisher {public static void main (String [] args) {Endpoint. publish ("127.0.0.1: 9876/ts", new TimeServerImpl ());}}
If it starts normally, you can access 127.0.0.1: 9876/ts in a browser? The wsdl file of the Web Service is displayed.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.