Java completes the simplest WebService creation and use (REST mode, Jersey framework)

Source: Internet
Author: User

Objective:

has always been interested in webservice, but because it is difficult to understand what WebService is, so little understanding. In Tuesday, a colleague who had a better relationship with me wanted to write a little demo of WebService, hoping to make a similar entry in the browser:

http://localhost:8080/XXX/method? property = value

With this format, you can get the desired data on the page by clicking into it.

I did the C # implementation WebService is the URL with the. asmx, the traditional Java implementation of colleagues WebService is the back with the WSDL, is not the desired format.

I am also very curious about this question, on the Internet to find a lot of information, and finally in two days to write a can be the kind of URL format to access the WebService.

Body:

1, Jersey is used to implement the WebService framework. Go to Jersey website (https://jersey.java.net/) Download the jar package you need to use

2. Create a Web project in MyEclipse (my project is named Javarestdemo)

3, the download jar package (I use Jersey-bundle-1.19.jar) into the/javarestdemo/webroot/web-inf/lib/

4, create the package Net.meng.main, and create the class Helloworld.java in it, the code is as follows:

 PackageNet.meng.main;ImportJavax.servlet.http.HttpServletResponse;Importjavax.ws.rs.*;ImportJavax.ws.rs.core.*; @Path ("/helloworld") Public classHelloWorld {@Context httpservletresponse response; @GET @Produces (Mediatype.text_plain) PublicString GetResult (@QueryParam ("name") (String name) {returnresult (name); } @POST @Produces (Mediatype.text_plain) PublicString Postresult (@QueryParam ("name") (String name) {returnresult (name); }    Privatestring Result (string name) {response.setcharacterencoding ("UTF-8");//address the problem of garbled characters when the name of the variable contains Chinese        return"My name is" + name + ", Hello world!"; }}

5. Modify the contents of the Webroot/web-inf/web.xml file as follows:

<?XML version= "1.0" encoding= "UTF-8"?><Web-appversion= "2.5"xmlns= "Http://java.sun.com/xml/ns/javaee"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">        <servlet>        <Servlet-name>Helloworldservlet</Servlet-name>        <Servlet-class>Com.sun.jersey.spi.container.servlet.ServletContainer</Servlet-class>        <Init-param>            <Param-name>Com.sun.jersey.config.property.packages</Param-name>            <Param-value>Net.meng.main</Param-value>        </Init-param>        <Load-on-startup>1</Load-on-startup>    </servlet>        <servlet-mapping>        <Servlet-name>Helloworldservlet</Servlet-name>        <Url-pattern>/rest/*</Url-pattern>    </servlet-mapping>          <welcome-file-list>        <Welcome-file>index.jsp</Welcome-file>      </welcome-file-list></Web-app>

6. Deploy to Tomcat and start
7, enter the http://localhost:8080/JavaRestDemo/rest/helloworld?name= in the browser address bar, you can see the page is displayed as follows:

(using the Cheetah Browser, Google Chrome effect is the same)

At this point, a HelloWorld version of the rest form of WebService is declared complete.

Postscript:

In fact, this article Thursday can be published, but later I use Firefox and IE for insurance purposes, the direct input URL plus the following Chinese (key word hand), the return will show garbled, like this:

(Firefox, manually enter the URL after the return)

(IE, manually enter the URL after the return)

I made a comparison between the Google and Firefox address bar links, the same as the "hearing dream" two words, the results are different:

Google Chrome display the Address bar link:

Http://localhost:8080/JavaRestDemo/rest/helloworld?name=%e8%81%86%e6%a2%a6

The Address bar link shown in Firefox:

Http://localhost:8080/JavaRestDemo/rest/helloworld?name=%f1%f6%c3%ce

Then through the Webmaster tools to the URL of the UrlEncode encoding/urldecode decoding decoding, found that Google is encoded with UTF-8, Firefox is encoded with gb2312, but because it is the address bar directly input in Chinese, the server after the server can only be encoded by a fixed character encoding to decode, This leads to differences in results.

In order for the three browsers to display the same effect, I changed

Response.setcharacterencoding ("gb2312");

And

New String (Request.getparameter ("name"). GetBytes ("Iso-8859-1"), "gb2312");

The value of the different do a few sets of experiments, initially want to try to see what circumstances can make the results are normal, and later in UTF-8 and gb2312 switch between many times, are cheetahs and Google "queued", ie and Firefox "queued", occasionally naughty ie will "make special". The experimental process records such as:

Where "Go" represents a jump from another page to the results page, "Lose" represents the case of entering Chinese keywords directly in the address bar. In turn, Cheetah, IE, Firefox, Google.

It seems to be set to UTF-8 time can ensure that more than the situation is normal, so the final Helloworld.java code is as follows:

 PackageNet.meng.main;Importjava.io.UnsupportedEncodingException;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjavax.ws.rs.*;ImportJavax.ws.rs.core.*; @Path ("/helloworld") Public classHelloWorld {@Context httpservletrequest request;    @Context httpservletresponse response; @GET @Produces (Mediatype.text_plain) PublicString GetResult (@QueryParam ("name") (String name) {returnresult (name); } @POST @Produces (Mediatype.text_plain) PublicString Postresult (@QueryParam ("name") (String name) {returnresult (name); }    Privatestring Result (string name) {Try{Name=NewString (Request.getparameter ("name"). GetBytes ("Iso-8859-1"), "UTF-8"); } Catch(unsupportedencodingexception e) {e.printstacktrace (); } response.setcharacterencoding ("UTF-8"); return"My name is" + name + ", Hello world!"; }}

Later, I used Baidu's search address in the manual input Chinese keywords in the case of the various browsers to do experiments, found that there will be no such problems, if you are browsing this article you know the solution, but also hope to enlighten.

Java completes the simplest WebService creation and use (REST mode, Jersey framework)

Related Article

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.