Please find the following code.
Service:DataResource.java
package com.mypack.pack2;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
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.Context;
import javax.ws.rs.core.MediaType;
import com.mypack.pack1.DataClass;
#Path("data")
public class DataResource {
//Just retrieves the data members of the class
//i.e., 10 Ram
// Able to retrieve successfully.
#GET
#Produces("text/plain")
public String display()
{
DataClass obj1=new DataClass();
return obj1.getId()+obj1.getName();
}
#POST
#Path("/{id}/{name}")
#Produces("text/plain")
#Consumes("text/plain")
public void newData(#PathParam("id") int no,
#PathParam("name") String name) {
DataClass obj= new DataClass();
obj.setData(name,no);
System.out.println("Success");
System.out.println("Data after changes"+obj.getId()+obj.getName());
}
//TodoDao.instance.getModel().put(id, todo);
}
DataClass.java
package com.mypack.pack1;
public class DataClass {
private String ename="Ram";
private int eno=10;
public void setData(String name,int no)
{
this.ename=name;
this.eno=no;
}
public int getId()
{
return eno;
}
public String getName()
{
return ename;
}
}
Web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>de.vogella.jersey.jaxb</display-name>
<servlet>
<servlet-name>Jersey REST Service</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.mypack.pack2</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
I am not able to change the values of class members ename and eno of DataClass. Can anyone please tell me why it is not changing? Is it because i am trying the code in a wrong way?
How are you invoking the POST URI (localhost:8080/JerseyProject/rest/data/11/John)? Be sure you are not invoking it from your browser, cause this way you would be invoking the verb GET o the /data/{id}/{name} that doesn't have implementation. That would explain why you're getting the status 405.
Usually the CREATE operation is used using the HTTP VERB POST on the collection URI with its params in the payload not on the path. In this case using POST on /data instead of /data/{id}/{name}.
Related
I tried to create a simple Restful Web Service, but when I tried to debug it, an error occurred when the "return customer" like the picture. May I know what is the cause? It seem like it failed Convert a Java Object to XML using JAXB when return object Customer which contain data.
package com.mkyong.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/xml/customer")
public class XMLService {
#GET
#Path("/{pin}")
#Produces(MediaType.APPLICATION_XML)
public Customer getCustomerInXML(#PathParam("pin") int pin) {
Customer customer = new Customer();
customer.setName("mkyong");
customer.setPin(pin);
return customer;
}
}
package com.mkyong.rest;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"name",
"pin"
})
#XmlRootElement(name = "customer")
public class Customer {
String name;
int pin;
#XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlAttribute
public int getPin() {
return pin;
}
public void setPin(int pin) {
this.pin = pin;
}
}
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
Restful Web Application
<servlet>
<servlet-name>JAVA API</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.mkyong.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAVA API</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
I have found the error in this sample, the latest eclipse IDE had deprecated the xml jar, you have to add it back manually in the IDE when running and debugging (in the configuration) –
After deploying the ejb project and the web project on glassfish and when I run my webservice PatientService I have HTTP Status 404 - Not Found. this is my code :
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
#Named
#Path("/patient")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public class PatientService {
#Inject
private PatientEntityFacade patientEntityFacade;
#Context
private UriInfo uriInfo;
#GET()
#Path("/findALL")
public List<PatientEntity> findAll(){
return patientEntityFacade.findAll();
}
}
And this is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
can you help me please ?
I am writing a RESTful web service with Jersey. I want to return a custom object in XML form to consumer. The error I am getting is:
MessageBodyWriter not found for media type={application/xml, q=1000}, type=class com.test.ws.Employee, genericType=class com.test.ws.Employee.
Below is the code:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>com.vogella.jersey.first</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<!-- Register resources and providers under com.vogella.jersey.first package. -->
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.test.ws</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Service Class
package com.test.ws;
#Path("/hello")
public class Hello {
#GET
#Path("/sayHello")
#Produces(MediaType.APPLICATION_XML)
public Employee sayHello() {
Employee employee = new Employee();
employee.setEmpId(1);
employee.setFirstName("Aniket");
employee.setLastName("Khadke");
return employee;
}
}
Employee.java
package com.test.ws;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "employee")
public class Employee {
public String firstName;
public String lastName;
public int empId;
public Employee(String firstName, String lastName, int empId) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.empId = empId;
}
public Employee() {
super();
}
#XmlElement
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#XmlElement
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#XmlElement
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
}
And here is the list of libraries added:
Can anyone help me?
I believe your error is in the web.xml. Try changing your part to this in your web.xml.
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<!-- Register resources and providers under com.vogella.jersey.first package. -->
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.test.ws</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
One way to solve your issue is to create a custom javax.ws.rs.core.Application or org.glassfish.jersey.server.ResourceConfig. It seems that your server does not detect your providers for the serialization. By implementing your own Application, you will be able to specify which provider you want to use. for your example, what you could have done is :
MyApplication.java
package com.test.ws;
public class MyApplication extends ResourceConfig {
public MyApplication() {
//register your resources
packages("com.test.ws");
//if you're using Jackson as your XMLProvider for example
register(JacksonJaxbXMLProvider.class);
}
}
And add the application in your deployment file :
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>com.vogella.jersey.first</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.test.ws.MyApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Employee class should implements Serializable interface
I was able to resolve the issue myself. This was because of having conflicting jars included in build path. Here is the snap for jar files.
I manage a legacy project wich I needed to add a REST web service. This not have Maven.
For jersey 2.25, the last compiled with Java SDK 1.7, I solved adding jar
jersey-media-jaxb-2.25.jar
I'm trying to create my own RESTful WS application using Jersey 2.12 based from this article. I want to return an XML representation of a class depending on the id been passed from the url, however, I'm getting a 500 response code when trying from either Advanced Rest Client Application (google chrome app) or browser. Below are the details:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>WS_RESTful_Practice</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<!-- Register resources and providers under com.vogella.jersey.first package. -->
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>test.services</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
TestRestModel.java
package test.model;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class TestRestModel{
/**
*
*/
private static final long serialVersionUID = -8391589100962515747L;
private String name;
private String content;
public TestRestModel(String name, String content){
this.name = name;
this.content = content;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
TestResource.java
package test.services;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import test.dao.TestModelDao;
import test.model.TestRestModel;
#Path("/test")
public class TestResource {
#GET
#Path("{id}")
public Response getModel(#PathParam("id") String id){
return Response.ok().entity(TestModelDao.instance.getModel().get(id)).build();
}
}
TestModelDao.java
package test.dao;
import java.util.HashMap;
import java.util.Map;
import test.model.TestRestModel;
public enum TestModelDao {
instance;
private Map<String, TestRestModel> container = new HashMap<String, TestRestModel>();
private TestModelDao(){
TestRestModel model = new TestRestModel("a", "this is first");
container.put("1", model);
model = new TestRestModel("b", "this is second");
container.put("2", model);
model = new TestRestModel("c", "this is third");
container.put("3", model);
}
public Map<String, TestRestModel> getModel(){
return container;
}
}
I'm totally new to Jersey and REST. And I don't know how to log error from Jersey yet.
This happens when you don't provide a default no arg constructor to your JAXB bean. So in your case you should amend the class by adding one:
public TestRestModel(){
}
This is due to a requirement in the JSR-222:
existing types, authored by users, are required to provide a no arg
constructor. The no arg constructor is used by an unmarshaller during
unmarshalling to create an instance of the type.
Stuff below is not the answer, but will probably help Johne to find out, whats up.
Out of the comments I've extract, that the main problem is, that you don't have any noticeable debug output in your console. So you are not able to find the issue by yourself, rather than give us some logs which would help to find out, what the exact problem could be.
Therefore pls implement an ExceptionMapper first, which will force console output of the stacktrace:
Example:
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
#Provider
public class HelpMeExceptionMapper implements ExceptionMapper<Exception> {
#Override
public Response toResponse(Exception e) {
e.printStackTrace();
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.type(MediaType.APPLICATION_JSON)
.entity(e.getCause())
.build();
}
}
The ExceptionMapper has to be in a subpackage of your resource-config/providers path test.services:
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>test.services</param-value>
</init-param>
As i didn't implement your/vogellas code i would like to recommend you, to debug this step by step to find out whats up.
I reckon, that you miss to import something. But who knows ...
Have a nice day ...
To the ones with the same problem, I had something like it but in my case it was a List that i wanted in my response. The source of the problem was that the object had a lazy load relationship and when I used GenericEntity> to return my list the same problem as occurred to me.
Just change to null the relationship or bring the lazy load relation to the object before create GenericEntity> and it will be fine.
We need to understand this problem first
Jersey returns 500 when trying to return an XML response. This issue is coming because of missing dependency in pom.xml and that is:
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.2.11</version>
</dependency>
But this is not enough. This will resolve the 500 Error but one more error will come, while using endpoint.
javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: com/sun/xml/bind/v2/model/annotation/AnnotationReader
To resolve this you need to add following dependencies too into pom.xml
<!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-core -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.1</version>
</dependency>
So this is the complete solution, to make your Jersey webApp work
I am trying to learn jersey by creating a small RESTful service. I want to use the Filters for specific reasons(Like I want to use the ContainerResponseFilter for CORS headers to allow cross domain requests). However, I am just not able to get these filters intercept my call. I have seen all the posts for this problem and most of them say to register with annotation provider or in web.xml.
I have tried registering the files in web.xml as well as giving a #Provider annotation for the container
Here is my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html#d4e194 -->
<web-app version="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">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring/config/BeanLocations.xml</param-value>
</context-param>
<servlet>
<servlet-name>Jersey Web Application</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.rest.example</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.rest.example.cors</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>com.rest.example.CORSFilter</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
<param-value>com.rest.example.RequestFilter</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webresources/*</url-pattern>
</servlet-mapping>
</web-app>
Here are my Filters:
package com.rest.example.cors;
import javax.ws.rs.ext.Provider;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;
#Provider
public class CORSFilter implements ContainerResponseFilter {
public ContainerResponse filter(ContainerRequest creq,
ContainerResponse cresp) {
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "*");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Credentials", "true");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
return cresp;
}
}
package com.rest.example.cors;
import javax.ws.rs.ext.Provider;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
#Provider
public class RequestFilter implements ContainerRequestFilter {
public ContainerRequest filter(ContainerRequest request) {
System.out.println("request filter");
return request;
}
}
Link to my github project.
I added a Jersey Application class and registered the filter in the class, which solved my problem. Also upgraded my jersey version to 2.x from 1.x
public class MyApplication extends ResourceConfig {
/**
* Register JAX-RS application components.
*/
public MyApplication () {
register(RequestContextFilter.class);
register(JacksonFeature.class);
register(CustomerResource.class);
register(Initializer.class);
register(JerseyResource.class);
register(SpringSingletonResource.class);
register(SpringRequestResource.class);
register(CustomExceptionMapper.class);
}
}
I solved the problem on Wildfly 10 / rest easy like this (CORSFilter is my ContainerResponseFilter):
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("/rest")
public class JaxRsActivator extends Application {
#Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> resources = new HashSet<Class<?>>();
resources.add(CORSFilter.class);
return resources;
}
}
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>org.anchepedheplatform.infrastructure.core.filters.ResponseCorsFilter</param-value>
</init-param>
First, I wrote a class which implements com.sun.jersey.spi.container.ContainerResponseFilter
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;
/**
* Filter that returns a response with headers that allows for Cross-Origin
* Requests (CORs) to be performed against the platform API.
*/
public class ResponseCorsFilter implements ContainerResponseFilter {
#Override
public ContainerResponse filter(final ContainerRequest request, final ContainerResponse response) {
final ResponseBuilder resp = Response.fromResponse(response.getResponse());
resp.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
final String reqHead = request.getHeaderValue("Access-Control-Request-Headers");
if (null != reqHead && !reqHead.equals(null)) {
resp.header("Access-Control-Allow-Headers", reqHead);}
response.setResponse(resp.build());
return response;
}
and later I had put this reference of this class in intit-param web.xml.
If you are extending the ResourceConfig class the process of registering all the providers can be tedious one and chances are there that one can even miss few providers.
What here can be done with a type of ResourceConfig is you can use packages method in the default constructor to specify the packages("") which will contain your rest resources and the providers. For Instance lets say we have a package com.test.poc.rest which contains all the rest services and another package namely com.test.poc.providers then our resourceConig will look like:
public class CustomResourceConfig extends ResourceConfig{
public CustomResourceConfig(){
super();
packages("com.test.poc.rest;com.test.poc.providers");
//register any custom features
register(JacksonFeature.class); // enabling JSON feature.
}
}
and boom jersey will now scan for your webservices annotated with #Path and for the providers annotated with #Provider.