Spring RESTful ajax gets error

2019-06-13 16:49发布

问题:

When I put my service address http://localhost:8080/mailservice/mail/name into web browser address bar then I receive response in json like this :

["name"]

but when i create a simple html page like this bellow:

<html>
<head>
 <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script>
    $( document ).ready(function() {
        doMagic();
    });
    function doMagic()
    {
        $.ajax({
          type: 'GET',
          url: 'http://localhost:8080/mailservice/mail/name',
          contentType:"application/json",
          success: function () {
            console.log("ok");
          },
            error: function (request, status, error) {
                console.log(status);
            }
        });
    }
</script>
</head>
<body>
<div id="out">
</div>
</body>
</html>

my ajax always hits error function, it doesn't matter if I'm using POST (different example of ajax code with html, not present here) or GET.

My Controller looks like that:

@Controller
@RequestMapping("/mail")
public class MailController {

    @Autowired
    MailService mailService;

    @RequestMapping(value = "/{name}", 
            method = RequestMethod.GET,
            produces={"application/json"})
    public @ResponseBody
    List<String> getMovie(@PathVariable String name) {
        List<String> lista = Arrays.asList(name);
        return lista;
    }


    @RequestMapping(value = "/send", 
            method = RequestMethod.POST,
            produces={"application/json","application/xml"})
    @ResponseBody 
    public String getDefaultMovie(Message message) {
        mailService.sendEmail(message);
        return "OK!";
    }

}

Information from firebug:

GET http://localhost:8080/mailservice/mail/name 200 OK 9ms

Headers
Response headers
Content-Type    application/json;charset=UTF-8
Date    Sat, 12 Apr 2014 14:07:22 GMT
Server  GlassFish Server Open Source Edition 4.0
Transfer-Encoding   chunked
X-Powered-By    Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition 4.0 Java/Oracle Corporation/1.7)

Request headers
Accept  */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
DNT 1
Host    localhost:8080
Origin  null
User-Agent  Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0

error

My web.xml

<!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>Mail service</display-name>
     <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
         <servlet-name>dispatcher</servlet-name>
         <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

My dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

<context:component-scan base-package="com.szymon.mailservice.concrete,
                                        com.szymon.mailservice.controllers,
                                        com.szymon.mailservice.entities,
                                        com.szymon.mailservice.interfaces" />

    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
      <property name="mediaTypes">
        <map>
           <entry key="json" value="application/json" />
           <entry key="text" value="text/javascript" />
           <entry key="xml" value="application/xml" />
        </map>
      </property>

      <property name="defaultContentType" value="application/json" />
    </bean>

<tx:annotation-driven />

<mvc:annotation-driven />

</beans>

My 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.szymon</groupId>
  <artifactId>mailservice</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>mailservice Maven Webapp</name>
  <url>http://maven.apache.org</url>

    <properties>
        <spring.version>3.2.5.RELEASE</spring.version>
    </properties>

  <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>   
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.9.12</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.12</version>
        </dependency>       
        <dependency>
                   <groupId>org.slf4j</groupId>
                   <artifactId>slf4j-api</artifactId>
                   <version>1.5.6</version>
                   <type>jar</type>
        </dependency>
        <dependency>
                   <groupId>org.slf4j</groupId>
                   <artifactId>slf4j-simple</artifactId>
                   <version>1.5.6</version>
        </dependency>  
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>       
        <dependency>
                <groupId>javax.mail</groupId>
                <artifactId>mail</artifactId>
                <version>1.4</version>
        </dependency>        
        <dependency>
            <groupId>org.codemonkey.simplejavamail</groupId>
            <artifactId>simple-java-mail</artifactId>
            <version>2.1</version>
        </dependency>       
          <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
          </dependency>     
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20131018</version>
        </dependency>            
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
  </dependencies>
  <build>
    <finalName>mailservice</finalName>
  </build>
</project>

Let someone help :(

回答1:

In your ajax call, can you try with

...
...
url: '/mailservice/mail/name'
...
...

and recompile it and try again. I think this is the issue because origin is null.



回答2:

Disclaimer: This was extracted from the question.

Solution (partial)

I had to change html file and web.xml and dispatcher-servlet.xml

$(function() {
    var url = 'http://localhost:8080/email/mail/send.jsonp?callback=jsonCallback';

    $.ajax({
        url: url,
    type: "GET",
    async: false,
    jsonpCallback: 'jsonCallback',
    contentType: "application/json",
    dataType: 'jsonp',
        error: function(a, b, c) {
            console.log(JSON.stringify(a)+","+b+","+c);
        },
    success: function( response ) {
        console.log( response );
    }
    });
});    

dispatcher-servlet.xml

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="favorPathExtension" value="true"/>
    <property name="mediaTypes">
        <map>
            <entry key="json" value="application/json"/>
            <entry key="jsonp" value="application/javascript"/>
        </map>
    </property>
    <property name="defaultViews">
        <list>
            <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
            <bean class="org.szymon.email.classes.MyMapperClass"/>
        </list>
    </property>
</bean>

web.xml:

<servlet-mapping>
     <servlet-name>dispatcher</servlet-name>
     <url-pattern>*.json</url-pattern>
     <url-pattern>*.jsonp</url-pattern>      
     <url-pattern>/*</url-pattern>
</servlet-mapping>

MyMapperClass.java

package org.szymon.email.classes;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

public class MyMapperClass extends MappingJacksonJsonView {

    /**
     * Default content type. Overridable as bean property.
     */
    public static final String DEFAULT_CONTENT_TYPE = "application/javascript";

    @Override
    public String getContentType() {
        return DEFAULT_CONTENT_TYPE;
    }

    /**
     * Prepares the view given the specified model, merging it with static
     * attributes and a RequestContext attribute, if necessary.
     * Delegates to renderMergedOutputModel for the actual rendering.
     * @see #renderMergedOutputModel
     */
    @Override
    public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

        if("GET".equals(request.getMethod().toUpperCase())) {
            @SuppressWarnings("unchecked")
            Map<String, String[]> params = request.getParameterMap();

            if(params.containsKey("callback")) {
                response.getOutputStream().write(new String(params.get("callback")[0] + "(").getBytes());
                super.render(model, request, response);
                response.getOutputStream().write(new String(");").getBytes());
                response.setContentType("application/javascript");
            }

            else {
                super.render(model, request, response);
            }
        }

        else {
            super.render(model, request, response);
        }
    }
}