• Eclipse+Jersey实现RESTful服务接口(简单列子)


    web.xml 配置

    <servlet>
        <servlet-name>jerseyRestService</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>com.webservice.resfull</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
        <servlet-mapping>
            <servlet-name>jerseyRestService</servlet-name>
            <url-pattern>/rest/*</url-pattern>
        </servlet-mapping>

    实体类

    package com.webservice.resfull;
    
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.QueryParam;
    import javax.ws.rs.core.MediaType;
    
    @Path("hello")
    public class HelloResource {
    
        @GET
        @Produces(MediaType.TEXT_PLAIN)
        public String sayHello() {
            return "hello,jersey";
        }
        
        @GET
        @Path("hi")
        public String sayHiTo(@QueryParam("name") String name) {
            return "hello To " + name;
        }
    
    }

    maven配置

            <dependency>
         <groupId>com.sun.jersey</groupId>
         <artifactId>jersey-server</artifactId>
         <version>1.17.1</version>
    </dependency>
    <dependency>
         <groupId>com.sun.jersey</groupId>
         <artifactId>jersey-core</artifactId>
         <version>1.17.1</version>
    </dependency>
    <dependency>
         <groupId>com.sun.jersey</groupId>
         <artifactId>jersey-servlet</artifactId>
         <version>1.17.1</version>
    </dependency>

    测试:

    浏览器输入

    http://localhost:8080/xxx/rest/hello    (其中xxx是你的项目名)

    结果页面输出:hello,jersey

    浏览器输入:
    http://localhost:8080/xxx/rest/hello/hi?name=tom
    结果页面输出:hello To tom

    注意事项:

    web.xml中com.webservice.resfull 是指你的java类的包路径

  • 相关阅读:
    P1219 N皇后(位运算&普通dfs)
    P1434 滑雪(记忆化搜索)
    P1118 数字三角形(技巧)
    P1162 填涂颜色
    P1141 01迷宫
    P2685抓牛(bfs)
    WordPress ‘crypt_private()’方法远程拒绝服务漏洞
    java获取网页源码
    tomcat报错: Error parsing HTTP request header
    空指针异常的原因
  • 原文地址:https://www.cnblogs.com/rdchen/p/13891941.html
Copyright © 2020-2023  润新知