这是使用文本 xml 格式并将其映射到对象以将其持久化的方法
@POST
@Path("/inscription")
@Produces(MediaType.TEXT_HTML)
public Response testClient(String s) {
ResponseBuilder builder = null;
try {
final String xmlString = s;
final StringReader xmlReader = new StringReader(xmlString);
final StreamSource xmlSource = new StreamSource(xmlReader);
final JAXBContext jaxbContext = JAXBContext
.newInstance(Client.class);
final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
final Client client = (Client) unmarshaller.unmarshal(xmlSource,
Client.class).getValue();
System.out.println("nomCl : " + client.getNomCl());
System.out.println("prenomCl : " + client.getPrenomCl());
System.out.println("emailCl : " + client.getEmailCl());
System.out.println("numTel : " + client.getNumTel());
System.out.println("long_ : " + client.getLong_());
System.out.println("lat : " + client.getLat());
System.out.println("LoginCl : " + client.getLoginCl());
System.out.println("PasswordCl : " + client.getPasswordCl());
System.out.println("adresseCl : " + client.getAdresseCl());
EntityManagerFactory factory;
factory = Persistence.createEntityManagerFactory("FournisseurWeb");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
em.persist(client);
em.getTransaction().commit();
em.close();
factory.close();
builder = Response.ok("true");
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
builder = Response.ok("false");
builder.header("Access-Control-Allow-Origin", "*");
builder.header("Access-Control-Max-Age", "3600");
builder.header("Access-Control-Allow-Methods", "POST");
builder.header(
"Access-Control-Allow-Headers",
"X-Requested-With,Host,User-Agent,Accept,Accept-Language,Accept-Encoding,Accept-Charset,Keep-Alive,Connection,Referer,Origin");
return builder.build();
}
builder.header("Access-Control-Allow-Origin", "*");
builder.header("Access-Control-Max-Age", "3600");
builder.header("Access-Control-Allow-Methods", "POST");
builder.header(
"Access-Control-Allow-Headers",
"X-Requested-With,Host,User-Agent,Accept,Accept-Language,Accept-Encoding,Accept-Charset,Keep-Alive,Connection,Referer,Origin");
return builder.build();
}
我用这个示例使用 ajax 调用这个方法:
var x="<client><nomCl>Taarit</nomCl><prenomCl>Aymen</prenomCl><emailCl>aymen.taarit@gmail.com</emailCl><numTel>222</numTel><long_>1.66</long_></client>";
$.ajax({
url: 'http://localhost:9080/FournisseurWeb/jaxrs/clients/cl',
type: 'post',
scriptCharset: "utf-8" ,
dataType:"xml",
data: x,
success: function(data, status) {
console.log(data);
}
});
这是一个使用跨域的 ajax POST 的 jax-rs 调用,所以希望它有所帮助:)
注意:没有 JSONP 的跨域调用在这里是合法的,因为服务器返回了以下标头,它启用了跨域 AJAX!
builder.header("Access-Control-Allow-Origin", "*");
有关更多详细信息,请参阅Access-Control-Allow-Origin 上的 Mozilla 开发人员中心页面。