【发布时间】:2017-05-20 00:32:36
【问题描述】:
我已经检查了来自 here,here,here 的答案,但有些东西对我来说无法正常工作。我的问题与我在尝试提交表单时收到 415 -unsupported media type 相同。即使我与邮递员客户检查过,它也显示相同。所以它一定来自我的后端代码。但我无法得到它。
这是我的 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;
}
本公司RegVO
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 注释,一件事可以正常工作 这是我在控制台中添加的对象
这是我的地址VO类
public class AddressVO {
private String line1;
private String line2;
private Integer zipCode;
private String state;
private String country;
//getter and setter
}
这是我字符串化后的数据
字符串化数据:{"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}
编辑2: 根据此处的输入,这是我的网络标签显示的内容
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"
【问题讨论】:
-
在我看来,您正在将一些 HTML 元素发布回服务器,这就是它发生的地方。你可以看一下
JSON.stringify(add)addis not contain any element. -
你能证明你是如何创建“add”变量的值的吗?
-
已添加请看一次
标签: java jquery json spring-mvc jackson