Over a million developers have joined DZone.

Combine JaxRS 2.0 Rest Client, Java FX 2, Spring MVC and Hibernate

· Java Zone

Learn more about how the Java language, tools and frameworks have been the foundation of countless enterprise systems, brought to you in partnership with Salesforce.

Today I want to share with you a sample application that runs in accordance with RESTful styles and includes server and client side technologies. Just before showing the content of the application, I want to talk about server and client side technologies in the application running.

Server side ones

  • Spring MVC 3.1 (For Restful server service)
  • Hibernate 4 (To make the data persistent with ORM)

Client side ones

  • Java FX 2 (For visual user interface)
  • JaxRS 2 – Rest Client (For the management of http requests to Restful server)

After introducing the technologies, let’s get to work on the server side in the first stage. Because the application on the server side is a Maven application, it can be run on every desired IDE environment. You can take a look at the picture below in order to get to know the components inside the server application.

spring-mvc-rest

1) Book.java

@Entity
@XmlRootElement
public class Book implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private Double price;

    public Book(){}

    public Book(String name, Double price) {
        this.name = name;
        this.price = price;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }


}

Book entity object (defined by @Entity) is a classic Java object that will be made permanent to database, will be read, edited and deleted. According to JAXB standard, if a converting from a Java object to XML object is required (the opposite one is also valid Java <> XML), the converted class must be wrapped with @XmlRootElement annotation in its simplest form.

2) BookWrapper.java

@XmlRootElement
public class BookWrapper implements Serializable {

    private List<Book> bookList;

    public List<Book> getBookList() {
        return bookList;
    }

    public void setBookList(List<Book> bookList) {
        this.bookList = bookList;
    }

    public BookWrapper(List<Book> bookList) {
        this.bookList = bookList;
    }

    public BookWrapper() {
    }
}

BookWrapper class acts as a class that wraps more than one book object. The only purpose of it is to allow the converting of List interface type objects to XML or JSON format easily.

3) MvcInitializer.java

public class MvcInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext servletContext) throws ServletException {

        AnnotationConfigWebApplicationContext mvcContext= new AnnotationConfigWebApplicationContext();
        mvcContext.register(WebConfig.class);

        ServletRegistration.Dynamic register=
                servletContext.addServlet("distpatcher", new DispatcherServlet(mvcContext));
        register.addMapping("/*");
        register.setLoadOnStartup(1);

    }
}

When we look to the image that is server application oriented, you can see web.xml transport configurator is not included in the project directory. Well, how can Spring MVC Context run without web.xml configurator?

The answer is based on Servlet 3.0 standard. With Servlet 3.0 standard, the dependence to web.xml transport configurator is completely removed.

When Servlet 3.0 container is run for the first time, if there is a class implements the ServletContainerInitializer interface in the CLASSPATH of the application, onStartup(..)method of that class is run automatically and definition and similar operations such as Servlet, Filter, Listener can be done within this method as can be done in web.xml.

In order to facilitate the work done in Spring Framework, WebApplicationInitializer interface that is managed by SpringServletContainerInitializer class is presented to us in terms of the configuration of Spring container easily.

XML based configuration files where Spring objects are defined, linked to each other and configured are not necessary anymore with the Spring Framework 3.1 version. Because it is possible now to make XML independent Spring Context configuration by the version 3.1. At this point, I prefer to use this method in order to show the web.xml and spring-beans.xml(name can vary) independent configuration as well.

In short, the above procedure includes creating Spring web context and defining Spring context configuration class namely WebConfig and defining the DispatcherServlet which one is the integral part of Spring MVC. We can say that this class is the conjugate of web.xml transport configurator.

4) WebConfig.java

@Configuration // This is a Spring config class
@EnableTransactionManagement // As <tx:annotation-config />
@EnableWebMvc  // As <mvc:component-scan .. />
@ComponentScan(basePackages = "com.kodcu") // As <context:component-scan ../>
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    // Injectible Transaction Manager Bean
    public HibernateTransactionManager createTransactionManager(){

       HibernateTransactionManager transactionManager=new HibernateTransactionManager();
       transactionManager
        .setSessionFactory(createSessionFactoryBean().getObject());

        return transactionManager;

    }

    @Bean
    // Injectible Hibernate SessionFactory Bean
    public LocalSessionFactoryBean createSessionFactoryBean(){
        LocalSessionFactoryBean localSessionFactoryBean=new LocalSessionFactoryBean();
        Properties properties=new Properties();
        properties.setProperty("hibernate.dialect"
              ,"org.hibernate.dialect.MySQL5InnoDBDialect");
        properties.setProperty("hibernate.hbm2ddl.auto","create");
        properties.setProperty("hibernate.show_sql","true");
        localSessionFactoryBean.setHibernateProperties(properties);
        localSessionFactoryBean.setAnnotatedClasses(new Class<?>[]{Book.class});
        localSessionFactoryBean.setDataSource(createDataSource());
        return localSessionFactoryBean;
    }

    @Bean
    // Injectible DataSource Bean
    public BasicDataSource createDataSource(){
        BasicDataSource dataSource=new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/fxdb");
        dataSource.setUsername("root");
        dataSource.setPassword("root");

        return dataSource;
    }
       
}

Today, there is a tendency to annotation based configuration operations rather than XML based configurators. Actually, there is no answer about which method is better. Choosing depends on the appreciation of developer.

When you look to the above WebConfig.java configuration class, you can see that this class is a conjugate of XML based Spring configuration files.

To illustrate:

Defining a method that returns a BasicDataSource type object instead of <bean id=”..” class=”com. apache….BasicDataSource” >…</bean> definition and applying @Bean annotation to this method have the same function.

5) PublisherController.java

@Transactional(readOnly = true)
@Repository  // Spring DAO
@Controller  // Spring MVC Controller
@RequestMapping(value = "/publisher/*")
public class PublisherController {

    @Autowired
    // SessionFactory injection
    private SessionFactory sessionFactory;

    // Gets current Session object
    public Session  getSession(){
        return sessionFactory.getCurrentSession();
    }

    @RequestMapping(value = "/book",
            method = RequestMethod.POST,
            produces = {MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_XML_VALUE },
            consumes = {MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_XML_VALUE })
    @Transactional(readOnly = false)
    public @ResponseBody Long saveBook(@RequestBody Book book) {

     return (Long)getSession().save(book);

    }

    @RequestMapping(value = "/book/{id}", method = RequestMethod.DELETE)
    @Transactional(readOnly = false)
    public void removeBook(@PathVariable Long id) {

      getSession().delete(getSession().get(Book.class,id));

    }

    @RequestMapping(value = "/books",produces = {MediaType.APPLICATION_XML_VALUE},method = RequestMethod.GET)
    @ResponseStatus( HttpStatus.OK )
    public @ResponseBody
    BookWrapper allBooks() {

        List<Book> bookList= (List<Book>)getSession().createQuery("SELECT b FROM Book b").list();

      return new BookWrapper(bookList) ;

    }

    @RequestMapping(value = "/book",
            method = RequestMethod.PUT,
            consumes = {MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_XML_VALUE })
    @Transactional(readOnly = false)
    public void updateBook(@RequestBody Book book) {
        getSession().saveOrUpdate(book);
    }
}

PublisherController class is a DAO (Data Access Object)that is assigned as a @Controllerclass in which each method is Transaction supported (by means of @Transactional) and also belongs to Spring MVC.

@RequestMapping annotation is an useful Spring MVC annotation that takes charge as a combination of some annotations such as @Path, @GET, @POST, @PUT, @Produces,@Consumes located in JAX-RS standard and also this annotation directs the URL -> Resource access.

@RequestBody and @ResponseBody annotations allow the data beams that are sent to method and output from the method to be output by Spring MVC as meaningful data and these annotations also enable the type converting (such as Java <> XML or Java <> JSON etc) in the background if it is necessary.

@PathVariable annotation sorts out the variables from URL components and then transfers this value to the variable within the method parameter.

Operations such as making database permanent, updating, deleting, and reading can be done by various methods (like saveOrUpdate, delete etc) of Hibernate Session object.

After explaining the overall architecture of the server application, we can go into the details of client side components.

RESTful web services can be accessed with any tool manages the HTTP requests, programming language or software. JAX-RS 1.1 standard allows you to write RESTful web services in Java programming language. But there is not any client tool which manages HTTP requests easily in JAX-RS 1.1 version. For this reason, in JAX-RS 2 standard that will take place in Java EE 7, a new library, namely RESTful client is going to be added. This REST client library is accessible and usable with the help of current studies.

You can access to JAX-RS 2.0 reference implementation library from this http://repo1.maven.org/maven2/org/glassfish/jersey/bundles/jax-rs-ri/ address and then use it.

In order to create a RESTful client with JAX-RS 2.0, a client object can be obtained by Clientclient= ClientFactory.newClient(); call. Through this object, HTTP requests which are in accordance with RESTful style can be made, data (REST Entity) can be post on HTTP request, information like HTTP header, body can be obtained from returned response. The usage of this library is really convenient and easy due to the Builder design pattern.

Now, if you want, we can test how to perform method accesses to Spring MVC RESTful services which is on the server side by the implementer library of JAX-RS 2.0 standard.

1) HTTP DELETE – http://localhost:8080/rest/publisher/book/{ID}

Response response = client
        .target("http://localhost:8080/rest/") // ROOT_URL
        .path("publisher") // publisher resource
        .path("book") // book resource
        .path(String.valueOf(fxBook.getId())) // ID parameter
        .request() // HTTP request
        .delete();  // HTTP DELETE method

2) HTTP POST – http://localhost:8080/rest/publisher/book

Book book = new Book();
book.setName(nameField.getText());
book.setPrice(Double.parseDouble(priceField.getText()));

// REST Entity object that will be converted to XML type 
Entity<Book> kitapEntity = Entity.entity(book, MediaType.APPLICATION_XML);
Response response = client
        .target(REST_ROOT_URL) // ROOT_URL
        .path("publisher") // Publisher resource
        .path("book")  // book resource
        .request() // HTTP request
        .post(kitapEntity); // REST Entity object is being sent to the server

3) HTTP GET – http://localhost:8080/rest/publisher/book

Response response = client
        .target("http://localhost:8080/rest/")
        .path("publisher")
        .path("books")
        .request(MediaType.APPLICATION_XML) // Request the data as JSON
        .get(); // HTTP GET request is being made

// REST entity object that comes from the server is being obtained.
BookWrapper bookWrapper = response.readEntity(BookWrapper.class);

4) HTTP PUT – http://localhost:8080/rest/publisher/book

Entity<Book> kitapEntity = Entity.entity(book, MediaType.APPLICATION_XML);

Response response = client
        .target(REST_ROOT_URL)
        .path("publisher")
        .path("book")
        .request()
        .put(kitapEntity); // REST Entity object is being sent to the server.

You can access and use Spring MVC RESTful service with a simple command line application as well as above examples. But visual applications make more sense in human mind. I want to share with you a simple Java FX application in project codes in order to support this idea. The visual components of JavaFX application was created with JavaFX Scene Builder tool in FXML Standard. You can also see details clearly by opening FXML component file in the Project together with Scene Builder tool.

javafx-rest

You can access to source codes in the following blog post. 

Hope to see you again..

Discover how the Force.com Web Services Connector (WSC) is a code-generation tool and runtime library for use with Force.com Web services, brought to you in partnership with Salesforce.

Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}