By GokiSoft.com|
19:34 23/09/2020|
Java Web + WebService
[Share Code] Tạo dự án Web Service + App Client - WS - Web Service
Web Service
#persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="WebServiceExamplePU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>entity.Student</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/student_mgr?serverTimezone=UTC"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value=""/>
</properties>
</persistence-unit>
</persistence>
#Student.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Diep
*/
@Entity
@Table(name = "student")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Student.findAll", query = "SELECT s FROM Student s")
, @NamedQuery(name = "Student.findByRollno", query = "SELECT s FROM Student s WHERE s.rollno = :rollno")
, @NamedQuery(name = "Student.findByFullname", query = "SELECT s FROM Student s WHERE s.fullname = :fullname")
, @NamedQuery(name = "Student.findByEmail", query = "SELECT s FROM Student s WHERE s.email = :email")
, @NamedQuery(name = "Student.findByAddress", query = "SELECT s FROM Student s WHERE s.address = :address")
, @NamedQuery(name = "Student.findByBirthday", query = "SELECT s FROM Student s WHERE s.birthday = :birthday")})
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 20)
@Column(name = "rollno")
private String rollno;
@Size(max = 50)
@Column(name = "fullname")
private String fullname;
// @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
@Size(max = 150)
@Column(name = "email")
private String email;
@Size(max = 200)
@Column(name = "address")
private String address;
@Column(name = "birthday")
@Temporal(TemporalType.DATE)
private Date birthday;
public Student() {
}
public Student(String rollno) {
this.rollno = rollno;
}
public String getRollno() {
return rollno;
}
public void setRollno(String rollno) {
this.rollno = rollno;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public int hashCode() {
int hash = 0;
hash += (rollno != null ? rollno.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Student)) {
return false;
}
Student other = (Student) object;
if ((this.rollno == null && other.rollno != null) || (this.rollno != null && !this.rollno.equals(other.rollno))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entity.Student[ rollno=" + rollno + " ]";
}
}
#CalculatorWS.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ws;
import javax.jws.WebService;
import javax.jws.WebMethod;
/**
*
* @author Diep
*/
@WebService(serviceName = "CalculatorWS")
public class CalculatorWS {
@WebMethod
public float cong(float x, float y) {
return x + y;
}
@WebMethod
public float tru(float x, float y) {
return x - y;
}
@WebMethod
public float nhan(float x, float y) {
return x * y;
}
@WebMethod
public float chia(float x, float y) throws Exception {
if(y == 0) {
throw new Exception("Error >> devided by zero");
}
return x/y;
}
}
#CalculatorWSPort.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ws;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
/**
* REST Web Service
*
* @author Diep
*/
@Path("calculatorwsport")
public class CalculatorWSPort {
private ws_client.CalculatorWS port;
@Context
private UriInfo context;
/**
* Creates a new instance of CalculatorWSPort
*/
public CalculatorWSPort() {
port = getPort();
}
/**
* Invokes the SOAP method chia
* @param arg0 resource URI parameter
* @param arg1 resource URI parameter
* @return an instance of java.lang.String
*/
@GET
@Produces("text/plain")
@Consumes("text/plain")
@Path("chia/")
public String getChia(@QueryParam("arg0")
@DefaultValue("0.0") float arg0, @QueryParam("arg1")
@DefaultValue("0.0") float arg1) {
try {
// Call Web Service Operation
if (port != null) {
float result = port.chia(arg0, arg1);
return new java.lang.Float(result).toString();
}
} catch (Exception ex) {
// TODO handle custom exceptions here
}
return null;
}
/**
* Invokes the SOAP method tru
* @param arg0 resource URI parameter
* @param arg1 resource URI parameter
* @return an instance of java.lang.String
*/
@GET
@Produces("text/plain")
@Consumes("text/plain")
@Path("tru/")
public String getTru(@QueryParam("arg0")
@DefaultValue("0.0") float arg0, @QueryParam("arg1")
@DefaultValue("0.0") float arg1) {
try {
// Call Web Service Operation
if (port != null) {
float result = port.tru(arg0, arg1);
return new java.lang.Float(result).toString();
}
} catch (Exception ex) {
// TODO handle custom exceptions here
}
return null;
}
/**
* Invokes the SOAP method nhan
* @param arg0 resource URI parameter
* @param arg1 resource URI parameter
* @return an instance of java.lang.String
*/
@GET
@Produces("text/plain")
@Consumes("text/plain")
@Path("nhan/")
public String getNhan(@QueryParam("arg0")
@DefaultValue("0.0") float arg0, @QueryParam("arg1")
@DefaultValue("0.0") float arg1) {
try {
// Call Web Service Operation
if (port != null) {
float result = port.nhan(arg0, arg1);
return new java.lang.Float(result).toString();
}
} catch (Exception ex) {
// TODO handle custom exceptions here
}
return null;
}
/**
* Invokes the SOAP method cong
* @param arg0 resource URI parameter
* @param arg1 resource URI parameter
* @return an instance of java.lang.String
*/
@GET
@Produces("text/plain")
@Consumes("text/plain")
@Path("cong/")
public String getCong(@QueryParam("arg0")
@DefaultValue("0.0") float arg0, @QueryParam("arg1")
@DefaultValue("0.0") float arg1) {
try {
// Call Web Service Operation
if (port != null) {
float result = port.cong(arg0, arg1);
return new java.lang.Float(result).toString();
}
} catch (Exception ex) {
// TODO handle custom exceptions here
}
return null;
}
/**
*
*/
private ws_client.CalculatorWS getPort() {
try {
// Call Web Service Operation
ws_client.CalculatorWS_Service service = new ws_client.CalculatorWS_Service();
ws_client.CalculatorWS p = service.getCalculatorWSPort();
return p;
} catch (Exception ex) {
// TODO handle custom exceptions here
}
return null;
}
}
#StudentWS.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ws;
import entity.Student;
import java.util.List;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
/**
*
* @author Diep
*/
@WebService(serviceName = "StudentWS")
public class StudentWS {
@WebMethod
public List<Student> findAll() {
//open connection
EntityManagerFactory factory = Persistence.createEntityManagerFactory("WebServiceExamplePU");
EntityManager em = factory.createEntityManager();
Query q = em.createNamedQuery("Student.findAll", Student.class);
return q.getResultList();
}
@WebMethod
public Student findById(String rollno) {
//open connection
EntityManagerFactory factory = Persistence.createEntityManagerFactory("WebServiceExamplePU");
EntityManager em = factory.createEntityManager();
Student std = em.find(Student.class, rollno);
return std;
}
@WebMethod
public String save(Student std) {
//open connection
EntityManagerFactory factory = Persistence.createEntityManagerFactory("WebServiceExamplePU");
EntityManager em = factory.createEntityManager();
Student stdFind = em.find(Student.class, std.getRollno());
if(stdFind != null) {
//update data
em.getTransaction().begin();
stdFind.setAddress(std.getAddress());
stdFind.setBirthday(std.getBirthday());
stdFind.setEmail(std.getEmail());
stdFind.setFullname(std.getFullname());
em.getTransaction().commit();
} else {
//insert data
em.getTransaction().begin();
em.persist(std);
em.getTransaction().commit();
}
return "Success";
}
@WebMethod
public String remove(String rollno) {
//open connection
EntityManagerFactory factory = Persistence.createEntityManagerFactory("WebServiceExamplePU");
EntityManager em = factory.createEntityManager();
Student stdFind = em.find(Student.class, rollno);
em.getTransaction().begin();
em.remove(stdFind);
em.getTransaction().commit();
return "success";
}
}
#StudentWSPort.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ws;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;
import ws_client1.Student;
import javax.xml.namespace.QName;
import ws_client1.FindAllResponse;
import ws_client1.StudentWS;
/**
* REST Web Service
*
* @author Diep
*/
@Path("studentwsport")
public class StudentWSPort {
private StudentWS port;
@Context
private UriInfo context;
/**
* Creates a new instance of StudentWSPort
*/
public StudentWSPort() {
port = getPort();
}
/**
* Invokes the SOAP method remove
* @param arg0 resource URI parameter
* @return an instance of java.lang.String
*/
@GET
@Produces("text/plain")
@Consumes("text/plain")
@Path("remove/")
public String getRemove(@QueryParam("arg0") String arg0) {
try {
// Call Web Service Operation
if (port != null) {
java.lang.String result = port.remove(arg0);
return result;
}
} catch (Exception ex) {
// TODO handle custom exceptions here
}
return null;
}
/**
* Invokes the SOAP method save
* @param arg0 resource URI parameter
* @return an instance of java.lang.String
*/
@POST
@Produces("text/plain")
@Consumes("application/xml")
@Path("save/")
public String postSave(JAXBElement<Student> arg0) {
try {
// Call Web Service Operation
if (port != null) {
java.lang.String result = port.save(arg0.getValue());
return result;
}
} catch (Exception ex) {
// TODO handle custom exceptions here
}
return null;
}
/**
* Invokes the SOAP method findAll
* @return an instance of javax.xml.bind.JAXBElement<ws_client1.FindAllResponse>
*/
@GET
@Produces("application/xml")
@Consumes("text/plain")
@Path("findall/")
public JAXBElement<FindAllResponse> getFindAll() {
try {
// Call Web Service Operation
if (port != null) {
java.util.List<ws_client1.Student> result = port.findAll();
class FindAllResponse_1 extends ws_client1.FindAllResponse {
FindAllResponse_1(java.util.List<ws_client1.Student> _return) {
this._return = _return;
}
}
ws_client1.FindAllResponse response = new FindAllResponse_1(result);
return new ws_client1.ObjectFactory().createFindAllResponse(response);
}
} catch (Exception ex) {
// TODO handle custom exceptions here
}
return null;
}
/**
* Invokes the SOAP method findById
* @param arg0 resource URI parameter
* @return an instance of javax.xml.bind.JAXBElement<ws_client1.Student>
*/
@GET
@Produces("application/xml")
@Consumes("text/plain")
@Path("findbyid/")
public JAXBElement<Student> getFindById(@QueryParam("arg0") String arg0) {
try {
// Call Web Service Operation
if (port != null) {
ws_client1.Student result = port.findById(arg0);
return new JAXBElement<ws_client1.Student>(new QName("http//ws_client1/", "student"), ws_client1.Student.class, result);
}
} catch (Exception ex) {
// TODO handle custom exceptions here
}
return null;
}
/**
*
*/
private StudentWS getPort() {
try {
// Call Web Service Operation
ws_client1.StudentWS_Service service = new ws_client1.StudentWS_Service();
ws_client1.StudentWS p = service.getStudentWSPort();
return p;
} catch (Exception ex) {
// TODO handle custom exceptions here
}
return null;
}
}
APP CLIENT
#CalculatorAPI.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package aptech;
import ws.Exception_Exception;
/**
*
* @author Diep
*/
public class CalculatorAPI {
public static float cong(float arg0, float arg1) {
ws.CalculatorWS_Service service = new ws.CalculatorWS_Service();
ws.CalculatorWS port = service.getCalculatorWSPort();
return port.cong(arg0, arg1);
}
public static float tru(float arg0, float arg1) {
ws.CalculatorWS_Service service = new ws.CalculatorWS_Service();
ws.CalculatorWS port = service.getCalculatorWSPort();
return port.tru(arg0, arg1);
}
public static float nhan(float arg0, float arg1) {
ws.CalculatorWS_Service service = new ws.CalculatorWS_Service();
ws.CalculatorWS port = service.getCalculatorWSPort();
return port.nhan(arg0, arg1);
}
public static float chia(float arg0, float arg1) throws Exception_Exception {
ws.CalculatorWS_Service service = new ws.CalculatorWS_Service();
ws.CalculatorWS port = service.getCalculatorWSPort();
return port.chia(arg0, arg1);
}
}
#Main.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package aptech;
import java.util.Scanner;
import ws.Exception_Exception;
/**
*
* @author Diep
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception_Exception {
// TODO code application logic here
Scanner scan = new Scanner(System.in);
int choose;
float x, y, result = 0;
do {
showMenu();
choose = scan.nextInt();
System.out.println("Nhap x: ");
x = scan.nextFloat();
System.out.println("Nhap y: ");
y = scan.nextFloat();
switch(choose) {
case 1:
result = CalculatorAPI.cong(x, y);
break;
case 2:
result = CalculatorAPI.tru(x, y);
break;
case 3:
result = CalculatorAPI.nhan(x, y);
break;
case 4:
result = CalculatorAPI.chia(x, y);
break;
case 5:
System.out.println("Thoat!!!");
break;
default:
System.out.println("Failed!!!");
break;
}
System.out.println("Result: " + result);
} while(choose != 5);
}
static void showMenu() {
System.out.println("1. Cong");
System.out.println("2. Tru");
System.out.println("3. Nhan");
System.out.println("4. Chia");
System.out.println("5. Thoat");
System.out.println("Chon: ");
}
}
#StudentAPI.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package aptech;
import ws.Student;
/**
*
* @author Diep
*/
public class StudentAPI {
public static java.util.List<ws.Student> findAll() {
ws.StudentWS_Service service = new ws.StudentWS_Service();
ws.StudentWS port = service.getStudentWSPort();
return port.findAll();
}
public static Student findById(java.lang.String arg0) {
ws.StudentWS_Service service = new ws.StudentWS_Service();
ws.StudentWS port = service.getStudentWSPort();
return port.findById(arg0);
}
public static String save(ws.Student arg0) {
ws.StudentWS_Service service = new ws.StudentWS_Service();
ws.StudentWS port = service.getStudentWSPort();
return port.save(arg0);
}
public static String remove(java.lang.String arg0) {
ws.StudentWS_Service service = new ws.StudentWS_Service();
ws.StudentWS port = service.getStudentWSPort();
return port.remove(arg0);
}
}
#StudentFrame.form
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.3" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JFrameFormInfo">
<Properties>
<Property name="defaultCloseOperation" type="int" value="3"/>
</Properties>
<SyntheticProperties>
<SyntheticProperty name="formSizePolicy" type="int" value="1"/>
<SyntheticProperty name="generateCenter" type="boolean" value="false"/>
</SyntheticProperties>
<AuxValues>
<AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
</AuxValues>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<EmptySpace min="0" pref="530" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<EmptySpace min="0" pref="474" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
</Layout>
</Form>
#StudentFrame.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package aptech;
/**
*
* @author Diep
*/
public class StudentFrame extends javax.swing.JFrame {
/**
* Creates new form StudentFrame
*/
public StudentFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 530, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 474, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new StudentFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)