I have written a simple RESTful web service in JAVA but when I run it using Run As --> Run on server option from Eclipse IDE, I am getting HTTP Status 404 – Not Found error. Please tell what can be the issue in my code?
Response:
web.xml
<?xml version="1.0" encoding="UTF-8"?> <!--?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>RESTfulWebServiceExample</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>org.arpit.javapostsforlearning.webservice</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>
FeetToInchAndInchToFeetConversionService.java
package org.arpit.javapostsforlearning.webservice;
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("ConversionService")
public class FeetToInchAndInchToFeetConversionService {
#GET
#Path("/InchToFeet/{i}")
#Produces(MediaType.TEXT_XML)
public String convertInchToFeet(#PathParam("i") int i) {
int inch=i;
double feet = 0;
feet =(double) inch/12;
return ""
+ "" + inch + ""
+ "" + feet + ""
+ "";
}
#Path("/FeetToInch/{f}")
#GET
#Produces(MediaType.TEXT_XML)
public String convertFeetToInch(#PathParam("f") int f) {
int inch=0;
int feet = f;
inch = 12*feet;
return ""
+ "" + feet + ""
+ "" + inch + ""
+ "";
}
}
You're trying to go to localhost:8080/RESTfulWebServiceExample when, according to your web.xml, RESTfulWebServiceExample is your display name. You need to go to localhost:8080/rest/ to hit your servlet context root (as defined in your servlet-mapping section of the web.xml).
Related
I need to configure This file i tried to run this file but error was file not found : 404. so what would be the configure file I need to configure This file i tried to run this file but error was file not found : 404. so what would be the configure file
LoginService.java
package com.webService;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import com.pojo.UserVO;
import com.model.SecurityManager;;
#Path("/WebService")
public class LoginService
{
#POST
#Path("/login")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String login(#FormParam("username") String username, #FormParam("password") String password)
{
return getAllUsersList(username, password);
}
public String getAllUsersList(String username, String password)
{
String userListData=null;
ArrayList<UserVO> userList = null;
SecurityManager sm = new SecurityManager();
userList =sm.getAllUsersList();
for(UserVO userVO: userList)
{
if(userVO.getUsername().equals(username))
{
if(userVO.getPassword().equals(password))
{
return "Logged In User :" + username;
}
}
}
return "You Are not a Valid User";
}
}
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>FirstProject</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>ServletAdaptor</servlet-name>
<servlet-class>com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>REST</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
I have created my very first basic rest api. Its working find and give me output in xml using this url
http://localhost:8080/Webservice/Test/RestClient
Now, I'm thinking If I want my api to ask server only specific data then I how can I use parameters for the same in api url.
Here is my little updated code
package RestClient;
//import javax.servlet.annotation.WebServlet;
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.xml.bind.annotation.XmlRootElement;
#Path("/RestClient")
#XmlRootElement
public class Restwebclient {
#GET
#Produces(MediaType.TEXT_XML)
public String sayXMLHello(#PathParam("x") int x, #PathParam("y") int y) {
String output = "";
if (x == 1 && y == 1) {
output = "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
}
else if (x == 2 && y == 2) {
output = "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
}
return output;
}
}
And web.xml is here
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>Webservice</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>JAVA WS</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>RestClient</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAVA WS</servlet-name>
<url-pattern>/Test/*</url-pattern>
</servlet-mapping>
</web-app>
But when run the url passing parameters like this nothing comes up in output
http://localhost:8080/Webservice/Test/RestClient?x=1&y=1
Note: Expected output from above parameters in url should be first if condition
May I know What I'm missing to achieve this ?
You are sending parameters in query so you should use #QueryParam and not #PathParam. change method to:
public String sayXMLHello(#QueryParam("x") int x, #QueryParam("y") int y) {
Query Params:
http://localhost:8080/Webservice/Test/RestClient?x=1&y=1
Path Params need to change Path:
#Path("{x}/{y}/RestClient")
http://localhost:8080/Webservice/Test/1/1/RestClient
This question already has answers here:
How to handle CORS using JAX-RS with Jersey
(5 answers)
Closed 6 years ago.
I have a JAVA RESTful webservice which will return JSON string and it was written in Java. My problem is when I send request to that webservice with below URL
http://localhost:8080/WebServiceXYZ/Users/insert
it's giving me the below error message
XMLHttpRequest cannot load http://localhost:8080/WebServiceXYZ/Users/insert/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 500.
Here is my Code
package com.lb.jersey;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.json.JSONException;
import org.json.JSONObject;
#Path("/Users")
public class RegistrationService
{
#POST
#Produces(MediaType.APPLICATION_JSON)
#Path("/insert")
public String InsertCredentials (String json) throws JSONException
{
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(dt);
String phone = null;
JSONObject returnJson = new JSONObject();
try
{
JSONObject obj = new JSONObject(json);
JSONObject result1 = obj.getJSONObject("Credentials");
phone = result1.getString("phone");
DBConnection conn = new DBConnection();
int checkUserID = conn.GetUserIDByPhone(phone);
if(checkUserID <= 0)
{
DBConnection.InsertorUpdateUsers(phone, currentTime);
}
int userID = conn.GetUserIDByPhone(phone);
int otp = (int) Math.round(Math.random()*1000);
DBConnection.InsertorUpdateCredentials(userID, otp, currentTime);
JSONObject createObj = new JSONObject();
createObj.put("phone", phone);
createObj.put("otp", otp);
createObj.put("reqDateTime", currentTime);
returnJson.put("Credentials", createObj);
System.out.println(returnJson);
}
catch (Exception e)
{
}
return returnJson.toString();
}
}
My web.xml code
<?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>WebServiceXYZ</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.lb.jersey</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
I already read many articles but no progress, so please let me know, How can I handle this issue?
this is assuming you are using jetty as your server. hope it helps...
add the following code to your web.xml
<filter>
<filter-name>cross-origin</filter-name>
<filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
<init-param>
<param-name>allowedOrigins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>allowedMethods</param-name>
<param-value>GET,POST,DELETE,PUT,HEAD</param-value>
</init-param>
<init-param>
<param-name>allowedHeaders</param-name>
<param-value>origin, content-type, accept</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>cross-origin</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
and the following dependency in your pom.xml
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
<version>8.0.0.M0</version>
</dependency>
the link to configure tomcat is link... here is another link2 modify accordingly :)
You can try setting the header for the HttpServletResponse
import javax.servlet.http.HttpServletResponse;
#Path("/Users")
public class RegistrationService
{
#Context
private HttpServletResponse servletResponse;
private void allowCrossDomainAccess() {
if (servletResponse != null){
servletResponse.setHeader("Access-Control-Allow-Origin", "*");
}
}
#POST
#Produces(MediaType.APPLICATION_JSON)
#Path("/insert")
public String InsertCredentials (String json) throws JSONException
{
allowCrossDomainAccess();
// your code here
}
}
I met a surious problem when I want to develop an API to call an "exterior" method (this method is called "createClientNode" which is a simple request for neo4j).
Anyways, this is my 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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>API</display-name>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>API</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-serlvet</servlet-name>
<url-pattern>/API/*</url-pattern>
</servlet-mapping>
</web-app>
And this my class :
package API;
import javax.ws.rs.DefaultValue;
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.MediaType;
import org.neo4j.graphdb.Node;
import function.query.weceipt.GraphManagement;
#Path("/API")
public class MyService {
#POST
#Path("/node")
#Produces({ MediaType.APPLICATION_JSON })
public Node createNode(#DefaultValue("default_id") #QueryParam("ID") String id) {
GraphManagement gm = new GraphManagement();
Node node = gm.createClientNode(id);
return node;
}
#GET
#Path("/node/{ID}")
#Produces({ MediaType.APPLICATION_JSON })
public Node getNode(#PathParam("ID") String id) {
GraphManagement gm = new GraphManagement();
Node node = gm.getClientNode(id);
return node;
}
#Path("/test")
#GET
#Produces(MediaType.TEXT_PLAIN)
public void afficher() {
System.out.println("test");
}
}
the error that I get is "the Servlet jersey-serlvet is not available".
I have the impression that I have-perhaps- a problem with a specific JAR or Tomcat, but I coudn't find the cause of this problem. So, can anyone help me please because I tried a loooong time with this!
I am trying to build simple webservices using Java, Rest Webservices(Jersey), Glass fish. project is successfully deploying in server without any errors, but when i access resources in browser it is giving 404-Not Found Error.
My resources class:
package org.student.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;
#Path("/ConversionService")
public class FeetToInchAndInchToFeetConversionService {
#GET
#Path("/InchToFeet/{i}")
#Produces(MediaType.TEXT_XML)
public String convertInchToFeet(#PathParam("i") int i) {
int inch=i;
double feet = 0;
feet =(double) inch/12;
return "<InchToFeetService>"
+ "<Inch>" + inch + "</Inch>"
+ "<Feet>" + feet + "</Feet>"
+ "</InchToFeetService>";
}
#Path("/FeetToInch/{f}")
#GET
#Produces(MediaType.TEXT_XML)
public String convertFeetToInch(#PathParam("f") int f) {
int inch=0;
int feet = f;
inch = 12*feet;
return "<FeetToInchService>"
+ "<Feet>" + feet + "</Feet>"
+ "<Inch>" + inch + "</Inch>"
+ "</FeetToInchService>";
}
}
And Web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_3_0.xsd"
version="3.0">
<display-name>StudentPortal</display-name>
<servlet>
<servlet-name>Jersey REST 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>org.student.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>
using following Url with https//
mylocalhost:port/StudentPortal/rest/ConversionService/InchToFeet/2
Please Someone point what i am doing wrong