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
Related
my web.xml file :
Web.xml
I am trying to do a simple jersey restful webservice hello world but its not working. Can anyone check where I am doing wrong?
I am using the below URL :
http://localhost:8080/learning1/rest/firstRest/User1
<?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">
<servlet>
<servlet-name>Learn</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>org.java.learning1</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Learn</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
My restfulwebservice java file : java file
Server is responding with HTTP Status code 404 : not found
package org.java.learning1;
import javax.websocket.server.PathParam;
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.HttpHeaders;
#Path("/firstRest")
public class firstRest {
#GET
#Produces("MediaType.TEXT_HTML")
#Path("{name}")
public String sendResponse(#Context HttpHeaders httpHeaders, #PathParam("name") String name){
String greeting = "hello";
return greeting;
}
}
Hello user7481861 and welcome to stackoverflow!
You have two errors in your code, I've corrected them bellow and added a comment in each, saying what was wrong.
package org.java.learning1;
//import javax.websocket.server.PathParam; <-- incorrect import
import javax.ws.rs.PathParam; // <<-- correct import
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.HttpHeaders;
#Path("/firstRest")
public class firstRest {
#GET
#Produces(MediaType.TEXT_HTML) // No quotes like stdunbar said in the comments
#Path("/{name}") // missing slash before name
public String sendResponse(#Context HttpHeaders httpHeaders, #PathParam("name") String name){
String greeting = "hello " + name; // concatenate the string with the variable name
return greeting;
}
}
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 am using jar files instead of maven because i dont have internet.
problem: i am using jersey implemenation of jax-rs. i need to convert the java to json but it is giving the following error
java.lang.NoSuchMethodError: org.glassfish.jersey.internal.util.PropertiesHelper.getValue(Ljava/util/Map;Ljavax/ws/rs/RuntimeType;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;
at org.glassfish.jersey.moxy.json.MoxyJsonFeature.configure(MoxyJsonFeature.java:67)
at org.glassfish.jersey.model.internal.CommonConfig.configureFeatures(CommonConfig.java:730)
at org.glassfish.jersey.model.internal.CommonConfig.configureMetaProviders(CommonConfig.java:648)
at org.glassfish.jersey.server.ResourceConfig.configureMetaProviders(ResourceConfig.java:829)
at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:453)
at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:184)
at org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:350)
at org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:347)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:255)
at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:347)
at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:392)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:177)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:369)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1236)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1149)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1041)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4910)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5192)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1387)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
the code i am using is:
package mypack;
import javax.websocket.server.PathParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.glassfish.jersey.server.BackgroundScheduler;
import entity.Res;
#Path("/s")
public class webapi {
#GET
#Path("q/{name}")
#Produces(MediaType.APPLICATION_JSON)
public Res method(#PathParam("name") String name){
try{
Res r = new Res();
r.setId(5);
r.setName(name);
return r;
}catch(Exception e){
System.out.println(e.getMessage());
return null;
}
}
}
the res class is as follow:
package entity;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Res {
#XmlElement int id;
#XmlElement String name;
public Res() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
the jar files that i am using are:
web.xml file is :
<?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">
<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>mypack</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>
what is the reason for the error?
I Think there may be a problem with the jar Versioning . Because the jar that you used for your Project is Older Version. Please update your lib to update the jersey dependency as i see and predict the error.
I would suggest you to add jars atleast of Version 2.7 instead of 2.2 or 2.3 as your dependency Says.
Please Update your lib Folder then Clean your Project .
Build Your Project again. After Updating your lib with New jar Files .
Thank You
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 have a Simple Web Service returning JSON data.
The User Class (com.bargadss.SpringService.Domain) is The POJO class containing
user_ID, firstName, lastName, eMail
The UserService class (com.bargadss.SpringService.DAO) two major operation
getAllUser() -> Queries the DB to Select all Users from User Table and returns List{User}
getUserById(int user_ID) -> Queries the DB to Select a specific user based on ID
The SpringServiceController (com.bargadss.SpringService.Controller) is as follows :
package com.bargadss.SpringService.Controller;
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.bargadss.SpringService.DAO.UserService;
import com.bargadss.SpringService.Domain.User;
#RestController
#RequestMapping("/service/user/")
public class SpringServiceController {
UserService userService=new UserService();
#RequestMapping(value = "/{id}", method = RequestMethod.GET,headers="Accept=application/json")
public User getUser(#PathVariable int id) {
User user=userService.getUserById(id);
return user;
}
#RequestMapping(method = RequestMethod.GET,headers="Accept=application/json")
public List<User> getAllUsers() {
List<User> users=userService.getAllUsers();
return users;
}
}
The ListUserController (com.bargadss.SpringService.Controller) is as follows :
package com.bargadss.SpringService.Controller;
import java.util.LinkedHashMap;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import com.bargadss.SpringService.Domain.User;
#Controller
public class ListUserController {
#RequestMapping("/listUsers")
public ModelAndView listUsers() {
RestTemplate restTemplate = new RestTemplate();
String url="http://localhost:8080/SpringServiceWithRESTAndJSONExample/service/user/";
List<LinkedHashMap> users=restTemplate.getForObject(url, List.class);
return new ModelAndView("listUsers", "users", users);
}
#RequestMapping("/dispUser/{userid}")
public ModelAndView dispUser(#PathVariable("userid") int userid) {
RestTemplate restTemplate = new RestTemplate();
String url="http://localhost:8080/SpringServiceWithRESTAndJSONExample/service/user/{userid}";
User user=restTemplate.getForObject(url, User.class,userid);
return new ModelAndView("dispUser", "user", user);
}
}
The CorsFilter (com.bargadss.CORS) is as follows :
package com.bargadss.CORS;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
public class CorsFilter extends OncePerRequestFilter{
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Max-Age", "1800");//30 min
}
filterChain.doFilter(request, response);
}
}
The web.xml is as follows :
<?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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SpringServiceWithRESTAndJSONExample</display-name>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>/WEB-INF/jsp/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>cors</filter-name>
<filter-class>com.bargadss.CORS.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
The Web Service when being invoked by AngularJS from another Web Server returns Error referring to Cross Origin Resource Sharing problem !!!
What Changes must be performed in the Controller side to eliminate the error ?
Is there any changes necessary to be done at the AngularJS side to avoid this situation ?
Check the cors-filter
Download cors-filter-2.1.2.jar and java-property-utils-1.9.1.jar.
mvn dependency
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>java-property-utils</artifactId>
<version>1.9.1</version>
</dependency>
and in web.xml
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>