I am trying to configure CXF nonSpring with Swagger to see the json documentation generated, but I can not see where the url that was generated from Swagger is.
Here is my code:
pom.xml
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-service-description-swagger</artifactId>
<version>3.1.11</version>
</dependency>
web.xml
<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<display-name>CXFServlet</display-name>
<servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value> com.bank.AdminApplication </param-value>
</init-param>
<init-param>
<param-name>jaxrs.application.address.ignore</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>jaxrs.features</param-name>
<param-value>
org.apache.cxf.jaxrs.swagger.Swagger2Feature
(basePath=/swagger/apidocs)
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
main interface with definitions and annotations:
#Path("/")
#Api(value="/swagger/apidocs")
public interface ApiClient {
#GET
#Path("endpoint/consult")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#ApiOperation(value = "Consult test Endpoint", response = Response.class)
public Response consultEndpoint() throws ServiceException;
}
I go to: http://localhost:8080/webapp/swagger/apidocs
but nothing appears
Any recommendation?
Well, finally I found how to integrate CXF non spring with swagger; here is the code:
pom.xml
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>coop.bancocredicoop.test</groupId>
<artifactId>test-api-cxfnonspring-swagger</artifactId>
<version>1.0.0</version>
<name>test-api-cxfnonspring-swagger</name>
<description>Servicios test api rest</description>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>swagger-ui</artifactId>
<version>3.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-service-description-swagger</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.9.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
web.xml
<?xml version="1.0"?><!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"><web-app><servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.AdminApplication</param-value>
</init-param>
<init-param>
<param-name>jaxrs.address</param-name>
<param-value>/</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping></web-app>
AdminAplication.java
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
import org.apache.cxf.jaxrs.swagger.Swagger2Feature;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
public class AdminApplication extends Application {
HashSet<Object> singletons = new HashSet<Object>();
public AdminApplication() {
singletons.add(new PersonService());
}
#Override
public Set<Class<?>> getClasses() {
HashSet<Class<?>> set = new HashSet<Class<?>>();
return set;
}
#Override
public Set<Object> getSingletons() {
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
mapper.setAnnotationIntrospectors(primary, secondary);
JacksonJsonProvider jaxbProvider = new JacksonJsonProvider();
jaxbProvider.setMapper(mapper);
singletons.add(jaxbProvider);
Swagger2Feature feature = new Swagger2Feature();
feature.setContact("Pablo Garcia");
feature.setDescription("api Description");
feature.setPrettyPrint(true);
feature.setTitle("api title");
singletons.add(feature);
return singletons;
}
}
PersonService.java
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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;
#Path("/people")
#Produces(MediaType.APPLICATION_JSON)
#Api(value = "/people")
public class PersonService {
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/person/{id}/")
#ApiOperation(
value = "api value",
notes = "api notes "
)
public Response getPerson(#PathParam("id") String personId) throws Exception {
PersonResponse p = new PersonResponse();
return Response.ok(p).build();
}
}
And finally, a simple POJO PersonResponse:
public class PersonResponse {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Related
Actually , I'm struggling with this issue from two days . I am not able to output in console and I do not know what the problem is?
I am hitting this URL on my local machine, http://localhost:8080/Last/webapi/employee/p2
Below is the Screenshot of my issue :
https://i.stack.imgur.com/vubwA.png
Code is as below.
pom.xml
<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.webservices</groupId>
<artifactId>Last</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Last</name>
<build>
<finalName>Last</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.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<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-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<!-- Thanks for using https://jar-download.com -->
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-binding</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-jaxb -->
<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-bundle -->
<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-core -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.19.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-jaxb -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-jaxb</artifactId>
<version>2.31</version>
</dependency>
</dependencies>
<properties>
<jersey.version>2.31</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
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 -->
<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">
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Jersey Web Application</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.webservices.Last</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
</web-app>
EmployeesList.java
package com.webservices.Last;
import java.util.ArrayList;
import java.util.List;
import javax.print.attribute.standard.Media;
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.QueryParam;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path(value = "employee")
public class EmployeesList {
List<StaffInformation> st = null;
public EmployeesList() {
st = new ArrayList<>();
st.add(new StaffInformation("Kerem", "Kağan","123"));
st.add(new StaffInformation("Java", "Oracle","321"));
}
#GET
#Produces(MediaType.APPLICATION_XML)
#Path("/p2")
public Response listXML()
{
List<StaffInformation> list = new ArrayList<StaffInformation>();
list.add(new StaffInformation("kerem", "ss", "123"));
GenericEntity<List<StaffInformation>> entity = new GenericEntity<List<StaffInformation>>(list) {};
Response response = Response.ok(entity).build();
return response;
}
}
StaffInformation.java
package com.webservices.Last;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class StaffInformation {
#XmlElement
private String name;
#XmlElement
private String surname;
#XmlElement
private String tcNo;
public String getTcNo() {
return tcNo;
}
public void setTcNo(String tcNo) {
this.tcNo = tcNo;
}
public StaffInformation() {
super();
}
public StaffInformation(String name, String surname, String tcNo) {
super();
this.name = name;
this.surname = surname;
this.tcNo = tcNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
you are hitting http://localhost:8080/Last/webapi/employee/p2 url
try with
http://localhost:8080/webapi/employee/p2
or
add '/last' in your web.xml, url pattern field
The path you are requesting is not found by the server, hence you are seeing the 500 internal server error.
You have mentioned as #Path(value = "employee") for your main path whereas that should be
#Path(value = "/employee")
and changing that to "/employee" should work fine. I tried your code in my local machine and it just worked fine after changing to "/employee".
This means the URL starts with /employee (after Application path) and remaining methods to follow this URL. Forex in your case http://localhost:8080/Last/webapi/employee/p2
Trying to produce JSON code from database entries using rest but I am getting a HTTP 500 error code
#Path("product")
public class ProductResource {
#GET
#Produces({ MediaType.APPLICATION_XML })
public List<Product> getProductInformation() {
return ProductDAO.instance.getProductInformation();
}
}
^^ This is the class I have mapped to the resource I am trying to access
It then accesses the ProductDAO class which gets the info from the database and adds it to a HashMap (This part seems to work fine)
public enum ProductDAO {
instance;
private Map<Integer, Product> productMap = new HashMap<Integer, Product>();
private ProductDAO() {
loadFromDb();
}
public Map<Integer, Product> loadFromDb() {
productMap.clear();
try {
Connection conn = Utils.getConnection();
PreparedStatement psmt = conn.prepareStatement("SELECT * FROM products");
ResultSet rs = psmt.executeQuery();
while (rs.next()) {
Product p = new Product(rs.getInt("id"), rs.getString("description"), rs.getInt("CategoryId"),
rs.getDouble("price"), rs.getInt("QuantitySold"), rs.getString("image"));
productMap.put(productMap.size() + 1, p);
System.out.println(productMap);
}
} catch (Exception e) {
e.printStackTrace();
}
return productMap;
}
public List<Product> getProductInformation() {
List<Product> product = new ArrayList<Product>();
product.addAll(productMap.values());
return product;
}
I have 4 test entries in the database currently.
When I add a system.out.println() for the HashMap I get the following output to the console:
Database connection established
{1=myApp.Product#20c427e5}
{1=myApp.Product#20c427e5, 2=myApp.Product#610e026a}
{1=myApp.Product#20c427e5, 2=myApp.Product#610e026a, 3=myApp.Product#2e0456eb}
{1=myApp.Product#20c427e5, 2=myApp.Product#610e026a, 3=myApp.Product#2e0456eb, 4=myApp.Product#5241c547}`
My pom.xml is as follows:
<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.framesinmind</groupId>
<artifactId>FramesIM</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>FramesIM</name>
<build>
<finalName>FramesIM</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.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<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-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
<scope>compile</scope>
</dependency>
</dependencies>
<properties>
<jersey.version>2.16</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
Web.xml as follows:
<?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 -->
<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">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>myApp</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
The Java classes are all part of the 'myApp' package
When trying to access the url 'http://localhost:8080/FramesIM/rest/product' I get the HTTP 500 error. Any ideas?
The internal server error is because you need to code the Product class with the annotations and cannot directly pass the list as response. Please follow the code below.
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessType;
#XmlRootElement(name = "product")
#XmlAccessorType (XmlAccessType.FIELD)
public class Product {
String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "products")
#XmlAccessorType (XmlAccessType.FIELD)
public class Products
{
#XmlElement(name="product")
private List<Product> products;
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("product")
public class ProductResource {
#GET
#Produces(MediaType.APPLICATION_XML)
public Products getProductInformation() {
List<Product> product = ProductDAO.instance.getProductInformation();
Products products = new Products();
products.setProducts(product);
return products;
}
}
The response below is the sample output
<products>
<product>
<id>12</id>
</product>
</products>
I get this error when I try to see JSON response in my browser. I read a lot of posts on stack witch are similar but nothing work. Browser return "Error 500". Intellij IDEA return error "Error MessageBodyWriter not found for media type=application/json". Here is my code:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>app</artifactId>
<version>1.0-SNAPSHOT</version>
<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-servlet-core</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-entity-filtering</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<properties>
<jersey.version>2.23.2</jersey.version>
</properties>
</project>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="3.1">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>app</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
MessageService:
package app.resource;
import app.model.Message;
import app.service.MessageService;
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 java.util.List;
#Path("messages")
public class MessageResource {
MessageService messageService = new MessageService();
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<Message> getMessages()
{
return messageService.getAllMessages();
}
#GET
#Path("/{messageId}")
#Produces(MediaType.APPLICATION_JSON)
public Message test(#PathParam("messageId") long id)
{
return messageService.getMessage(id);
}
}
Message class:
package app.model;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Date;
#XmlRootElement
public class Message {
private long id;
private String message;
private Date created;
private String author;
public Message()
{
}
public Message(long id, String message, String author) {
this.id = id;
this.message = message;
this.created = new Date();
this.author = author;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
Old post, but I figured it could help someone. I can across the same issue playing around with Apache Tomcat 9.0.36 and Jersey. This error is due to a missing media dependency. Here are my Jersey POM dependencies that worked for me:
<!-- Jersey dependencies -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.29.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.29.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.29.1</version>
</dependency>
<!-- Jersey media type files, including XML -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-jaxb</artifactId>
<version>2.29.1</version>
</dependency>
<!-- Jersey JSON entity providers -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.29.1</version>
</dependency>
You can read more about Jersey supported media types in their documentation.
I have created a REST webservice 'JSONService' ( using Jersey implementation JAX-RS) with a POST method and created 'JerseyClientPost'.
What I am trying to achieve is to send a POST from my JerseyClientPost. Getting all values into a 'player' object and sending along with response back. But while trying to send the POST request from the postman, it throws
HTTP Status 404 - Not Found, The requested resource is not available.
Any pointers to address this problem will be much appreciated ?
Request Url : http://localhost:8080/WeekendSoccer/test/register/create
Following are my environment details:
JDK 1.7.0_79,
Tomcat Server v7.0,
Jersey (jaxrs-ri-2.25.1),
Web.xml
//REST Resource is given below
package webService;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import dto.RegisterPlayer;
#Path("/register")
public class JSONService {
#POST
#Path("/create")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response createPlayerInJSON(RegisterPlayer player) {
String result = "Player Created : " +player;
return Response.status(201).entity(result).build();
}
}
//Below is the Jersey Client Post
package dao;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
public class JerseyClientPost {
public static void main(String[] args) {
try {
RegisterPlayer player = new RegisterPlayer();
player.setName("Link");
player.setEmail("link#test.com");
player.setCompany("Test Ltd");
Client client = ClientBuilder.newClient(new ClientConfig().register( LoggingFilter.class ));
WebTarget webTarget
= client.target("http://localhost:8080/WeekendSoccer/test");
WebTarget playerWebTarget
= webTarget.path("/register/create");
Invocation.Builder invocationBuilder
= playerWebTarget.request(MediaType.APPLICATION_JSON);
Response response
= invocationBuilder
.post(Entity.entity(player,MediaType.APPLICATION_JSON));
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));
} catch (Exception e) {
e.printStackTrace();
}
}
}
// RegisterPlayer model class with getters, setters
public class RegisterPlayer implements Serializable{
private String name;
private String email;
private String company;
public RegisterPlayer()
{
}
public RegisterPlayer(String name, String email, String company)
{
super();
this.name = name;
this.email = email;
this.company = company;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
....
}
// 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>WeekendSoccer</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Register Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>webService</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Register Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>JSON Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>dao</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JSON Service</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
</web-app>
//Listed all jars
aopalliance-repackaged-2.5.0-b32.jar
gson-2.2.2.jar
hk2-api-2.5.0-b32.jar
hk2-locator-2.5.0-b32.jar
hk2-utils-2.5.0-b32.jar
jackson-annotations-2.3.2.jar
jackson-core-2.3.2.jar
jackson-databind-2.3.2.jar
jackson-jaxrs-base-2.3.2.jar
jackson-jaxrs-json-provider-2.3.2.jar
jackson-module-jaxb-annotations-2.3.2.jar
javassist-3.20.0-GA.jar
javax.annotation-api-1.2.jar
javax.inject-2.5.0-b32.jar
javax.servlet-api-3.0.1.jar
javax.ws.rs-api-2.0.1.jar
jaxb-api-2.2.7.jar
jersey-client.jar
jersey-common.jar
jersey-container-servlet-core.jar
jersey-container-servlet.jar
jersey-entity-filtering-2.17.jar
jersey-guava-2.25.1.jar
jersey-media-jaxb.jar
jersey-media-json-jackson-2.17.jar
jersey-server.jar
mysql-connector-java-5.1.40-bin.jar
org.osgi.core-4.2.0.jar
osgi-resource-locator-1.0.1.jar
persistence-api-1.0.jar
validation-api-1.1.0.Final.jar
Firstly, I have never tested your client side code but I guess your problem is about server side and tested in Postman. you should add #XmlRootElement annotation in your pojo class RegisterPlayer like that:
#XmlRootElement
public class RegisterPlayer implements Serializable{
private String name;
private String email;
private String company;
public RegisterPlayer()
{
}
public RegisterPlayer(String name, String email, String company)
{
super();
this.name = name;
this.email = email;
this.company = company;
}
and added these dependencies in pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
If you already have these jars it is fine. It works for me right now. I hope it helps to you.
jackson-core-2.9.3.jar
jackson-mapper-asl-1.9.13.jar
jackson-core-asl-1.9.13.jar
asm-3.3.1.jar
jersey-bundle-1.19.4.jar
jsr311-api-1.1.1.jar
json-20170516.jar
jersey-server-1.19.4.jar
jersey-core-1.19.4.jar
jersey-multipart-1.19.4.jar
mimepull-1.9.3.jar
jackson-annotations-2.7.0.jar
jackson-databind-2.7.0.jar
I'm still not sure, why do you have following mapping in web.xml ? As theren't any servlet class associated with this servlet name. You should removed them
<servlet-mapping>
<servlet-name>JSON Service</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
I see you have following entries and they do have servlet class associated.
<servlet-mapping>
<servlet-name>Register Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
That means, you target url should be
http://localhost:8080/WeekendSoccer/rest/register/create
instead of
http://localhost:8080/WeekendSoccer/test/register/create
This question already has answers here:
Why does Spring MVC respond with a 404 and report "No mapping found for HTTP request with URI [...] in DispatcherServlet"?
(13 answers)
Closed 6 years ago.
While learning spring i was trying to run code examples of Spring in Action
but it is showing me the below mentioned error in tomcat logs:
11-Aug-2016 12:15:57.561 WARNING [http-nio-8080-exec-1] org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/RestTester-0.0.1-SNAPSHOT/] in DispatcherServlet with name 'dispatcher'
I am trying to configure spring by the help of java based configuration only.
Code for the same is mentioned below:
TestProjectInitializer.java
package test.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class TestProjectInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return new Class<?>[]{RootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class<?>[]{WebConfig.class};
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[]{"/"};
}
}
WebConfig.java
package test.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("test.webconf")
public class WebConfig extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver getViewResolver()
{
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".html");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
{
configurer.enable();
}
}
RootConfig.java
package test.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#ComponentScan(basePackages={"test"}, excludeFilters={#Filter(type=FilterType.ANNOTATION,value=EnableWebMvc.class)})
public class RootConfig {
}
HomeController.java
package test.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
/*#RequestMapping("/")*/
public class HomeController
{
#RequestMapping(value="/",method=RequestMethod.GET)
public String home()
{
return "home";
}
}
pom.xml
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>RestTester</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
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>test</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
Directory Structure
Please help me understanding what i am doing wrong.
The name of base package on Webmvc was wrong and should be test.controller.