为什么在使用Maven,Jax-Rs,Java和休息时会遇到此错误?

发布于 2025-01-23 12:48:20 字数 11938 浏览 0 评论 0原文

以下是我的代码,我正在使用命令行工具,JAX-RS,REST API和JAVA

我会收到此错误:“ RESTRY:MESSECHOVERWRITER在媒体类型= text/plain,type = class java.util.arraylist,genertictype,genertictype = java.util.arraylist class”,当我转到localhost:8888/quotes命令“ mvn exec:java”之后 我在做什么错?我有一个主要类,引用类,QuoteResource类,QuoteService类,quotetest类和pom.xml,以及以下代码:

package edu.depaul.se457.bisbell;

import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;

/**
 * Root resource (exposed at "quotes" path)
 */
@Path("quotes")
public class QuoteResource {
    
    private QuoteService quoteService = new QuoteService();
    
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public Response getAllQuotes() {
        List<Quote> quotes = quoteService.getAllQuotes();
        
        if (!quotes.isEmpty()){
            return Response.ok(quotes).build();
        }else{
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }
    
    @Path("/{id}")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    //public int getQuoteByID(@PathParam("id") int id){
    public Response getQuoteById(@PathParam("id") int id) throws NotFoundException{
        Quote quote = quoteService.fetchBy(id);
        
        if (quote.id.equals(null)) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }else{
            return Response.ok(quote).build();
        }
    }
    
    @POST
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes(MediaType.TEXT_PLAIN)
    public Response createQuote(Quote quote){
        boolean result = quoteService.create(quote);
        if (result){
            return Response.ok().status(Response.Status.CREATED).build();
        }else{
            return Response.notModified().build();
        }
    }
    
    @PUT
    @Path("/{id}")
    @Consumes(MediaType.TEXT_PLAIN)
    public Response updateQuote(@PathParam("id") int id, Quote quote) {
        boolean result = quoteService.update(quote);

        if (result) {
            return Response.ok().status(Response.Status.NO_CONTENT).build();
        } else {
            return Response.notModified().build();
        }
    }


    @Path("/{id}")
    @DELETE
    @Produces(MediaType.TEXT_PLAIN)
    public Response deleteQuote(@PathParam("id") int id) {
        boolean result = quoteService.delete(id);

        if (result) {
            return Response.ok().status(Response.Status.NO_CONTENT).build();
        } else {
            return Response.notModified().build();
        }
    }
}
    

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.depaul.se457.bisbell;

/**
 *
 * @author bkisb
 */
public class Quote {
    Integer id;
    String quote;
    
    public Quote() {

    }

    public Quote(String quote, int id){
        super();
        this.quote = quote;
        this.id = id;
    }
    
    public String getQuote(){
        return quote;
    }
    
    public void setQuote(String quote){
        this.quote = quote;
    }
    
    public int getId(){
        return id;
    }
    
    public void setId(int id){
        this.id = id;
    }
    
    @Override
    public String toString() {
        return "Quote [id=" + id + "]";
    }

    boolean add(Quote quote) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
    
}



package edu.depaul.se457.bisbell;

import jakarta.ws.rs.NotFoundException;
import java.util.ArrayList;
import java.util.List;

/**
 * Root resource (exposed at "quote" path)
 */

public class QuoteService {

    /**
     * Method handling HTTP GET requests. The returned object will be sent
     * to the client as "text/plain" media type.
     *
     * @return String that will be returned as a text/plain response.
     */
    List<Quote> quotes = new ArrayList<>();
    
    public List<Quote> getAllQuotes() {
        quotes.add(new Quote("Some Quote 1", 1));
        quotes.add(new Quote("Some Quote 2", 2));
        quotes.add(new Quote("Some Quote 3", 3));
        quotes.add(new Quote("Some Quote 4", 4));
        quotes.add(new Quote("Some Quote 5", 5));
        return quotes;
    }
    
    //public int getQuoteByID(@PathParam("id") int id){
    public Quote fetchBy(int id) throws NotFoundException{
        for (Quote quote: getAllQuotes()) {
            if (id == quote.getId()){
                return quote;
            }
            else{
                throw new NotFoundException("Resource not found with ID ::" + id);
            }
        }
        return null;
    }
    
    
    public boolean create(Quote quote){
        return quote.add(quote);
    }
    
    
    public boolean update(Quote quote){
        for (Quote updateQuote: quotes) {
            if (quote.getId() == (updateQuote.getId())){
                quotes.remove(updateQuote);
                quotes.add(quote);
                return true;
            }
        }
        return false;
    }
    

        public boolean delete(int id) throws NotFoundException {
        for (Quote quote: quotes) {
            if (quote.getId() == (id)) {
                quotes.remove(quote);
                return true;
            }
        }
        return false;
    }
    
}



package edu.depaul.se457.bisbell;

import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;

import org.glassfish.grizzly.http.server.HttpServer;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class quoteTest {

    private HttpServer server;
    private WebTarget target;

    @Before
    public void setUp() throws Exception {
        // start the server
        server = Main.startServer();
        // create the client
        Client c = ClientBuilder.newClient();

        // uncomment the following line if you want to enable
        // support for JSON in the client (you also have to uncomment
        // dependency on jersey-media-json module in pom.xml and Main.startServer())
        // --
        // c.configuration().enable(new org.glassfish.jersey.media.json.JsonJaxbFeature());

        target = c.target(Main.BASE_URI);
    }

    @After
    public void tearDown() throws Exception {
        server.stop();
    }

    /**
     * Test to see that the message "Got it!" is sent in the response.
     */
    @Test
    public void testGetIt() {
        String responseMsg = target.path("quote").request().get(String.class);
        assertEquals("Got It!", responseMsg);
    }
}





package edu.depaul.se457.bisbell;

import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;

import java.io.IOException;
import java.net.URI;

/**
 * Main class.
 *
 */
public class Main {
    // Base URI the Grizzly HTTP server will listen on
    public static final String BASE_URI = "http://localhost:8888/";

    /**
     * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
     * @return Grizzly HTTP server.
     */
    public static HttpServer startServer() {
        // create a resource config that scans for JAX-RS resources and providers
        // in edu.depaul.se457.bisbell package
        final ResourceConfig rc = new ResourceConfig().packages("edu.depaul.se457.bisbell");

        // create and start a new instance of grizzly http server
        // exposing the Jersey application at BASE_URI
        return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
    }

    /**
     * Main method.
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        final HttpServer server = startServer();
        System.out.println(String.format("Jersey app started with endpoints available at "
                + "%s%nHit Ctrl-C to stop it...", BASE_URI));
        System.in.read();
        server.stop();
    }
}




<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>edu.depaul.se457.bisbell</groupId>
    <artifactId>hw2</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>hw2</name>

    <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>
        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>jersey-hk2</artifactId>
        </dependency>

        <!-- uncomment this to get JSON support:
         <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-binding</artifactId>
        </dependency>
        -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</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>edu.depaul.se457.bisbell.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

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

Below is my code, I am using command line tool, jax-rs, rest apis and java

I get this error: "SEVERE: MessageBodyWriter not found for media type = text/plain, type=class java.util.ArrayList, genericType=class java.util.ArrayList", when I go to localhost:8888/quotes after the command "mvn exec:java"
What am I doing wrong? I have a main class, Quote class, QuoteResource class, QuoteService class, quoteTest class, and pom.xml with the following code:

package edu.depaul.se457.bisbell;

import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;

/**
 * Root resource (exposed at "quotes" path)
 */
@Path("quotes")
public class QuoteResource {
    
    private QuoteService quoteService = new QuoteService();
    
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public Response getAllQuotes() {
        List<Quote> quotes = quoteService.getAllQuotes();
        
        if (!quotes.isEmpty()){
            return Response.ok(quotes).build();
        }else{
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }
    
    @Path("/{id}")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    //public int getQuoteByID(@PathParam("id") int id){
    public Response getQuoteById(@PathParam("id") int id) throws NotFoundException{
        Quote quote = quoteService.fetchBy(id);
        
        if (quote.id.equals(null)) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }else{
            return Response.ok(quote).build();
        }
    }
    
    @POST
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes(MediaType.TEXT_PLAIN)
    public Response createQuote(Quote quote){
        boolean result = quoteService.create(quote);
        if (result){
            return Response.ok().status(Response.Status.CREATED).build();
        }else{
            return Response.notModified().build();
        }
    }
    
    @PUT
    @Path("/{id}")
    @Consumes(MediaType.TEXT_PLAIN)
    public Response updateQuote(@PathParam("id") int id, Quote quote) {
        boolean result = quoteService.update(quote);

        if (result) {
            return Response.ok().status(Response.Status.NO_CONTENT).build();
        } else {
            return Response.notModified().build();
        }
    }


    @Path("/{id}")
    @DELETE
    @Produces(MediaType.TEXT_PLAIN)
    public Response deleteQuote(@PathParam("id") int id) {
        boolean result = quoteService.delete(id);

        if (result) {
            return Response.ok().status(Response.Status.NO_CONTENT).build();
        } else {
            return Response.notModified().build();
        }
    }
}
    

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.depaul.se457.bisbell;

/**
 *
 * @author bkisb
 */
public class Quote {
    Integer id;
    String quote;
    
    public Quote() {

    }

    public Quote(String quote, int id){
        super();
        this.quote = quote;
        this.id = id;
    }
    
    public String getQuote(){
        return quote;
    }
    
    public void setQuote(String quote){
        this.quote = quote;
    }
    
    public int getId(){
        return id;
    }
    
    public void setId(int id){
        this.id = id;
    }
    
    @Override
    public String toString() {
        return "Quote [id=" + id + "]";
    }

    boolean add(Quote quote) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
    
}



package edu.depaul.se457.bisbell;

import jakarta.ws.rs.NotFoundException;
import java.util.ArrayList;
import java.util.List;

/**
 * Root resource (exposed at "quote" path)
 */

public class QuoteService {

    /**
     * Method handling HTTP GET requests. The returned object will be sent
     * to the client as "text/plain" media type.
     *
     * @return String that will be returned as a text/plain response.
     */
    List<Quote> quotes = new ArrayList<>();
    
    public List<Quote> getAllQuotes() {
        quotes.add(new Quote("Some Quote 1", 1));
        quotes.add(new Quote("Some Quote 2", 2));
        quotes.add(new Quote("Some Quote 3", 3));
        quotes.add(new Quote("Some Quote 4", 4));
        quotes.add(new Quote("Some Quote 5", 5));
        return quotes;
    }
    
    //public int getQuoteByID(@PathParam("id") int id){
    public Quote fetchBy(int id) throws NotFoundException{
        for (Quote quote: getAllQuotes()) {
            if (id == quote.getId()){
                return quote;
            }
            else{
                throw new NotFoundException("Resource not found with ID ::" + id);
            }
        }
        return null;
    }
    
    
    public boolean create(Quote quote){
        return quote.add(quote);
    }
    
    
    public boolean update(Quote quote){
        for (Quote updateQuote: quotes) {
            if (quote.getId() == (updateQuote.getId())){
                quotes.remove(updateQuote);
                quotes.add(quote);
                return true;
            }
        }
        return false;
    }
    

        public boolean delete(int id) throws NotFoundException {
        for (Quote quote: quotes) {
            if (quote.getId() == (id)) {
                quotes.remove(quote);
                return true;
            }
        }
        return false;
    }
    
}



package edu.depaul.se457.bisbell;

import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;

import org.glassfish.grizzly.http.server.HttpServer;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class quoteTest {

    private HttpServer server;
    private WebTarget target;

    @Before
    public void setUp() throws Exception {
        // start the server
        server = Main.startServer();
        // create the client
        Client c = ClientBuilder.newClient();

        // uncomment the following line if you want to enable
        // support for JSON in the client (you also have to uncomment
        // dependency on jersey-media-json module in pom.xml and Main.startServer())
        // --
        // c.configuration().enable(new org.glassfish.jersey.media.json.JsonJaxbFeature());

        target = c.target(Main.BASE_URI);
    }

    @After
    public void tearDown() throws Exception {
        server.stop();
    }

    /**
     * Test to see that the message "Got it!" is sent in the response.
     */
    @Test
    public void testGetIt() {
        String responseMsg = target.path("quote").request().get(String.class);
        assertEquals("Got It!", responseMsg);
    }
}





package edu.depaul.se457.bisbell;

import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;

import java.io.IOException;
import java.net.URI;

/**
 * Main class.
 *
 */
public class Main {
    // Base URI the Grizzly HTTP server will listen on
    public static final String BASE_URI = "http://localhost:8888/";

    /**
     * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
     * @return Grizzly HTTP server.
     */
    public static HttpServer startServer() {
        // create a resource config that scans for JAX-RS resources and providers
        // in edu.depaul.se457.bisbell package
        final ResourceConfig rc = new ResourceConfig().packages("edu.depaul.se457.bisbell");

        // create and start a new instance of grizzly http server
        // exposing the Jersey application at BASE_URI
        return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
    }

    /**
     * Main method.
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        final HttpServer server = startServer();
        System.out.println(String.format("Jersey app started with endpoints available at "
                + "%s%nHit Ctrl-C to stop it...", BASE_URI));
        System.in.read();
        server.stop();
    }
}




<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>edu.depaul.se457.bisbell</groupId>
    <artifactId>hw2</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>hw2</name>

    <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>
        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>jersey-hk2</artifactId>
        </dependency>

        <!-- uncomment this to get JSON support:
         <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-binding</artifactId>
        </dependency>
        -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</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>edu.depaul.se457.bisbell.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文