2

I have a Simple Web Service returning JSON data.

enter image description here

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

  1. getAllUser() -> Queries the DB to Select all Users from User Table and returns List{User}
  2. 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 ?

Arindam Das
  • 206
  • 1
  • 7
  • 29
  • 1
    You miss the interceptor to add the "Access-Control-Allow-Origin" header to the servlet response. Cf : http://patrickgrimard.com/2013/12/12/cross-origin-resource-sharing-cors-requests-with-spring-mvc/ – alain.janinm Nov 21 '14 at 08:11
  • @alain.janinm The above mentioned Link is useful, Thank You but can you explain it w.r.t the given problem ? – Arindam Das Nov 21 '14 at 08:34
  • Are you sure that requests come from sub domain ? – Maksym Nov 21 '14 at 08:45
  • The CORS filter you have done allows incoming request to be processed by your servlet (it actually add to the response returned to the browser a header that tells thats the request will actually be proceed) But you also have to add a header to the Servlet response your return to the customer (after the request has been proceed), this is done with the interceptor. – alain.janinm Nov 21 '14 at 08:45

1 Answers1

3

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>
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Ahmed Nasser
  • 114
  • 6