[JavaWEB]Rest学习记录——Jersey学习(1)

时间:2022-03-27 12:53:05

创建第一个JerseyWebService

eclipse + Maven插件 + Jersey framework


  • 创建一个Maven项目
  • 选择项目的ArcheType原型(jersey-quickstart-grizzly)
  • 填写项目信息,填写完点击“Finish”
  • Eclipse地址栏右下方可看到项目正在生成的进度条
  • 项目生成成功,查看项目目录结构
    -Main.java是grizzly web server启动的Java小应用程序
    “F:\EclipseCode\jerseyTest\src\main\java\com\bxl\group\jerseyTest\Main.java”
    -MyResource是自动生成第一个REST Resource类,包含了一个简单的GET请求的资源
    “F:\EclipseCode\jerseyTest\src\main\java\com\bxl\group\jerseyTest\MyResource.java”
  • 执行Main.java,grizzly web server将启动
    -访问http://localhost:8080/myapp/application.wadl,将生成的REST资源描述语言
    -访问生成的测试资源http://localhost:8080/myapp/myresource,看到“Got it”,第一个Jersey程序创建成功

修改pom.xml,添加Maven相应依赖库

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">


<modelVersion>4.0.0</modelVersion>

<groupId>com.bxl.group</groupId>
<artifactId>jerseyTest</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>jerseyTest</name>

<url>http://maven.apache.org</url>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-grizzly2-http</artifactId>
</dependency>
<!-- uncomment this to get JSON support:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
-->

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.2</version>
</dependency>
</dependencies>

<build>
<finalName>jerseyTest</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.bxl.group.jerseyTest.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>

<properties>
<jersey.version>2.1</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

添加基本类Student

/**
* @author ShirleyPaul
* @date : 2017年2月16日 上午11:45:44
*/

package com.bxl.group.jerseyTest;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Student {
private int id;
private String name;
private String dept;

public int getId() {
return id;
}

public Student() {
}

public Student(int id, String name, String dept) {
super();
this.id = id;
this.name = name;
this.dept = dept;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}

}

添加一个REST web服务实现类RestDemo

/**
* @author ShirleyPaul
* @date : 2017年2月16日 上午11:46:14
*/

package com.bxl.group.jerseyTest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import com.bxl.group.jerseyTest.Student;

import org.apache.log4j.Logger;


@Path("/students")
public class RestDemo {
private static Logger logger = Logger.getLogger(RestDemo.class);
private static int index = 1;
private static Map<Integer,Student> studentList = new HashMap<Integer, Student>();

public RestDemo() {
if(studentList.size()==0) {
studentList.put(index, new Student(index++, "Baoxl", "CS"));
studentList.put(index, new Student(index++, "ShirleyPaul", "Math"));
}
}

@GET
@Path("{studentid}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Student getMetadata(@PathParam("studentid") int studentid) {
if(studentList.containsKey(studentid))
return studentList.get(studentid);
else
return new Student(0, "Nil", "Nil");
}

@GET
@Path("list")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public List<Student> getAllStudents() {
List<Student> students = new ArrayList<Student>();
students.addAll(studentList.values());
return students;
}

@POST
@Path("add")
@Produces("text/plain")
public String addStudent(@FormParam("name") String name,
@FormParam("dept") String dept) {
studentList.put(index, new Student(index++, name, dept));
return String.valueOf(index-1);
}

@DELETE
@Path("delete/{studentid}")
@Produces("text/plain")
public String removeStudent(@PathParam("studentid") int studentid) {
logger.info("Receieving quest for deleting student: " + studentid);

Student removed = studentList.remove(studentid);
if(removed==null) return "failed!";
else return "true";
}

@PUT
@Path("put")
@Produces("text/plain")
public String putStudent(@QueryParam("studentid") int studentid,
@QueryParam("name") String name,
@QueryParam("dept") String dept
) {
logger.info("Receieving quest for putting student: " + studentid);
if(!studentList.containsKey(studentid))
return "failed!";
else
studentList.put(studentid, new Student(studentid, name, dept));

return String.valueOf(studentid);
}
}

修改web.xml文件
“-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN”
“http://java.sun.com/dtd/web-app_2_3.dtd” >


Archetype Created Web Application


jersey
com.sun.jersey.spi.container.servlet.ServletContainer

    <init-param>
<param-name>com.sun.jersey.config.property.resourceConfigClass</param-name>
<param-value>com.sun.jersey.api.core.PackagesResourceConfig</param-value>
</init-param>

<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.bxl.group.jerseyTest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>


运行

url栏输入“http://localhost:8080/jerseytest/application.wadl”出现

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<application xmlns="http://wadl.dev.java.net/2009/02">
<doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 2.1 2013-07-18 18:14:16"/>
<grammars>
<include href="application.wadl/xsd0.xsd">
<doc title="Generated" xml:lang="en"/>
</include>
</grammars>
<resources base="http://localhost:8080/jerseytest/">
<resource path="myresource">
<method id="getIt" name="GET">
<response>
<representation mediaType="text/plain"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="application/vnd.sun.wadl+xml"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="text/plain"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="*/*"/>
</response>
</method>
</resource>
<resource path="/students">
<resource path="delete/{studentid}">
<param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="studentid" style="template" type="xs:int"/>
<method id="removeStudent" name="DELETE">
<response>
<representation mediaType="text/plain"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="application/vnd.sun.wadl+xml"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="text/plain"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="*/*"/>
</response>
</method>
</resource>
<resource path="add">
<method id="addStudent" name="POST">
<request>
<representation mediaType="application/x-www-form-urlencoded">
<param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="name" style="query" type="xs:string"/>
<param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="dept" style="query" type="xs:string"/>
</representation>
</request>
<response>
<representation mediaType="text/plain"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="application/vnd.sun.wadl+xml"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="text/plain"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="*/*"/>
</response>
</method>
</resource>
<resource path="list">
<method id="getAllStudents" name="GET">
<response>
<ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" element="student" mediaType="application/xml"/>
<ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" element="student" mediaType="application/json"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="application/vnd.sun.wadl+xml"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="text/plain"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="*/*"/>
</response>
</method>
</resource>
<resource path="put">
<method id="putStudent" name="PUT">
<request>
<param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="studentid" style="query" type="xs:int"/>
<param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="name" style="query" type="xs:string"/>
<param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="dept" style="query" type="xs:string"/>
</request>
<response>
<representation mediaType="text/plain"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="application/vnd.sun.wadl+xml"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="text/plain"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="*/*"/>
</response>
</method>
</resource>
<resource path="{studentid}">
<param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="studentid" style="template" type="xs:int"/>
<method id="getMetadata" name="GET">
<response>
<ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" element="student" mediaType="application/xml"/>
<ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" element="student" mediaType="application/json"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="application/vnd.sun.wadl+xml"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="text/plain"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="*/*"/>
</response>
</method>
</resource>
</resource>
<resource path="application.wadl">
<method id="getWadl" name="GET">
<response>
<representation mediaType="application/vnd.sun.wadl+xml"/>
<representation mediaType="application/xml"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="text/plain"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="*/*"/>
</response>
</method>
<resource path="{path}">
<param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="path" style="template" type="xs:string"/>
<method id="geExternalGrammar" name="GET">
<response>
<representation mediaType="application/xml"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="text/plain"/>
</response>
</method>
<method id="apply" name="OPTIONS">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="*/*"/>
</response>
</method>
</resource>
</resource>
</resources>
</application>

地址栏输入“http://localhost:8080/jerseytest/students/list

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<students>
<student>
<dept>CS</dept>
<id>1</id>
<name>Baoxl</name>
</student>
<student>
<dept>Math</dept>
<id>2</id>
<name>ShirleyPaul</name>
</student>
</students>

地址栏输入“http://localhost:8080/jerseytest/students/1
会显示一个学生的信息

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<student>
<dept>CS</dept>
<id>1</id>
<name>Baoxl</name>
</student>