Java создание html страница

Java Platform, Enterprise Edition 7: Creating HTML5 Pages in JavaServer Faces 2.2

This tutorial shows you how to convert a static HTML5 page into a dynamic JavaServer Faces (JSF) page with HTML5-friendly markup.

Time to Complete

Introduction

JSF is a presentation technology that allows developers to create pages with component-oriented design. The design reduces development time and increases interactivity of applications. HTML5 is the new standard for writing web pages. Modern web applications require collaboration between web developers and enterprise developers to achieve great design and usability. Java Platform, Enterprise Edition 7 (Java EE 7) with JSF 2.2 bridges the gap for web developers: They can integrate their web designs by using HTML5 in JSF pages. This tutorial shows the conversion steps of an HTML5 page to a JSF-enabled page.

Please note that the pages are viable solutions that can be used in an application. The goal of this tutorial is to show you the different versions that you can use in Java EE 7 with JSF 2.2, as follows:

  • A pure HTML5 solution using JavaScript for interactivity and dynamic data
  • An HTML5 page with JSF attributes that adds dynamic data to a pure HTML5 page
  • An HTML5 page with JSF components that will be rendered as HTML5 elements adding passthrough parameters for extended HTML5 properties
  • A JSF component-oriented page that uses HTML5 elements when necessary

Scenario

In this tutorial, you modify the sticker story web application developed in the previous tutorial (Using WebSocket for Real-Time communication in Java Platform, Enterprise Edition 7) to use JSF with HTML5-friendly markup.

Software Requirements

The following are the software requirements:

  • Download and install the Java 7 development kit: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
  • Download and install the Java NetBeans 7.3.1 integrated development environment (IDE) for Java EE development with GlassFish 4.0: https://netbeans.org/downloads/index.html.
  • (Optional) Download and install the GlassFish Server Open Source Edition 4.0: http://glassfish.java.net/download.html.
Читайте также:  Java log all http requests

Prerequisites

Before starting this tutorial, you should:

  • Have knowledge of the Java programming language.
  • Have basic knowledge of Java EE (JSF) and HTML.
  • Have completed the tutorial entitled Using WebSocket for Real-Time Communication in Java Platform, Enterprise Edition 7. If you prefer, you can download the completed project here.

Setting Up the Project

In this section, you set up the project. If you completed the tutorial entitled Using WebSocket for Real-Time Communication in Java Platform, Enterprise Edition 7, use the same project and skip to step 8.

As you can see, the stickers-2 page has HTML5 code with JSF attributes that give dynamic data. This situation is ideal if your web designer creates HTML5 pages, and you must add JSF functionality on top.

Creating a JSF with HTML Markup

In this section, you incorporate JSF components inside an HTML5 page to add JSF functionality. For simplicity, you will use the stickers-2 page as the base for the new page.

Creating a JSF Page

In this section, you modify the page again to use JSF components.

Use the following code sample for reference. The tags to replace are highlighted.

stickers-4.xhtml page

  html> html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:p="http://xmlns.jcp.org/jsf/passthrough"> h:head> title>Sticker Storytitle> h:outputStylesheet name="styles.css"/> h:outputScript name="story-page.js"/> h:head> h:body> header> h1>Sticker Story Bookh1> header> nav> Drag stickers from the left bar to the canvas. nav> aside> h2>Stickersh2> h:panelGroup layout="block" id="stickerContainer"> ui:repeat var="imgName" value="#stickerSheet.allStickers>"> h:graphicImage name="stickers/$imgName>" style="float:left" p:draggable="true" p:ondragstart="drag(event)" p:data-sticker="$imgName>" /> ui:repeat> h:panelGroup> aside> h:panelGroup layout="block" id="content"> canvas id="board" width="1000" height="580" ondrop="drop(event)" ondragover="allowDrop(event)"> Canvas Not Supported. canvas> h:graphicImage name="canvas2.png" id="background_img" style="display:none;"/> h:panelGroup> footer> small>Made with JSF 2.2 + HTML5 + WebSockets and JSONsmall> ol> li onclick="toggleLog();">Logli> ol> footer> div id="logContainer"> h2>logh2> h:panelGroup layout="block" id="log"/> div> h:body> html> 

Rerun the application and test the newly created page.

Summary

In this tutorial, you learned how to:

  • Use JSF attributes in HTML pages
  • Use JSF components in HTML pages
  • Use JSF passthrough parameters to create HTML5 markup

Resources

  • The Java EE 7 tutorial
  • The JSF 2.2 specification
  • The Java EE documentation
  • The HTML5 specification
  • To learn more about Java EE 7, refer to additional OBEs in the Oracle Learning Library.

Credits

  • Lead Curriculum Developer: Eduardo Moranchel
  • Other Contributors:
    • Edgar Martinez
    • Miguel Salazar

    To help navigate this Oracle by Example, note the following: Hiding Header Buttons: Click the Title to hide the buttons in the header. To show the buttons again, simply click the Title again. Topic List Button: A list of all the topics. Click one of the topics to navigate to that section. Expand/Collapse All Topics: To show/hide all the detail for all the sections. By default, all topics are collapsed Show/Hide All Images: To show/hide all the screenshots. By default, all images are displayed. Print: To print the content. The content currently displayed or hidden will be printed.

    To navigate to a particular section in this tutorial, select the topic from the list.

    Источник

    Создать HTML-файл в Java

    Создать HTML-файл Java

    Файлы HTML содержат язык разметки, который можно использовать для форматирования текста и другого содержимого страницы, просматриваемого с помощью веб-браузеров. Возможно, вы захотите создать HTML-страницы для различных требований. Соответственно, в этой статье рассказывается, как программно создать HTML-файл на Java.

    Создание HTML-файлов — установка Java API#

    Aspose.HTML for Java можно использовать для создания, редактирования или преобразования HTML, SVG, MD и других форматов файлов. Вы можете настроить API, либо загрузив его JAR-файл из раздела Загрузки, либо используя следующие конфигурации Maven в файле pom.xml вашего проекта на основе Maven. Он настроит библиотеку из Aspose Repository:

       snapshots repo http://repository.aspose.com/repo/   
       com.aspose aspose-html 22.9 jdk18   

    Программно создать файл HTML в Java#

    Следующие шаги демонстрируют, как программно создать базовый HTML-файл с нуля на Java:

    1. Инициализировать объект класса HTMLDocument.
    2. Создайте текстовый элемент и добавьте его в пустой документ.
    3. Сохраните полученный HTML-файл.

    В приведенном ниже примере кода показано, как создать HTML-файл с нуля программным путем с помощью Java:

    // Подготовьте выходной путь для сохранения документа String documentPath = "create-new-document.html"; // Инициализировать пустой HTML-документ com.aspose.html.HTMLDocument document = new com.aspose.html.HTMLDocument(); // Создайте текстовый элемент и добавьте его в документ var text = document.createTextNode("Hello World!"); document.getBody().appendChild(text); // Сохраните документ на диск document.save(documentPath); 

    Создайте расширенный HTML-файл в Java#

    Этот раздел является шагом дальше от информации, которую мы узнали выше. В нем объясняется, как создать расширенную версию HTML-файла, в которую будут добавлены заголовок, абзац и список с помощью Java:

    1. Инициализировать экземпляр класса HTMLDocument.
    2. Создайте элемент заголовка и добавьте его в документ.
    3. Добавьте абзац и добавьте его.
    4. Добавьте элемент списка и сохраните его как файл HTML.

    Фрагмент кода ниже объясняет, как программно создать расширенный файл HTML в Java:

    // Создайте пустой HTML-документ var document = new com.aspose.html.HTMLDocument(); // Добавить заголовок // Создайте элемент заголовка var h2 = (com.aspose.html.HTMLHeadingElement)document.createElement("h2"); // Создать текстовый элемент var text = document.createTextNode("This is Sample Heading!"); // Добавить текстовый элемент в заголовок h2.appendChild(text); // Добавить заголовок to the document document.getBody().appendChild(h2); // Добавить абзац // Создать элемент абзаца var p = (com.aspose.html.HTMLParagraphElement)document.createElement("p"); // Установить настраиваемый атрибут p.setAttribute("id", "first-paragraph"); // Создайте текстовый узел var paraText = document.createTextNode("This is first paragraph. "); // Добавьте текст в абзац p.appendChild(paraText); // Прикрепить абзац к телу документа document.getBody().appendChild(p); // Добавить упорядоченный список // Создать элемент абзаца var list = (com.aspose.html.HTMLOListElement)document.createElement("ol"); // Добавить элемент var item1 = (com.aspose.html.HTMLLIElement)document.createElement("li"); item1.appendChild(document.createTextNode("First list item.")); // Добавить элементs to the list list.appendChild(item1); // Прикрепить список к телу документа document.getBody().appendChild(list); // Сохраните документ HTML в файл document.save("create-html-advanced.html"); 

    Изучите Aspose.HTML for Java#

    Вы можете заглянуть в раздел [документация][7], чтобы изучить различные другие функции API.

    Заключение#

    В заключение вы узнали, как создать файл HTML в Java. В нем объясняется основной вариант использования создания HTML-файла, а также расширенная версия для создания HTML-файла с нуля программным путем на Java. Кроме того, пожалуйста, не стесняйтесь писать нам на форум в случае каких-либо проблем.

    Смотрите также#

    Источник

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