spring-mvc:415(不支持的媒体类型)jquery

时间:2017-01-05 12:44:53

标签: java jquery json spring-mvc jackson

我已经检查了hereherehere的答案,但某些内容对我来说无效。我的问题是一样的,当我尝试提交表单时,我得到了415 -unsupport支持的媒体类型。即使我与邮递员客户检查它显示相同。所以它必须是我的后端代码。但我无法得到它。

这是我的jquery代码

    home='<%=request.getContextPath()%>';
function companyRegistration(){
    var add = {}
    var address={};
    add["type"] = $("#type").val();
    add["companyName"] = $("#companyName").val();
    add["regNumber"] = $("#regNumber").val();
    add["dob"] = $("#dob").val();
    add["email"] = $("#email").val();
    add["password"] = $("#password").val();
    add["confirmPassword"] = $("#cpassword").val();
    address["line1"] = $("#line1").val();
    address["line2"] = $("#line2").val();
    address["state"] = $("#state").val();
    address["country"] = $("#country").val();
    address["zipCode"] = $("#zipCode").val();
    add["address"]=address;
    add["enabled"]=false;
    console.log("search: ", add);
console.log("stringify data:",JSON.stringify(add));
    $.ajax({
        type : "POST",
     /*      headers: { 
                'Accept': 'application/json',
                'Content-Type': 'application/json' 
            },  */
        contentType: "application/json;charset=UTF-8",
        url : home+"/addCompany",
        data : JSON.stringify(add),
        dataType : 'json',
        timeout : 100000,
        success : function(data) {
            console.log("SUCCESS: ", data);
            alert(data)

        },
        error : function(e) {
            console.log("ERROR: ", e);
            alert(e);

        },done : function(e) {
            console.log("DONE");
        }
});

这里是相应的后端代码

 @RequestMapping(value="/addCompany",method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE)
   public@ResponseBody String userLogin(@RequestBody CompanyRegVO user,HttpServletRequest req){
    logger.debug("signUp user:"+user);
     // get reCAPTCHA request param
    String gRecaptchaResponse = req.getParameter("g-recaptcha-response");
    boolean isVerified= Verify.verifyGcaptchResponse(gRecaptchaResponse);
    ObjectMapper mapper=new ObjectMapper();
    String jsonString="";       
    System.out.println("signUp user:"+user);
    Integer id=null;
    try{
        if(isVerified){
            id = signupHandler.process(user);
            if(id!=null){
                logger.debug("ID in controller:"+id);

                emailHandler.sendVerificationMail(id,user.getEmail());
                System.out.println("user create successfully"); 

            }
            jsonString=mapper.writeValueAsString("User creaated successfully");

        }
         else
        jsonString= mapper.writeValueAsString("please verify that you are not a robot");
    } catch (JsonGenerationException e) {

        e.printStackTrace();
    } catch (JsonMappingException e) {

        e.printStackTrace();
    } catch (IOException e) {
                e.printStackTrace();
    } catch (Exception e) {
        try {
            jsonString=mapper.writeValueAsString(e.getMessage());
        } catch (JsonProcessingException e1) {

        }
        return jsonString;
    }


    return "success";

   }

我尝试添加标头和内容类型并接受。因此我的配置类

@Configuration
@ComponentScan(basePackageClasses={EmailHandler.class,CompanyRegVO.class,CompanyInfoDao.class,MainController.class,MyDBAuthenticationService.class,CompanyRegVO.class,ApplicationContextConfig.class,HibernateUtil.class,SendMail.class})
public class ApplicationContextConfig {
    @Bean
  public ResourceBundleMessageSource messageSource() {
      ResourceBundleMessageSource rb = new ResourceBundleMessageSource();
      // Load property in message/validator.properties
      rb.setBasenames(new String[] { "messages/validator" });
      return rb;
  }

  @Bean(name = "viewResolver")
  public InternalResourceViewResolver getViewResolver() {
      InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
      viewResolver.setPrefix("/WEB-INF/pages/");
      viewResolver.setSuffix(".jsp");
      return viewResolver;
  }

此CompanyRegVO

public class CompanyRegVO {
private String companyName;
private Integer regNumber;
private String password;
private String confirmPassword;
private String type;
private String email;
private String dob;
private Boolean enabled;
private AddressVO address;
//getters and setters
}

我的POM中有Jackson-core,jackson-mapper-asl,jackson数据绑定依赖。请让我知道哪里出错了?

编辑1: 如果我删除@RequestBody注释,有一件事是正常的 这是我在控制台中添加的对象

这是我的addressVO类

public class AddressVO {
 private String line1;
 private String line2;
 private Integer zipCode;
 private String state;
 private String country;
//getter and setter
}

此处是字符串化后的数据

stringify数据:{"type":"user","companyName":"k","regNumber":"0","dob":"16-10-1992","email":"vihangshah16@gmail.com","password":"12345678","confirmPassword":"12345678","address":{"line1":"l3","line2":"l2","state":"k","country":"i","zipCode":"12"},"enabled":false}

EDIT2: 根据此处的输入,我的网络标签显示

Request URL:http://localhost:8080/basicPages/addCompany
Request Method:POST
Status Code:415 Unsupported Media Type
Remote Address:127.0.0.1:8080
**Response Headers**
view source
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Language:en
Content-Length:1091
Content-Type:text/html;charset=utf-8
Date:Sat, 07 Jan 2017 06:11:32 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block
**Request Headers**
view parsed
POST /basicPages/addCompany HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 253
Accept: application/json
Origin: http://localhost:8080
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
Content-Type: application/json
Referer: http://localhost:8080/basicPages/signUp
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Cookie: JSESSIONID=0FFD6259AED6E75ABD62ED556AC125E4; oracle.uix=0^^GMT+5:30^p
**Request Payload**
view source
{type: "user", companyName: "k", regNumber: "1", dob: "16-10-1992", email: "v16@gmail.com",…}
address:{line1: "l1", line2: "", state: "g", country: "i", zipCode: "1234"}
companyName:"k"
confirmPassword:"12345678"
dob:"16-10-1992"
email:"v16@gmail.com"
enabled:false
password:"12345678"
regNumber:"1"
type:"user"

2 个答案:

答案 0 :(得分:0)

看看几件事:

这就是它的样子:

{
    "type": "user",
    "name": "teqni",
    "regNumber": "12345",
    "dob": "16-10-1992",
    "email": "vihangshah16@gmail.com",
    "password": "12345678",
    "confirmPassword": "12345678",
    "line1": "f-12",
    "line2": "e city",
    "state": "ka",
    "country": "in",
    "zipCode": "1235"
}

It should have been :


{
    "type": "user",
    "name": "teqni",
    "regNumber": "12345",
    "dob": "16-10-1992",
    "email": "vihangshah16@gmail.com",
    "password": "12345678",
    "confirmPassword": "12345678",
    "address":{
        "line1": "f-12",
        "line2": "e city",
       "state": "ka",
       "country": "in",
      "zipCode": "1235"
     }
}

应嵌入AddressVO对象。我觉得不正确的json。

尝试将@JsonIgnoreProperties(ignoreUnknown = true)添加到pojo类

答案 1 :(得分:0)

我不知道为什么以前的方法不起作用但是在我使用JSOnSerilizable对象之后它成功运行了。 以下是我更新的代码。

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonIgnoreProperties(ignoreUnknown=true)
@JsonSerialize(using=CompanySerilizable.class)
public class SignUpVO {
    private String email;
    private Integer regNumber;
    private String companyName;
    private String dob;
    private String type;
    private String password;
    private String confirmPassword;
    private AddressVO address;

    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getConfirmPassword() {
        return confirmPassword;
    }
    public void setConfirmPassword(String confirmPassword) {
        this.confirmPassword = confirmPassword;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Integer getRegNumber() {
        return regNumber;
    }
    public void setRegNumber(Integer regNumber) {
        this.regNumber = regNumber;
    }
    public String getCompanyName() {
        return companyName;
    }
    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }
    public String getDob() {
        return dob;
    }
    public void setDob(String dob) {
        this.dob = dob;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public AddressVO getAddress() {
        return address;
    }
    public void setAddress(AddressVO address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "SignUpVO [email=" + email + ", regNumber=" + regNumber + ", companyName=" + companyName + ", dob=" + dob
                + ", type=" + type + ", address=" + address + "]";
    }
}

这是我的可序列化的类

import java.io.IOException;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

public class CompanySerilizable extends JsonSerializer<SignUpVO> {

    @Override
    public void serialize(SignUpVO sign, JsonGenerator json, SerializerProvider sprov)
            throws IOException, JsonProcessingException {
        json.writeStartObject();
        json.writeNumberField("regNumber", sign.getRegNumber());
        json.writeStringField("line1", sign.getAddress().getLine1());
        json.writeStringField("companyName", sign.getCompanyName());
        json.writeStringField("dob", sign.getDob());
        json.writeStringField("line2", sign.getAddress().getLine2());
        json.writeStringField("country", sign.getAddress().getCountry());
        json.writeStringField("state", sign.getAddress().getState());
        json.writeNumberField("zipCode", sign.getAddress().getZipCode());
        json.writeStringField("password", sign.getPassword());
        json.writeStringField("confirmPassword", sign.getConfirmPassword());
        json.writeStringField("email", sign.getEmail());
        json.writeStringField("type", sign.getType());
        json.writeEndObject();

    }

}