Jun 27, 2013
Jun 25, 2013
The best tutorial - Hibernate Many-to-Many example (XML Mapping)
Tools and technologies used in this tutorials :
File : pom.xml
Table STOCK_CATEGORY only consist of two primary keys, and also foreign key reference back to STOCK and CATEGORY.
MySQL table scripts
File : Stock.java
File : Category.java
File : Stock.hbm.xml
File : Category.hbm.xml
File : hibernate.cfg.xml
File : App.java
Output …result should be self-explanatory
- Hibernate 3.6.3.Final
- MySQL 5.1.15
- Maven 3.0.3
- Eclipse 3.6
Project Structure
Project structure of this tutorial.Project Dependency
Get latest hibernate.jar from JBoss repository.File : pom.xml
<project ...> <repositories> <repository> <id>JBoss repository</id> <url>http://repository.jboss.org/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <!-- MySQL database driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.15</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.6.3.Final</version> </dependency> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.12.1.GA</version> </dependency> </dependencies> </project>
1. “Many-to-many” example
This is a many-to-many relationship table design, a STOCK table has more than one CATEGORY, and CATEGORY can belong to more than one STOCK, the relationship is linked with a third table called STOCK_CATEGORY.Table STOCK_CATEGORY only consist of two primary keys, and also foreign key reference back to STOCK and CATEGORY.
CREATE TABLE `stock` ( `STOCK_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `STOCK_CODE` VARCHAR(10) NOT NULL, `STOCK_NAME` VARCHAR(20) NOT NULL, PRIMARY KEY (`STOCK_ID`) USING BTREE, UNIQUE KEY `UNI_STOCK_NAME` (`STOCK_NAME`), UNIQUE KEY `UNI_STOCK_ID` (`STOCK_CODE`) USING BTREE ) CREATE TABLE `category` ( `CATEGORY_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `NAME` VARCHAR(10) NOT NULL, `DESC` VARCHAR(255) NOT NULL, PRIMARY KEY (`CATEGORY_ID`) USING BTREE ) CREATE TABLE `stock_category` ( `STOCK_ID` INT(10) UNSIGNED NOT NULL, `CATEGORY_ID` INT(10) UNSIGNED NOT NULL, PRIMARY KEY (`STOCK_ID`,`CATEGORY_ID`), CONSTRAINT `FK_CATEGORY_ID` FOREIGN KEY (`CATEGORY_ID`) REFERENCES `category` (`CATEGORY_ID`), CONSTRAINT `FK_STOCK_ID` FOREIGN KEY (`STOCK_ID`) REFERENCES `stock` (`STOCK_ID`) )
2. Hibernate Model Class
Create two model classes รข€“Stock.java
and Category.java
, to represent the above tables. No need to create an extra class for table ‘stock_category‘.File : Stock.java
package com.mkyong.stock; import java.util.HashSet; import java.util.Set; public class Stock implements java.io.Serializable { private Integer stockId; private String stockCode; private String stockName; private Set<Category> categories = new HashSet<Category>(0); //getter, setter and constructor }
package com.mkyong.stock; import java.util.HashSet; import java.util.Set; public class Category implements java.io.Serializable { private Integer categoryId; private String name; private String desc; private Set<Stock> stocks = new HashSet<Stock>(0); //getter, setter and constructor }
3. Hibernate XML Mapping
Now, create two Hibernate mapping files (hbm) รข€“Stock.hbm.xml
and Category.hbm.xml
. You will noticed the third ‘stock_category‘ table is reference via “many-to-many” tag.File : Stock.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.mkyong.stock.Stock" table="stock" catalog="mkyongdb"> <id name="stockId" type="java.lang.Integer"> <column name="STOCK_ID" /> <generator class="identity" /> </id> <property name="stockCode" type="string"> <column name="STOCK_CODE" length="10" not-null="true" unique="true" /> </property> <property name="stockName" type="string"> <column name="STOCK_NAME" length="20" not-null="true" unique="true" /> </property> <set name="categories" table="stock_category" inverse="false" lazy="true" fetch="select" cascade="all" > <key> <column name="STOCK_ID" not-null="true" /> </key> <many-to-many entity-name="com.mkyong.stock.Category"> <column name="CATEGORY_ID" not-null="true" /> </many-to-many> </set> </class> </hibernate-mapping>
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.mkyong.stock.Category" table="category" catalog="mkyongdb"> <id name="categoryId" type="java.lang.Integer"> <column name="CATEGORY_ID" /> <generator class="identity" /> </id> <property name="name" type="string"> <column name="NAME" length="10" not-null="true" /> </property> <property name="desc" type="string"> <column name="[DESC]" not-null="true" /> </property> <set name="stocks" table="stock_category" inverse="true" lazy="true" fetch="select"> <key> <column name="CATEGORY_ID" not-null="true" /> </key> <many-to-many entity-name="com.mkyong.stock.Stock"> <column name="STOCK_ID" not-null="true" /> </many-to-many> </set> </class> </hibernate-mapping>
4. Hibernate Configuration File
Now, putsStock.hbm.xml
and Category.hbm.xml
and MySQL detail in hibernate.cfg.xml
.File : hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyongdb</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <mapping resource="com/mkyong/stock/Stock.hbm.xml" /> <mapping resource="com/mkyong/stock/Category.hbm.xml" /> </session-factory> </hibernate-configuration>
5. Run It
Run it, Hibernate will insert a record into the STOCK table, two records into the CATEGORY table, and also two records into the STOCK)CATEGORY table.File : App.java
package com.mkyong; import java.util.HashSet; import java.util.Set; import org.hibernate.Session; import com.mkyong.stock.Category; import com.mkyong.stock.Stock; import com.mkyong.util.HibernateUtil; public class App { public static void main(String[] args) { System.out.println("Hibernate many to many (XML Mapping)"); Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Stock stock = new Stock(); stock.setStockCode("7052"); stock.setStockName("PADINI"); Category category1 = new Category("CONSUMER", "CONSUMER COMPANY"); Category category2 = new Category("INVESTMENT", "INVESTMENT COMPANY"); Set<Category> categories = new HashSet<Category>(); categories.add(category1); categories.add(category2); stock.setCategories(categories); session.save(stock); session.getTransaction().commit(); System.out.println("Done"); } }
Hibernate many TO many (XML Mapping) Hibernate: INSERT INTO mkyongdb.stock (STOCK_CODE, STOCK_NAME) VALUES (?, ?) Hibernate: INSERT INTO mkyongdb.category (NAME, `DESC`) VALUES (?, ?) Hibernate: INSERT INTO mkyongdb.category (NAME, `DESC`) VALUES (?, ?) Hibernate: INSERT INTO stock_category (STOCK_ID, CATEGORY_ID) VALUES (?, ?) Hibernate: INSERT INTO stock_category (STOCK_ID, CATEGORY_ID) VALUES (?, ?) Done
(Source: Internet)
The best tutorial - Hibernate Many-to-Many example (Annotation)
See previous post for dependency jar files
Project Structure
Review the new project structure of this tutorial.1. “Many-to-many” table relationship
2. Hibernate Model Class
Update previous model classes –Stock.java
and Category.java
, and define new annotation code inside.File : Stock.java
package com.mkyong.stock; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.CascadeType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; @Entity @Table(name = "stock", catalog = "mkyongdb", uniqueConstraints = { @UniqueConstraint(columnNames = "STOCK_NAME"), @UniqueConstraint(columnNames = "STOCK_CODE") }) public class Stock implements java.io.Serializable { private Integer stockId; private String stockCode; private String stockName; private Set<Category> categories = new HashSet<Category>(0); public Stock() { } public Stock(String stockCode, String stockName) { this.stockCode = stockCode; this.stockName = stockName; } public Stock(String stockCode, String stockName, Set<Category> categories) { this.stockCode = stockCode; this.stockName = stockName; this.categories = categories; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "STOCK_ID", unique = true, nullable = false) public Integer getStockId() { return this.stockId; } public void setStockId(Integer stockId) { this.stockId = stockId; } @Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10) public String getStockCode() { return this.stockCode; } public void setStockCode(String stockCode) { this.stockCode = stockCode; } @Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20) public String getStockName() { return this.stockName; } public void setStockName(String stockName) { this.stockName = stockName; } @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinTable(name = "stock_category", catalog = "mkyongdb", joinColumns = { @JoinColumn(name = "STOCK_ID", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "CATEGORY_ID", nullable = false, updatable = false) }) public Set<Category> getCategories() { return this.categories; } public void setCategories(Set<Category> categories) { this.categories = categories; } }
package com.mkyong.stock; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name = "category", catalog = "mkyongdb") public class Category implements java.io.Serializable { private Integer categoryId; private String name; private String desc; private Set<Stock> stocks = new HashSet<Stock>(0); public Category() { } public Category(String name, String desc) { this.name = name; this.desc = desc; } public Category(String name, String desc, Set<Stock> stocks) { this.name = name; this.desc = desc; this.stocks = stocks; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "CATEGORY_ID", unique = true, nullable = false) public Integer getCategoryId() { return this.categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } @Column(name = "NAME", nullable = false, length = 10) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "[DESC]", nullable = false) public String getDesc() { return this.desc; } public void setDesc(String desc) { this.desc = desc; } @ManyToMany(fetch = FetchType.LAZY, mappedBy = "categories") public Set<Stock> getStocks() { return this.stocks; } public void setStocks(Set<Stock> stocks) { this.stocks = stocks; } }
3. Hibernate Configuration File
Puts annotated classesStock.java
and Category.java
in hibernate.cfg.xml
like this :File : hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyongdb</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show_sql">true</property> <mapping class="com.mkyong.stock.Stock" /> <mapping class="com.mkyong.stock.Category" /> </session-factory> </hibernate-configuration>
4. Run It
Run it, the result is self-explanatory.File : App.java
package com.mkyong.util;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.mkyong.stock.Category;
import com.mkyong.stock.Stock;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class App {
private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;
public static void main(String[] args) {
try {
Configuration configuration = new Configuration();
configuration.configure().setProperty("hibernate.show_sql", "false");
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
factory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
System.out.println("**Example : Hibernate 4 SessionFactory**");
System.out.println("----------------------------------------");
System.out.println("Hibernate many to many (Annotation)");
Session session = factory.openSession();
//Add data into tables
add(session);
//Query data from tables
query(session);
session.close();
System.out.println("Done");
}//End of main
@SuppressWarnings("rawtypes")
private static void query(Session session) {
Transaction tx = null;
try {
tx = session.beginTransaction();
List employees = session.createQuery("FROM Stock").list();
for (Iterator iterator = employees.iterator(); iterator.hasNext();) {
Stock stock = (Stock) iterator.next();
System.out.println("Code: " + stock.getStockCode());
System.out.println("Name: " + stock.getStockName());
}
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
}
}
private static void add(Session session) {
Transaction tx = null;
try {
tx = session.beginTransaction();
Stock stock = new Stock();
stock.setStockCode("7052");
stock.setStockName("PADINI");
Category category1 = new Category("CONSUMER", "CONSUMER COMPANY");
Category category2 = new Category("INVESTMENT", "INVESTMENT COMPANY");
Set<Category> categories = new HashSet<Category>();
categories.add(category1);
categories.add(category2);
stock.setCategories(categories);
session.save(stock);
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
}
}
}
(Source: Internet)
The best tutorial - Developing REST Web Services
1. IntroductionThis document will outline the process of developing a REST web service, deploying it to the internal MyEclipse Tomcat server and testing it with the REST Web Services Explorer. The REST features in MyEclipse are based on Jersey, which is the reference implementation for JAX-RS, the Java API for RESTful Web Services. We will be creating a simple web service which we will use to maintain a list of customers.MyEclipse also supports developing SOAP web services using JAX-WS; for folks needing to develop and deploy WebSphere JAX-RPC or WebSphere JAX-WS web services, please take a look at MyEclipse Blue Edition. Additional resources covering web service creation using JAX-WS and JAX-RPC are included in the Resources section of this document. |
||||
2. System RequirementsThis tutorial was created with MyEclipse. However, if you notice portions of this tutorial looking different than the screens you are seeing, please let us know and we will make sure to resolve any inconsistencies. |
||||
3. Creating the REST Web Service ProjectTo get started we will create a simple Web Service Project by selecting Web Service Project from the new toolbar menu:Alternatively, invoke the wizard using File > New > Other > MyEclipse > Java Enterprise Projects > Web Service Project. Name the project restdemo and select REST (JAX-RS) from the list of frameworks. Click Next to move to page 2 of the wizard. On this page you can specify the path at which the services will be available, the name of the corresponding JAX-RS servlet and libraries which you wish to add to your project. For this project the defaults are fine, so click Finish to create the project. JAX-RS servlet generated in web.xml Note: Instead of creating a new project, you may also add REST capabilities to any existing Java EE 5 Web project. From the project's context menu, select MyEclipse > Add REST Capabilities... |
||||
4. Creating the REST Web Service
To start, create a simple Customer class with id, name and address
fields; this class represents the Customer entity we will be
managing with our web service. Use the
File > New > Class wizard, put Customer in the
Name field, com.myeclipseide.ws in the
Package field and Finish the wizard. Replace the
contents of the generated class with the following code:
|
package com.myeclipseide.ws;
|
In this tutorial, we will be using XML as the serialization format, i.e. we will send and receive Customer entities from the web service using XML.
The @XMLRootElement annotation on the Customer class is a JAXB annotation which allows JAXB to convert this entity from Java to XML and back. It is possible to annotate the fields and methods within the class to customize the serialization, but for our tutorial the JAXB defaults are fine.
4.2 Creating the CustomersResource class, the core of our web
service
-
Click the Add button again to add a method that will return
details of a specific customer.
-
The URL path field specifies the path at which this method can
be reached, relative to the containing resource.
In this case we specify {id}, which means this resource method can be reached at /customers/{id}. The curly braces denote a URI variable. These variables are substituted at runtime in order for a resource to respond to a request based on the substituted URI. - Click Add to add a method parameter which can be directly edited in the table. Since we need the value of the id variable, we use the PathParam annotation to map it to the cId parameter.
-
The URL path field specifies the path at which this method can
be reached, relative to the containing resource.
-
Select the restdemo project and invoke the new web service
wizard from the toolbar:
Make sure the Project combo displays the restdemo project and the REST (JAX-RS) framework is selected. Select Create new Java bean and click Next.
-
Fill out this page as shown in the following screenshot:
- The URL path field indicates the path at which this resource can be reached, for this tutorial, we will use customers as this resource manages our customer list. The resource will thus be hosted at "/customers".
- Singleton lifecycle ensures that only one instance of this class will created by Jersey per web-application.
- The Consumes and Produces combos can be used to specify the default mime type(s) of data which this resource can accept and generate. These values can be overridden by individual methods in the class. As mentioned above, we will be serializing to XML, so we use the application/xml mime type.
-
Click the
Add button in the above dialog to add the
method that will fetch a list of customers. Fill out the wizard
that pops up like so and click
Finish.
- The HTTP method combo can be used to specify what type of HTTP request this method will respond to; in this case, we wish to respond to an HTTP GET request.
- The Method Signature preview will be updated as you make changes to the page, giving you an idea of what your method will look like once generated.
-
Finally, add a method which allows us to add a new customer to
our list.
- In this case, we're responding to a POST request and expect application/xml input which would be deserialized into the customer parameter.
- The customer parameter is an Entity parameter (unannotated) and is mapped directly from the message body of the incoming request.
- We also override the default application/xml output specified by the CustomersResource class and specify text/html instead.
-
After adding those 3 methods, your wizard should now look like
this:
Click Finish to generate the CustomersResource class, you will see a class with stubbed out resource methods as shown below:
package com.myeclipseide.ws;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import com.sun.jersey.spi.resource.Singleton;
@Produces("application/xml")
@Path("customers")
@Singleton
public class CustomersResource {
@GET
public List<Customer> getCustomers() {
throw new UnsupportedOperationException("Not yet implemented.");
}
@GET
@Path("{id}")
public Customer getCustomer(@PathParam("id") int cId) {
throw new UnsupportedOperationException("Not yet implemented.");
}
@POST
@Path("add")
@Produces("text/plain")
@Consumes("application/xml")
public String addCustomer(Customer customer) {
throw new UnsupportedOperationException("Not yet implemented.");
}
} -
We must now provide implementations for the methods created by
the above wizard. In a real application, at this point we would
probably wire in a database using JPA or Hibernate to help
manage our customer list, but a simple in-memory map is
sufficient for this tutorial.
Our implementation is simple; when a customer is received by our service, we give the entity a counter based id and add it to our map. Retrieving a customer from this map by id and providing a list of customers is straightforward as you can see below. You may copy this implementation into your class; observe that the class and method signatures have not changed, all we're doing is fleshing out the generated stubs with an implementation of our service. We also add a single customer to the list for demonstration purposes.
package com.myeclipseide.ws;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import com.sun.jersey.spi.resource.Singleton;
@Produces("application/xml")
@Path("customers")
@Singleton
public class CustomersResource {
private TreeMap<Integer, Customer> customerMap = new TreeMap<Integer, Customer>();
public CustomersResource() {
// hardcode a single customer into the database for demonstration
// purposes
Customer customer = new Customer();
customer.setName("Harold Abernathy");
customer.setAddress("Sheffield, UK");
addCustomer(customer);
}
@GET
public List<Customer> getCustomers() {
List<Customer> customers = new ArrayList<Customer>();
customers.addAll(customerMap.values());
return customers;
}
@GET
@Path("{id}")
public Customer getCustomer(@PathParam("id") int cId) {
return customerMap.get(cId);
}
@POST
@Path("add")
@Produces("text/plain")
@Consumes("application/xml")
public String addCustomer(Customer customer) {
int id = customerMap.size();
customer.setId(id);
customerMap.put(id, customer);
return "Customer " + customer.getName() + " added with Id " + id;
}
}
Note: You can invoke the the JAX-RS Method
wizard directly for any class in a REST web service project by
using the Add REST Method... context menu action. Right-click in
the Java editor to bring up the context menu and select Add REST
Method... from the MyEclipse submenu.
5. Deploying & Testing the Web Service
5.1 Deploying & Running the restdemo Project
The fastest way to deploy our web service is to deploy our web
project using the
Run As or
Debug As action of
MyEclipse Server Application. We can do that by
right-clicking on our project, going down to
Debug As (or
Run As) and selecting
MyEclipse Server Application:
If you have multiple server connectors configured, MyEclipse will ask you which one you want to use, for the purpose of this tutorial select MyEclipse Tomcat. If you don't have any connectors configured, MyEclipse Tomcat will be used automatically for you to deploy your project to and then run.
Now MyEclipse will perform the following steps for you automatically:
- Package our web project, and deploy it in Exploded format to the application server
- Start the application server for us, loading our web project
5.2 Testing the Web Service with the REST Web Services Explorer
(PRO Only)
The easiest way to test our web service is to use the REST Web
Services explorer. Since the explorer is available only to
MyEclipse Professional subscribers, if you are MyEclipse Standard
subscriber, please follow the instructions in section 5.3.
-
Right-click the restdemo project and select Test with REST Web
Services Explorer from the MyEclipse submenu as shown below:
Note: If you deployed restdemo to an application server other than MyEclipse Tomcat, the WADL URL used in the explorer may contain an incorrect port, preventing the explorer from loading your WADL file. Correct the port and click the go button to proceed.
You may also open the REST Web Services Explorer using the drop down from the main eclipse toolbar. In this case, you need to manually enter the path of a WADL file in the address bar before proceeding.
-
Expand the customers node and select {id}. In the id field on
the right, enter 0 and click Test. In the Raw View
tab, observe the lone customer we have in our map being
returned in XML.
-
Let's add a customer to our list. Expand select add under the customers node. In the content area on the right, paste the
following and click Test:
<customer>
<name>Bill Adama</name>
<address>Vancouver, Canada</address>
</customer>
The response should now say: Customer Bill Adama added with Id 1
-
Select the customers node and click Test. The two customers in
our list are returned by the service in XML.
5.3 Testing the Web Service Using a Standard Browser
-
Open
http://localhost:8080/restdemo/services/customers/0
in your browser to see the first customer in XML.
-
To add a customer to our list, we need to send customer data to
the service via an HTTP POST request. You could use a Firefox
extension like
Poster to make the request as shown below.
-
Open
http://localhost:8080/restdemo/services/customers
in your browser to get a list of all customers in XML.
(Source: Internet)
Subscribe to:
Posts (Atom)