Create a simple web application with Dropwizard

Create a simple web application with Dropwizard

This goal

--Create a simple web app --When you enter from the screen, it will return the input contents

Development environment

File implemented this time

  1. DropTestApplication.java
  2. DropTestConfiguration.java
  3. SampleResource.java
  4. index.html
  5. index.js
  6. config.yml
  7. pom.xml

Execution procedure

  1. Create maven project
  2. Create configuration file
  3. Create pom.xml
  4. Create config.yml
  5. Creating a core class for Dropwizard
  6. Create Configuration class
  7. Create Application class
  8. Create server-side socket
  9. Create SampleResource.java
  10. Screen creation
  11. Create index.html
  12. Create index.js
  13. Build
  14. Run

1. Create maven project

Using eclipse, right-click in the project explorer-> new-> project Maven → Maven Project → Click Next This time, check Create a simple project and click Next Enter any group Id (organization ID), artifact Id (identification ID, which will be the project name), check that the packaging is jar, and click Finish.

image.png

Depending on the settings of eclipse, the following package configuration will be completed.

image.png

2. Create configuration file

Here, specify the package to be used in maven in pom.xml, and set the application in config.yml.

2-1. Create pom.xml

Select and edit pom.xml created directly under the project. It is necessary to describe that dropwizard is used here, this time specify the necessary library and main class, and specify maven-shade assuming fat-jar at build time.

pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>priv.jp.y.suzuki</groupId>
  <artifactId>dropTest</artifactId>
  <version>0.0.1-SNAPSHOT</version>

<properties>
    <dropwizard.version>0.9.2</dropwizard.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>


  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>2.3</version>
        <configuration>
          <createDependencyReducedPom>true</createDependencyReducedPom>
          <filters>
            <filter>
              <artifact>*:*</artifact>
              <excludes>
                <exclude>META-INF/*.SF</exclude>
                <exclude>META-INF/*.DSA</exclude>
                <exclude>META-INF/*.RSA</exclude>
              </excludes>
            </filter>
          </filters>
        </configuration>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <transformers>
                <transformer
                  implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
                <transformer
                  implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <mainClass>dropTest.priv.jp.y.suzuki.DropTestApplication</mainClass>
                </transformer>
              </transformers>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>io.dropwizard</groupId>
      <artifactId>dropwizard-core</artifactId>
      <version>${dropwizard.version}</version>
    </dependency>
    <dependency>
      <groupId>io.dropwizard</groupId>
      <artifactId>dropwizard-auth</artifactId>
      <version>${dropwizard.version}</version>
    </dependency>
    <dependency>
      <groupId>io.dropwizard</groupId>
      <artifactId>dropwizard-assets</artifactId>
      <version>${dropwizard.version}</version>
    </dependency>
  </dependencies>
</project>

2-2. Create config.yml

Describe the settings used in the app. This time, create a yml file (name is arbitrary) directly under the root of the project (the same position as pom.xml), Specify the port and set the root path when starting the application. With the settings below, the app will launch on the 8090 port and the root path is set to/ api /.

config.yml


# Application server setting.
server:
  applicationConnectors:
    - type: http
      port: 8090

  rootPath: '/api/*'

3. Creating a core class for Dropwizard

We will create the necessary files with Dropwizard. This time, I created a package called dropTest.priv.jp.y.suzuki under src / main / java and created a core class under it.

3-1. Configuration class creation

Here, set the parameters for each environment. The yaml file information described in the previous step will be loaded into this class. For example, suppose you have made the following settings (description) in the yaml file.

config.yml


~ Omitted ~

# template sentence
template: Hello!!

Then create a Configuration class as shown below

DropTestConfiguration.java


package priv.jp.y.suzuki;

import io.dropwizard.Configuration;

public class DropTestConfiguration extends Configuration {

    /**Read from the configuration file*/
    private String template;

    public String getTemplate() {
        return template;
    }

}

By doing this, you can read this in the Application class etc. and use it.

3-2. Application class creation

Create an Application class that is positioned to be the main class in Java. Here, the main function, bundle settings, and resource class registration are performed. I haven't created the resource class yet, so I'll comment it out.

DropTestApplication.java


package dropTest.priv.jp.y.suzuki;

import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;

public class DropTestApplication extends Application<DropTestConfiguration> {
  //Main settings
  public static void main(String[] args) throws Exception {
    new DropTestApplication().run(args);
  }

  //Bundle settings
  @Override
  public void initialize(Bootstrap<DropTestConfiguration> bootstrap) {
    bootstrap.addBundle(new AssetsBundle("/assets", "/", "index.html"));
    bootstrap.addBundle(new AssetsBundle("/assets/css", "/css", null, "css"));
    bootstrap.addBundle(new AssetsBundle("/assets/js", "/js", null, "js"));
  }

  //Resource class registration
  @Override
  public void run(DropTestConfiguration conf, Environment env) throws Exception {
    
    //Get the information read from the configuration file
    String template = conf.getTemplate();
    System.out.println(template); //Whether it could be read
    // env.jersey().register(new SampleResource());
  }

}

4. Create server-side socket

Create a resource class that has the role of receiving values from the screen side. The place of creation is as follows.

Creation location: dropTest.priv.jp.y.suzuki.resource

This time, it takes a value and returns it with "" input word: "".

SampleResource.java


package dropTest.priv.jp.y.suzuki.resource;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/message")
public class SampleResource {

	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.TEXT_PLAIN)
	@Path("/response/{sentence}")
	public String responseMessage(@PathParam("sentence") String sentence) {
		String message = "Input word:" + sentence;
		return message;
	}
}

The above points are various annotations.

--@POST specifies that the call should be made only during POST communication. --@Consumes @Produces specifies the input / output format. This time, JSON format and TEXT format are specified. --@PathParam is specified to receive the value from the screen, and the {sentence} part is acquired with the specified type (String this time). --@Path specifies the call target during REST communication by URL

In this case, this resource class is / message and the method you want to execute is/ response / {sentence}. Therefore, it is assumed to be executed with the following URL including the root path specified in the yml file.

POST communication: / api / message / response /" input statement "

Finally, register the resource class with the Application class created so far, and you're done.

DropTestApplication.java


import dropTest.priv.jp.y.suzuki.resource.SampleResource;

  // ~Omission~

  //Resource class registration
  @Override
  public void run(DropTestConfiguration conf, Environment env) throws Exception {
    
    //Get the information read from the configuration file
    String template = conf.getTemplate();
    System.out.println(template); //Whether it could be read
    env.jersey().register(new SampleResource()); //Validate what was commented out earlier
  }

}

5. Screen creation

Here, html and javascript are described as screen creation. First, create a folder called ʻassets under src / main / resources. Create a ʻindex.html file and ajs folder under the created ʻassets, Create a javascript file that describes the movement of ʻindex.html under the created js folder (this time ʻindex.js`).

Package example: src/main/resources   |__ assets     |__ index.html     |__ js       |__ index.js

5-1. Create index.html

This time, I will create a simple one that displays the input field, the submit button, and the characters returned from the server. It is assumed that jQuery will be used for screen display and REST communication. Therefore, [Download] jQuery (https://code.jquery.com/jquery-3.2.1.min.js) and place it in the js file.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>DropwizardTEST</title>
  <script src="js/jquery-3.2.1.min.js"></script>
  <script src="js/index.js"></script>
</head>
<body>
<input type="text" id="inputSentence"><br>
<input type="button" id="start" value="REST communication"><br>

<div><span id="result">The response content is written here</span></div>

</body>
</html>

5-2. Create index.js

Here, when the button is pressed, REST communication is executed and the result is output. This time, we will use jQuery ajax.

index.js



/**Responds to button press*/
$(document).on('click', '#start', function() {
  var SendData = $("#inputSentence").val();
  Request("/api/message/response/" + SendData, "POST", null, resultOpen, FailAnon);
  return false;
});

/**for ajax*/
function Request(Uri, Method, Data, CallbackFunc, ErrorCallbackFunc) {
  $.ajax({
    url:  Uri,
    type: Method,
    data: Data,
    contentType: "application/json; charset=utf-8",
    cache: false
  }).done(function(response){
    CallbackFunc(response);
    return false;
  }).fail(function(XMLHttpRequest, textStatus, errorThrown) {
    ErrorCallbackFunc();
    return false;
  });
  return false;
}

/**Called when ajax fails*/
function FailAnon() {
  $("#result").html("<b>ERROR!</b>Communication failed");
  return false;
}

/**Display the result*/
function resultOpen(response) {
  $("#result").html(response + "<br>");
  return false;
}

6. Build

Build the completed application. Build is done with Maven. Build from the project directory with the following command. If "BUILD SUCCESS" is displayed, it is successful. You should have a jar file under your target directory.

Build command: maven package

7. Run

Two files are required for execution. There are two files, a jar file created by the build and a yaml file that is a configuration file.

The execution command is as follows.

Execution command example: java -jar target / droptest-0.0.1-SNAPSHOT.jar server config.yml

At the end

When the startup is completed successfully, let's actually open the Web and check it. If you cannot connect, it is easy to understand the cause by using the output log or the developer mode such as F12.

image.png

By the way, the launched app can be stopped by the Ctrl + c command like many apps.

Recommended Posts

Create a simple web application with Dropwizard
Build a web application with Javalin
Until you create a Web application with Servlet / JSP (Part 1)
Create a simple DRUD application with Java + SpringBoot + Gradle + thymeleaf (1)
Create a simple on-demand batch with Spring Batch
[Rails withdrawal] Create a simple withdrawal function with rails
Create a simple bar chart with MPAndroidChart
Create a simple web server with the Java standard library com.sun.net.httpserver
Create a simple search app with Spring Boot
Create a web api server with spring boot
Create a java web application development environment with docker for mac part2
Create a playground with Xcode 12
Create a simple demo site with Spring Security with Spring Boot 2.1
Web application built with docker (1)
Create a JAVA WEB application and try OMC APM
Create a simple CRUD with SpringBoot + JPA + Thymeleaf ③ ~ Add Validation ~
The first WEB application with Spring Boot-Making a Pomodoro timer-
Create a Hello World web app with Spring framework + Jetty
Try developing a containerized Java web application with Eclipse + Codewind
Create a Vue3 environment with Docker!
Deploy a Docker application with Greengrass
Preparing to create a Rails application
Web application creation with Nodejs with Docker
Create exceptions with a fluid interface
Create a Maven project with a command
Implement a simple Web REST API server with Spring Boot + MySQL
Let's make a book management web application with Spring Boot part1
Create a simple CRUD with SpringBoot + JPA + Thymeleaf ④ ~ Customize error messages ~
Let's make a book management web application with Spring Boot part3
Let's make a book management web application with Spring Boot part2
I want to develop a web application!
Create a jar file with the command
[Rails6] Create a new app with Rails [Beginner]
Create a GUI JSON Viewer with Ruby/GTK3
Create a MySQL environment with Docker from 0-> 1
Start web application development with Spring Boot
Create a temporary class with new Object () {}
[docker] [nginx] Make a simple ALB with nginx
[Rails] Let's create a super simple Rails API
[Rails 5] Create a new app with Rails [Beginner]
Run WEB application with Spring Boot + Thymeleaf
Create a simple CRUD with SpringBoot + JPA + Thymeleaf ② ~ Screen and function creation ~
Creating a java web application development environment with docker for mac part1
Java beginner tried to make a simple web application using Spring Boot
I want to create a dark web SNS with Jakarta EE 8 with Java 11
[Java] Deploy a web application created with Eclipse + Maven + Ontology on Heroku
Create a simple gateway server by setting masquerade with firewall-cmd of CentOS8
Volume of trying to create a Java Web application on Windows Server 2016
# 1 [Beginner] Create a web application (website) with Eclipse from knowledge 0. "Let's build an environment for creating web applications"
Create a website with Spring Boot + Gradle (jdk1.8.x)
[Memo] Create a CentOS 8 environment easily with Docker
Create a CSR with extended information in Java
Let's make a calculator application with Java ~ Create a display area in the window
[Rails] rails new to create a database with PostgreSQL
[Windows] [IntelliJ] [Java] [Tomcat] Create a Tomcat9 environment with IntelliJ
Let's create a timed process with Java Timer! !!
Create a simple batch processing framework in Eclipse.
Create a Spring Boot application using IntelliJ IDEA
[Java] Create a collection with only one element
Let's create a super-simple web framework in Java
Create a team chat with Rails Action Cable