我开始将我的软件从 Primefaces 更改为 HTML5 客户端 - 服务器解决方案。
问题:同源策略在使用 POST 时失败,但在使用 GET 时有效。
网络服务
@POST
@Override
@Consumes({"application/xml", "application/json"})
public void create(Users entity) {
super.create(entity);
}
@GET
@Override
@Produces({"application/xml", "application/json"})
public List<Users> findAll() {
return super.findAll();
}
筛选
public class CrossOriginResourceSharingFilter implements ContainerResponseFilter {
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
response.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "*");
response.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "content-type");
return response;
}
}
WEB.XML
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>entity.CrossOriginResourceSharingFilter</param-value>
</init-param>
客户
<form id="register-form">
<div class="register-form-block">
<input type="text" value='Your first name' name="firstName" id="firstName"/>
</div>
<div class="register-form-block">
<input type="text" value='Your surname' name="lastName" id="lastName" onclick="this.value = ('')" />
</div>
<div class="register-form-block">
<input type="text" value='Username' name="username" id="username" onclick="this.value = ('')"/>
</div>
<div class="register-form-block">
<input type="password" value='Password' name="password" id="password" onclick="this.value = ('')"/>
</div>
<div class="register-form-block">
<input type="password" value='Password again' name="passwordagain" onclick="this.value = ('')"/>
</div>
<button type="submit" class="btn btn-primary" id="btnAddUser" onclick="foo()">Register</button>
</form>
<script>
function foo(){
alert('Button pressed');
$.ajax({
type: 'POST',
contentType: 'application/json',
url: 'http://127.0.0.1:8080/testsoft/webresources/entity.users/',
dataType: "json",
data: formToJSON(),
success: function(data, textStatus, jqXHR) {
alert('User created successfully');
},
error: function(jqXHR, textStatus, errorThrown) {
alert('addUser error: ' + textStatus +' ERROR:'+ errorThrown);
}
});
};
function formToJSON() {
alert($('#username').val());
return JSON.stringify({
"username": $('#username').val(),
"firstName": $('#firstName').val(),
"lastName": $('#lastName').val(),
"password": $('#password').val(),
});
}
</script>
错误
Failed to load resource: the server responded with a status of 500 (Internal Server Error) (22:49:54:618 | error, network)
at http://localhost:8080/testsoft/webresources/entity.users/
XMLHttpRequest cannot load http://localhost:8080/testsoft/webresources/entity.users/. Origin http://localhost:8383 is not allowed by Access-Control-Allow-Origin. (22:49:54:618 | error, javascript)
另一个解决方案不起作用,根本没有错误消息
function foo(){
alert('Button pressed');
console.log('#####################addUser################################');
$.ajax({
type: "POST",
contentType: "application/json",
url: "http://127.0.0.1:8080/testsoft/webresources/entity.users/",
dataType: "json",
data: {"username":"UllaUser","password":"testpwd","firstName":"Unto","lastName":"lastnameson","nickName":null,"isAdmin":false,"isCustomer":false,"isGuest":false,"isActive":true,"isInvemailsent":false,"isInvCardSent":null,"inSaveDateSent":false,"isThankCardSent":false,"weddingAsUser":false,"hasGuestUsers":false,"userRole":null,"email":null,"createDate":null,"turnout":null,"lastUpdated":1360240740000,"secretQuestion":null,"secretAnswer":null,"weddingWeddingId":null,"languageLanguageId":null,"invitationInvitationId":null,"emailEmailId":null,"addressAddressId":null},
success: function(data){
// we have the response
alert("Server said:\n '" + data.username + "'");
},
error: function(data) {
alert('addUser error: ' + data.username);
}
});
};