DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • An Overview of Programming Languages
  • How to Consume REST Web Service (GET/POST) in Java 11 or Above
  • Building REST API Backend Easily With Ballerina Language
  • Aggregating REST APIs Calls Using Apache Camel

Trending

  • Chaos Engineering for Microservices
  • The Modern Data Stack Is Overrated — Here’s What Works
  • Comparing SaaS vs. PaaS for Kafka and Flink Data Streaming
  • Building Scalable and Resilient Data Pipelines With Apache Airflow
  1. DZone
  2. Coding
  3. Languages
  4. Building a REST Service That Collects HTML Form Data Using Netbeans, Jersey, Apache Tomcat, and Java

Building a REST Service That Collects HTML Form Data Using Netbeans, Jersey, Apache Tomcat, and Java

By 
Chad Lung user avatar
Chad Lung
·
Jul. 13, 22 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
66.1K Views

Join the DZone community and get the full member experience.

Join For Free

The Jersey project is very well documented so it makes it easy to learn REST with Java. In this article I’m going to build two projects. The first project will be a very simple HTML page that presents a form to the user and then submits it to a REST project residing on the same server. The second project will be the REST part.

For this article I used the following tools:
1. Netbeans 7
2. Apache Tomcat 7
3. Jersey
4. Java

I built this on OS X Lion.

Go ahead and create a new Maven Web Application with Netbeans 7 called: MyForm

Once the project has been generated take the resulting (default) index.jsp file and delete it. In its place add a file called: index.html and add the following content to it:

 
<!DOCTYPE html>
<html>
    <head>
        <title>REST with Forms</title>
        <meta data-fr-http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <br />
        <form method="post" action="http://localhost:8080/RESTwithForms-1.0-SNAPSHOT/messages">
            Name: <input type="text" name="name" id="name" /><br />
            Message: <input type="text" name="message" id="message" /><br />
            Item 1: <input type="text" name="thelist" id="thelist" /><br />
            Item 2: <input type="text" name="thelist" id="thelist" /><br />
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>


Basically, I created a simple (ugly) form that takes a few parameters the user enters. They submit the form and the data is sent to the REST project we will soon be building. The idea here is we are using an HTTP POST to create a new message.

That’s it for the first project! With Netbean’s Maven integration do a Clean and Build and then deploy the resulting WAR file to Apache Tomcat.

Create another new Maven Web Application with Netbeans 7 called: RESTwithForms

Add two new Java classes to the new project:
1. MyApplication
2. MessageResource

The code for MyApplication.java is as follows:

 
package com.giantflyingsaucer;
 
import com.sun.jersey.api.core.PackagesResourceConfig;
import javax.ws.rs.ApplicationPath;
 
@ApplicationPath("/")
public class MyApplication extends PackagesResourceConfig {
 
    public MyApplication() {
        super("com.giantflyingsaucer");
    }
}


In a brief nutshell this code allows us to make use of some Servlet 3.0 goodies (we don’t need to create a web.xml file for this project as an example). For more details see the sections titled: Example 2.8. Reusing Jersey implementation in your custom application model and Example 2.9. Deployment of a JAX-RS application using @ApplicationPath with Servlet 3.0 at this link.

The real guts of the REST project are in the MessageResource.java file as seen below:

 
package com.giantflyingsaucer;
 
import java.net.URI;
import java.util.List;
import java.util.UUID;
 
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;
 
@Path("/messages")
public class MessageResource {
 
    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response createMessage(@FormParam("name") String name,
                                @FormParam("message") String message,
                                @FormParam("thelist") List<String> list) {
        if(name.trim().length() > 0 && message.trim().length() > 0 && !list.isEmpty()) {
            // Note 1: Normally you would persist the new message to a datastore
            // of some sort. I'm going to pretend I've done that and
            // use a unique id for it that obviously points to nothing in
            // this case.
            // Note 2: The way I'm returning the data should be more like the commented
            // out piece, I am being verbose for the sake of showing you how to
            // get the values and show that it was read.
            return Response.created(URI.create("/messages/" + String.valueOf(UUID.randomUUID()))).entity(
                    name+ ": " + message + " --> the items: " + list.get(0) + " - " + list.get(1)).build();
 
            // This is a more real world "return"
            //return Response.created(URI.create("/messages/" + String.valueOf(UUID.randomUUID()))).build();
        }
        return Response.status(Response.Status.PRECONDITION_FAILED).build();
    }
}


Note: Pay special attention to the comments. Please don’t email me stating I shouldn’t be returning text back with the values, also please don’t tell me I should be iterating the list, etc. this is just a demo. You will obviously do this differently in a production environment. The key here is simplicity and minimal code.

At this point you need to add jersey-server as a dependency in your POM file.

 
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-server-linking</artifactId>
    <version>1.9.1</version>
</dependency>


With Netbean’s Maven integration do a Clean and Build and then deploy the resulting WAR file to Apache Tomcat. You are now ready to test it out. Load up the HTML file from the first project and enter some data and then submit it.

If you have a tool like FireBug for Firefox, you can also see that an HTTP 201 was returned (if successful).

If you don’t enter any data in the form then you should get an HTTP 412 back.

With not much more work you could just as easily use something like jQuery and submit the form via AJAX.


REST Web Protocols Apache Tomcat HTML NetBeans Form (document) Data (computing) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • An Overview of Programming Languages
  • How to Consume REST Web Service (GET/POST) in Java 11 or Above
  • Building REST API Backend Easily With Ballerina Language
  • Aggregating REST APIs Calls Using Apache Camel

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!