用 Java 技術建立 RESTful Web 服務

1、在eclipse上配置rest服務

第一步,在Eclipse裏,新建一個web工程,添加須要用的jar包,以下圖  html


第二步,新建一個class,代碼以下java


第三步,修改web.xml配置文件,以下圖
web


啓動tomcat, 訪問本機測試地址:
tomcat


這時咱們就能夠訪問到咱們發佈的rest服務了,以下圖
eclipse

2、包含post提交的rest代碼

package com.myrest;post

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;測試

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;spa

// 這裏@Path定義了類的層次路徑。
// 指定了資源類提供服務的URI路徑。
@Path("UserInfoService")
public class UserInfo {
    // @GET表示方法會處理HTTP GET請求
    @GET
    // 這裏@Path定義了類的層次路徑。指定了資源類提供服務的URI路徑。
    @Path("/name/{i}")
    // @Produces定義了資源類方法會生成的媒體類型。
    @Produces(MediaType.TEXT_XML)
    // @PathParam向@Path定義的表達式注入URI參數值。
    public String userName(@PathParam("i") String i) {
        // 發現get提交,會幫咱們自動解碼
        System.out.println("傳入 name:" + i);
        String name = "返回name:" + i;
        return name;
    }.net

    @POST
    @Path("/information/")
    public String userAge(String info) throws UnsupportedEncodingException {rest

        // post提交須要咱們手動解碼,避免中文亂碼
        String str = URLDecoder.decode(info, "UTF-8");
        System.out.println("傳入參數: " + info);
        System.out.println("解碼後參數: " + str);
        String value = "返回值:" + str;
        return value;
    }
}

 

3、參考文章

http://www.ibm.com/developerworks/cn/web/wa-jaxrs/ https://zhidao.baidu.com/question/919927134443120859.html http://www.importnew.com/7336.html

相關文章
相關標籤/搜索