Java web start android

Руководство по веб-запуску Java

В этой статье объясняется, что такое Java Web Start (JWS), как настроить его на стороне сервера и как создать простое приложение.

Автор: baeldung
Дата записи

1. Обзор

В этой статье объясняется, что такое Java Web Start (JWS), как настроить его на стороне сервера и как создать простое приложение.

Примечание: JWS был удален из Oracle JDK, начиная с Java 11. В качестве альтернативы рассмотрите возможность использования Open Web Start .

2. Введение

JWS-это среда выполнения, которая поставляется вместе с Java SE для веб-браузера клиента и существует с версии Java 5.

При загрузке файлов JNLP (также известных как протокол запуска сети Java) с веб-сервера эта среда позволяет нам удаленно запускать пакеты JAR, на которые она ссылается.

Проще говоря, механизм загружает и запускает классы Java на компьютере клиента с обычной установкой JRE. Это также позволяет получить некоторые дополнительные инструкции от Jakarta EE. Однако ограничения безопасности строго применяются JRE клиента, обычно предупреждая пользователя о ненадежных доменах, отсутствии HTTPS и даже неподписанных JAR.

С общего веб-сайта можно загрузить файл JNLP для выполнения приложения JWS. После загрузки его можно запустить непосредственно из ярлыка на рабочем столе или средства просмотра кэша Java. После этого он загружает и выполняет файлы JAR.

Этот механизм может быть очень полезен для предоставления графического интерфейса, который не является веб-интерфейсом (без HTML), такого как приложение для безопасной передачи файлов, научный калькулятор, безопасная клавиатура, локальный браузер изображений и так далее.

3. Простое приложение JNLP

Хороший подход-написать приложение и упаковать его в файл WAR для обычных веб-серверов. Все, что нам нужно, это написать желаемое приложение (обычно с помощью Swing) и упаковать его в файл JAR. Затем этот JAR, в свою очередь, должен быть упакован в файл WAR вместе с JNLP, который будет ссылаться, загружать и выполнять класс Main своего приложения в обычном режиме.

Нет никакой разницы с обычным веб-приложением, упакованным в файл WAR, за исключением того факта, что нам нужен файл JNLP для включения JWS, как будет показано ниже.

3.1. Java-приложение

Давайте начнем с написания простого Java-приложения:

Мы видим, что это довольно простой класс свинга. Действительно, ничего не было добавлено, чтобы сделать его совместимым с JWS.

3.2. Веб-приложение

Все, что нам нужно, это упаковать этот пример класса Swing в файл WAR вместе со следующим файлом JNLP:

Давайте назовем его hello.jndi и поместим в любую веб-папку нашей ВОЙНЫ. И JAR, и WAR загружаются, поэтому нам не нужно беспокоиться о том, чтобы поместить JAR в папку lib .

URL-адрес нашей последней банки жестко закодирован в файле JNLP, что может вызвать некоторые проблемы с распространением. Если мы изменим серверы развертывания, приложение больше не будет работать.

Давайте исправим это с помощью правильного сервлета позже в этой статье. А пока давайте просто поместим файл JAR для загрузки в корневую папку в качестве index.html , и связать его с элементом привязки:

Давайте также установим основной класс в нашем JAR-манифесте . Это может быть достигнуто путем настройки плагина JAR в pom.xml файл. Аналогично, мы перемещаем файл JAR за пределы WEB-INF/lib , поскольку он предназначен только для загрузки, т. е. не для загрузчика классов:

4. Специальные конфигурации

4.1. Вопросы безопасности

Чтобы запустить приложение, нам нужно подписать банку . Создание действительного сертификата и использование плагина JAR Sign Maven выходит за рамки этой статьи, но мы можем обойти эту политику безопасности в целях разработки или если у нас есть административный доступ к компьютеру нашего пользователя.

Читайте также:  Лучшие pdf редакторы для андроид

Для этого нам нужно добавить локальный URL-адрес (например: http://localhost:8080 ) в список исключений безопасности установки JRE на компьютере, на котором будет выполняться приложение. Его можно найти, открыв панель управления Java (в Windows мы можем найти его через панель управления) на вкладке Безопасность.

5. JnlpDownloadServlet

5.1. Алгоритмы сжатия

Есть специальный сервлет, который можно включить в нашу ВОЙНУ. Он оптимизирует загрузку, ища наиболее сжатую скомпилированную версию нашего файла JAR, если она доступна, а также исправляет жестко закодированное значение codebase в файле JLNP.

Поскольку наша БАНКА будет доступна для загрузки, рекомендуется упаковать ее с помощью алгоритма сжатия, такого как Pack200, и доставить обычную банку и любой пакет JAR.PACK.GZ или JAR.GZ сжатая версия в той же папке, чтобы этот сервлет мог выбрать лучший вариант для каждого случая.

К сожалению, пока нет стабильной версии плагина Maven для этого алгоритма сжатия, но мы можем работать с исполняемым файлом Pack200, который поставляется с JRE (обычно устанавливается по пути /jre/bin/ ).

Без изменения JNLP и путем размещения jar.gz и jar.pack.gz версии JAR в той же папке, сервлет выбирает лучшую, как только он получает вызов от удаленного JNLP. Это улучшает пользовательский интерфейс и оптимизирует сетевой трафик.

5.2. Динамическая подстановка Кодовой Базы

Сервлет также может выполнять динамические замены жестко закодированных URL-адресов в теге . Изменив JNLP на подстановочный знак , он доставит тот же окончательный тег визуализации.

Сервлет также работает с подстановочными знаками $$codebase , $$hostname , $$name и $$site , которые разрешат ” http://localhost:8080/jnlp-example/ “, ” localhost:8080 “, ” hello.jnlp ” и ” http://localhost:8080 ” соответственно.

5.3. Добавление сервлета в путь к классу

Чтобы добавить сервлет, давайте настроим обычное сопоставление сервлетов для шаблонов JAR и JNLP для вашего web.xml :

Сам сервлет поставляется в виде набора банок ( jardiff.jar и jnlp-servlet.jar ), которые в настоящее время находятся в разделе демонстраций и образцов на странице загрузки Java SDK.

В примере GitHub эти файлы включены в папку java-core-samples-lib и включены в качестве веб-ресурсов плагином Maven WAR:

6. Заключительные мысли

Java Web Start-это инструмент, который может использоваться в средах (интрасети), где нет сервера приложений. Кроме того, для приложений, которым необходимо манипулировать локальными файлами пользователей.

Приложение отправляется конечному пользователю по простому протоколу загрузки без каких-либо дополнительных зависимостей или конфигурации, за исключением некоторых проблем безопасности (HTTPS, подписанный JAR и т. Д.).

В примере Git полный исходный код , описанный в этой статье, доступен для загрузки. Мы можем загрузить его непосредственно с GitHub в ОС с Tomcat и Apache Maven. После загрузки нам нужно запустить команду mvn install из исходного каталога и скопировать сгенерированный файл jws.war из target в папку webapps установки Tomcat.

После этого мы сможем запустить Tomcat, как обычно.

Источник

4 Overview of Java Web Start Technology

This chapter includes the following topics:

Introduction to Java Web Start

Java Web Start is an application-deployment technology that enables your users to launch full-featured applications with a single click from any web browser. Users can download and launch applications without going through complicated installation procedures.

With Java Web Start, your users launch applications by clicking a web page link. If the application is not present on their computer, Java Web Start automatically downloads all necessary files. It then caches the files on the computer so that the application is always ready to be relaunched anytime the user wants—either from an icon on the desktop or from the browser link. No matter which method is used to launch the application, the most current version of the application is always presented.

The technology underlying Java Web Start is the Java Network Launching Protocol & API (JNLP). This technology was developed through the Java Community Process (JCP). Java Web Start is the reference implementation (RI) for the JNLP specification. The JNLP technology defines, among other things, the JNLP file, which is a standard file format that describes how to launch an application. The JNLP specification is available at JSR 56: Java Network Launching Protocol and API.

Benefits of Java Web Start

From a technology standpoint, Java Web Start has a number of key benefits that make it an attractive platform to use for deploying applications.

The benefits include the following:

Java Web Start is built exclusively to launch applications written to the Java Platform, Standard Edition. Thus, a single application can be made available on a web server and then deployed on a wide variety of platforms, including Windows 7+, Linux, and macOS.

Java Web Start supports multiple revisions of the Java Platform, Standard Edition. Thus, an application can request a particular version of the platform it requires, such as Java SE 9. Several applications can run at the same time on different platform revisions without causing conflicts.

Java Web Start enables applications to be launched independently of a web browser. This can be used for off-line operation of an application, where launching the application through the browser is inconvenient or impossible. The application can also be launched through desktop shortcuts, making launching the web-deployed application similar to launching a native application.

Java Web Start takes advantage of security features of the Java Platform. Sandbox applications are run in a protective environment with restricted access to local disk and network resources. Users must also agree to run the application the first time it is launched.

Applications launched with Java Web Start are cached locally. Thus, an already-downloaded application is launched similar to a traditionally installed application.

Where to Find Java Web Start

Java Web Start is included in the Java Platform, Standard Edition development kit (JDK) and Java Runtime Environment (JRE), and includes the security features of the Java platform.

The JDK and JRE are available from the java.com website.

Using Java Web Start Software

Java Web Start allows you to launch Java-technology-based applications directly from the Web. An application can be launched in three different ways:

From a web browser by clicking a link

From desktop icons or the Start Menu

From the Java Cache Viewer

Regardless of which way is used, Java Web Start will connect back to the web server each time an application is launched, to check whether an updated version of the application is available.

Launching from a Web Browser

Point your web browser to a page with a link to a JNLP application, and click that link.

A security dialog box will pop up with information about the origin of the application based on who digitally signed the code, and the level of access requested. The application will run only if you decide to trust the vendor.

That is really all there is to using Java Web Start, but how does it work? The HTML links that launch the applications are, in fact, standard HTML links. However, instead of pointing to another web page, they link to a special configuration file called a JNLP file. The web browser examines the file extension or the MIME type of the file, and sees that it belongs to Java Web Start. It then launches Java Web Start with the downloaded JNLP file as an argument. Java Web Start proceeds with downloading, caching, and running the application as directed by the JNLP file.

Launching from Desktop Icons and the Start Menu (Microsoft Windows and Linux Running GNOME 2.0+)

Java Web Start technology can automatically create shortcuts for your application on the desktop and in the Start Menu for web-deployed applications developed with Java technology. You can use the Java Control Panel to control the shortcut settings. Shortcuts can also be added by using the Java Web Start Cache Viewer, using the install shortcut menu item.

Using Java Web Start Software Behind a Proxy Server or Firewall

Java Web Start software must be configured with the correct proxy settings in order to launch applications from outside your firewall. Java Web Start software automatically tries to detect the proxy settings from the default browser on your system (Internet Explorer or Mozilla browsers on Microsoft Windows, and Mozilla browsers on the Solaris Operating Environment and Linux). Java Web Start technology supports most web proxy auto-configuration scripts. It can detect proxy settings in almost all environments.

You can also use the Network Settings Tab in the Java Control Panel to view or edit the proxy configuration.

Setting Up the Web Server

Applications can be deployed from any standard web server. Java Web Start leverages existing internet technology, such as the HTTP protocol and web servers, so existing infrastructure for deploying HTML-based content can be reused to deploy Java Technology-based applications using Java Web Start.

To deploy your application to client machines, ensure that all files that contain your application are accessible through a web server. This typically requires copying one or more JAR files and a JNLP file into the web server’s directories. Enabling the website to support Java Web Start is similar to deploying HTML-based content. In addition, to use Java Web Start, the web server must be configured to support the application/x-java-jnlp-file MIME type.

Step 1 Configure the web server to use the Java Web Start MIME type.

Many web servers come with the Java Web Start MIME type configured by default. If your web server does not, configure it so that all files with the .jnlp file extension are set to the application/x-java-jnlp-file MIME type.

Most web browsers use the MIME type returned with the contents from the web server to determine how to handle the particular content. The server must return the application/x-java-jnlp-file MIME type for JNLP files in order for Java Web Start to be invoked.

Each web server has a specific way in which to add MIME types. For example, for the Apache web server, you add the following line to the .mime.types configuration file:

Check the documentation for the specifics of your web server.

Step 2 Create a JNLP file for the application.

The easiest way to create this file is to modify an existing JNLP file with your requirements. A simple JNLP file is shown in the following example:

The syntax and format for the JNLP file is described in JNLP File Syntax.

Step 3 Make the application accessible on the web server.

Ensure that your application’s JAR files and the JNLP file are accessible at the URLs listed in the JNLP file.

Step 4 Create the web page that launches the application.

Create the web page and include one of the following options for starting a Java Web Start application:

Use a link to the JNLP file, as shown in the following examples:

Use JavaScript, as shown in the following example:

Use a link with the jnlp: schema, as shown in the following example:

Copy the JavaScript code from the HTML file generated by the Java Packager tool.

If you are using the Java Packager tool, see Create the Web Page.

Installing the Java Web Start Protocol Handler

Java Web Start includes a protocol handler to handle the custom URI schemes jnlp: and jnlps: . Use these schemes as a direct way to start Java Web Start applications.

The protocol handler is automatically installed on Windows and macOS systems. It must be manually installed on Linux systems.

Installing the Protocol Handler for Chrome

If you use the Chrome browser on Linux, manually install the protocol handler that enables you to start Java Web Start applications using the jnlp or jnlps protocol.

  1. Use a text editor to create a file named javaws.desktop in the

/.local/share/applications directory.
Include the statements shown in the following example.

Installing the Protocol Handler in Firefox

If you use the Firefox browser on Linux, manually install the protocol handler that enables you to start Java Web Start applications using the jnlp or jnlps protocol.

Источник

Оцените статью