Rest version of WebService

Source: Internet
Author: User

In order to learn the app to do the plan today to self-study the next webservice,rest should be one of them is also a kind of soap, and now give a rest of the demo bar

To prepare WS jar and spring jar, how to connect the data, you can prepare yourself here.

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

After downloading the jar and putting it into LIB, you can configure it.

Create a project named Wstest

First configure the spring configuration 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/beanshttp//www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp//Www.springframework.org/schema/contexthttp//www.springframework.org/schema/context/spring-context-3.0.xsdhttp//Www.springframework.org/schema/txhttp//www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOPhttp//www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp//Www.springframework.org/schema/jeehttp//www.springframework.org/schema/jee/spring-jee-3.2.xsdhttp//Cxf.apache.org/jaxwshttp//cxf.apache.org/schemas/jaxws.xsdhttp//Cxf.apache.org/jaxrshttp//cxf.apache.org/schemas/jaxrs.xsd "><context:annotation-config/> <context:component-scanBase-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> <beanclass="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> <beanclass="Org.codehaus.jackson.jaxrs.JacksonJsonProvider"/> </jaxrs:providers> </jaxrs:server></beans>

It is then configured 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>contextconfi Glocation</param-name> <param-value>classpath:spring-source.xml</param-value> </context-par am> <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.springframew Ork.web.context.contextloaderlistener</listener-class> </listener></web-app>

And then the interface is written.

Package com.tp.soft.web.ws;import java.util.map;import javax.jws.WebService; @WebService  Public Interface Loginservice {    publicabstract map<string, object> dologin (String username, String password);}

The implementation class makes a very simple incoming account password returns the JSON code for 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 classLoginserviceimpl implements loginservice{@POST @Path (value="/login") @Produces (Mediatype.application_json) PublicMap<string, Object> dologin (@FormParam (value="username") String username, @FormParam (value="Password") {result result of String password) {=NewResult (); if(Username.equals ("ZS") && Password.equals ("123") ) {User User=NewUser ();            User.setusername (username);            User.setpassword (password); Map<string, object> map =NewHashmap<string, object>(); Map.put ("User", user);            Result.setmap (map); returnmap; }        return NULL; }}

The address can be accessed directly from the browser at this time: http://xxx.xxx.xx.x:8081/wsTest/ws/rest/loginService/login?username= "ZS" &password= "123" Special note that this is accessed through get, if you want to be able to access the @post change to @get

The server is written, the following is to write the customer service side of the code, the client is mainly to get the JSON user object, 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 classA { Public Static voidMain (string[] args) {String URL="Http://122.226.178.54:8081/wsTest1/ws/rest/loginService/login"; HttpClient Client=NewHttpClient (); Postmethod Method=Newpostmethod (URL); namevaluepair[] Data= {NewNamevaluepair ("username","ZS"),NewNamevaluepair ("Password","123")};        Method.setrequestbody (data); Try {            intStatusCode =Client.executemethod (method); if(StatusCode = = $) {String Strjson=method.getresponsebodyasstring (); System. out. println (Strjson); Gson Gson=NewGsonbuilder (). Create (); Map<string, user> map = Gson.fromjson (Strjson,NewTypetoken<map<string, user>>() {}.gettype ()); System. out. println (Map.Get("User"). GetUserName ()); }        } Catch(HttpException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }    }}

You can see the results in the run.

Rest version of WebService

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.