Access-Control-Allow-Origin in ajax call for jersey rest web services

I used jAX-R jersey as a web service to query mysql.I am trying to use a web service through a hybrid mobile app.

I call it http://coenraets.org/blog/2011/11/building-restful-services-with-java-using-jax-rs-and-jersey-sample-application/#comment-440541

On the server side, the following code running in tomcat server7 for sql query

@Path("/employees") public class EmployeeResource { EmployeeDAO dao = new EmployeeDAO(); @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public List<Employee> findAll() { return dao.findAll(); } } 

public class EmployeeDAO {

 public List<Employee> findAll() { List<Employee> list = new ArrayList<Employee>(); Connection c = null; String sql = "SELECT e.id, e.firstName, e.lastName, e.title FROM employee as e"; try { c = ConnectionHelper.getConnection(); Statement s = c.createStatement(); ResultSet rs = s.executeQuery(sql); while (rs.next()) { list.add(processSummaryRow(rs)); } } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { ConnectionHelper.close(c); } return list; } protected Employee processSummaryRow(ResultSet rs) throws SQLException { Employee employee = new Employee(); employee.setId(rs.getInt("id")); employee.setFirstName(rs.getString("firstName")); employee.setLastName(rs.getString("lastName")); employee.setTitle(rs.getString("title")); /*employee.setPicture(rs.getString("picture")); employee.setReportCount(rs.getInt("reportCount"));*/ return employee; } 

}

I created a database directory with a table name as an employee with field identifiers, firstName, lastName, title.

Now I have an html file in the web content folder of the same project .

 <!DOCTYPE HTML> <html> <head> <title>Employee Directory</title> </head> <body> <h1>Employee Directory</h1> <ul id="employeeList"></ul> <script src="http://code.jquery.com/jquery-1.7.min.js"></script> <script src="js/employeelist.js"></script> </body> </html> 

useeelist script

 getEmployeeList(); function getEmployeeList() { $.getJSON(serviceURL + 'employees', function(data) { $('#employeeList li').remove(); var employees = data.employee; $.each(employees, function(index, employee) { $('#employeeList').append( '<li><a href="employeedetails.html#' + employee.id + '">' + employee.firstName + ' ' + employee.lastName + ' (' + employee.title + ')</a></li>'); }); }); } 

Details about employees on the index page will be shown here.

Now I created the html page in another project , where I put the same call to $ .getJSON, which is indicated above, will cause an error in the console as

  XMLHttpRequest cannot load http://localhost:8181/jQueryJAXRS/rest/employees. Origin null is not allowed by Access-Control-Allow-Origin. 

In fact, I'm trying to develop an application with client and server infrastructure. Therefore, I need the html files in the client to consume jersey web services on the servers. This is really useful if I do $ .getJSON or $ .ajax call from html file to another project in order to use web service.

 when i use this url http://localhost:8181/jQueryJAXRS/rest/employees in my browser 

it shows xml

 <employees> <employee> <firstName>john</firstName> <id>1</id> <lastName>doe</lastName> <reportCount>0</reportCount> <title>trainee</title> </employee> <employee> <firstName>james</firstName> <id>2</id> <lastName>dane</lastName> <reportCount>0</reportCount> <title>developer</title> </employee> <employee> <firstName>ramsy</firstName> <id>4</id> <lastName>stuart</lastName> <reportCount>0</reportCount> <title>QA</title> </employee> </employees> 

but when I try through the script, it will show a CORS error. Suggest that some ideas really help me.

Thanks in advance.

+4
java json rest ajax cors
source share
3 answers

You must use CORS .

For this:

  • You must use the cors-filter flag
  • Then you need to use the filter in your web.xml:

     <filter> <filter-name>CORS</filter-name> <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class> <init-param> <param-name>cors.allowGenericHttpRequests</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>cors.allowOrigin</param-name> <param-value>*</param-value> </init-param> <init-param> <param-name>cors.allowSubdomains</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>cors.supportedMethods</param-name> <param-value>GET, HEAD, POST, OPTIONS</param-value> </init-param> <init-param> <param-name>cors.supportedHeaders</param-name> <param-value>Content-Type, X-Requested-With</param-value> </init-param> <init-param> <param-name>cors.exposedHeaders</param-name> <param-value>X-Test-1, X-Test-2</param-value> </init-param> <init-param> <param-name>cors.supportsCredentials</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>cors.maxAge</param-name> <param-value>-1</param-value> </init-param> </filter> <filter-mapping> <filter-name>CORS</filter-name> <url-pattern>/EmployeeResource</url-pattern> </filter-mapping> 
+4
source share

Thanks to Jhanvi for suggesting this CORS idea. Here I explain more in order to have better clarity and make this a complete solution to this problem.

I refer to this link to solve this problem

CORS JAR

Download javascript javascript javascript and java. Add these banks to the tomcat server lib folder. Then add the following filter as the chlidnode of the web application 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> 

This solution will solve the CORS problem.

+12
source share

Thanks for this question! This led me to a shorter way to import the jar using maven and just adding dependencies to pom.xml

 <dependency> <groupId>com.thetransactioncompany</groupId> <artifactId>java-property-utils</artifactId> <version>1.9.1</version> </dependency> <dependency> <groupId>com.thetransactioncompany</groupId> <artifactId>cors-filter</artifactId> <version>1.9.1</version> </dependency> 

Check current versions:
http://mvnrepository.com/artifact/com.thetransactioncompany/cors-filter/1.9 http://mvnrepository.com/artifact/com.thetransactioncompany/java-property-utils/1.9

+3
source share

All Articles