--Create a simple web app --When you enter from the screen, it will return the input contents
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.
Depending on the settings of eclipse, the following package configuration will be completed.
Here, specify the package to be used in maven in pom.xml, and set the application in config.yml.
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>
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/*'
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.
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.
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());
}
}
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
}
}
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
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>
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;
}
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
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
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.
By the way, the launched app can be stopped by the Ctrl + c
command like many apps.
Recommended Posts