Статьи

Разработка базовой функциональности сайта с помощью Webix и Struts 2

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

Генераторы кода, автозаполнение, анализаторы кода, библиотеки и фреймворки поселились в жизни разработчиков. Они позволяют сократить время разработки сайта до минимума. Сам интернет развивается вместе с этими инструментами.

Недавно сайты представили статические данные, а их функциональность была довольно минимальной. Сегодня сайты представляют собой полнофункциональные приложения, которые позволяют выполнять действия, которые ранее были доступны только для настольных компьютеров. Одним из инструментов для быстрого создания интерфейса веб-приложения для мобильных и настольных устройств является  Webix , библиотека виджетов пользовательского интерфейса JavaScript.

Рассмотрим пример создания сайта, предназначенного для анонса будущих конференций по фронтальной разработке с помощью Webix и Java-фреймворка Struts 2.

Задача состоит в том, чтобы разработать сайт, который будет представлять список предстоящих событий, касающихся развития интерфейса. Кроме того, необходимо реализовать возможность добавлять новые события, а также отчеты в каждое событие и возможность просматривать информацию о контактах.

Для реализации интерфейса мы будем использовать библиотеку виджетов JavaScript UI Webix, а серверная часть будет создаваться с помощью Java-фреймворка Struts 2 и Hibernate с MySQL. IDE Eclipse будет использоваться для разработки. В то же время можно использовать любую другую IDE, предназначенную для Java. Чтобы сделать Java-приложение доступным для пользователей, необходим веб-сервер. Apache Tomcat — это популярный и довольно простой в использовании сервер. Вы можете получить подробную информацию о веб-сервере и конфигурации IDE  здесь .

Создание приложения и настройка Struts 2

Итак, давайте создадим новое приложение Maven с архетипом maven-archetype-webapp. Для этого откройте в Eclipse: File — New — Project. В открывшемся окне найдите Maven Project, выберите его и нажмите «Далее».

Затем мы должны выбрать, где мы будем создавать наш проект: в рабочей области или в любом другом месте. Убедитесь, что опция «Создать простой проект» отключена. В следующем окне выберите архетип Maven-проекта. В нашем случае это должен быть maven-archetype-webapp. Выберите его и нажмите «Далее».

Последний и самый важный шаг — выбрать название и версию проекта! Каждый проект в Maven идентифицируется парой:  groupId / artefactId . Обычно название компании используется в качестве groupId, а имя проекта в качестве artefactId. Мои настройки выглядят так:

Нажмите «Готово» и наше приложение готово! Давайте удостоверимся, что это работает. Создайте тестовый файл src / main / webapp / index.jsp с контекстом следующим образом:

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Checking the connection</title>
</head>
<body>
    Our app will be here!
</body>
</html>

Я настоятельно рекомендую использовать кодировку UTF-8 для кириллических сайтов. В свойствах каждого созданного файла установите кодировку UTF-8 вручную, если была установлена ​​любая другая кодировка.

После этого запустите приложение: щелкните правой кнопкой мыши проект, выберите «Запуск от имени — Выполнить на сервере — Tomcat v7.0» на локальном хосте (или на другом веб-сервере, который вы используете) и нажмите «Готово». Если все было выполнено правильно, открыв путь HTTP: // локальный: 8080 / MyApp / я п браузер вы увидите следующую тестовую страницу:

Возможно, что на странице  index.jsp  в проекте Eclipse будет выделена ошибка. Чтобы исправить это, перейдите в «Build Path» (щелкните правой кнопкой мыши по проекту — Build Path — Configure Build Path). В открывшемся окне перейдите на вкладку «Библиотеки» и нажмите «Добавить библиотеку». Выберите «Время выполнения сервера — Apache Tomcat v7.0 — Готово». Затем в меню «Проект» выполните действие «Очистить» и подождите, пока ошибка не исчезнет.

Прежде чем продолжить разработку сайта, стоит учесть некоторую полезную информацию о структуре проекта. Проект хранится в нескольких каталогах. Каждый из этих каталогов имеет свое назначение:

Ресурсы Java:

  • / src / main / java  — место для хранения классов Java-проекта.
  • / src / main / resources  — здесь находятся файлы конфигурации: struts.xml, log4j.xml, hibernate.cfg.xml.

Развернутые ресурсы:

  • / src / main / webapp  — хранилище для веб-ресурсов: javascript, css, изображений, просмотр файлов *. JSP.
  • /src/main/webapp/WEB-INF/web.xml  — файловый дескриптор веб-проекта.
  • pom.xml  — файл конфигурации Maven. Здесь мы опишем проект и его зависимости.

Настало время настроить Struts 2. Это расширяемая среда для создания веб-приложений на Java. Он предоставляет набор готовых решений для отображения запросов, который выполняет всю рутинную работу по обработке входящих запросов и генерации ответов на основе представлений.

Прежде всего, вам нужно добавить зависимости Struts2 в файл «pom.xml»:

...
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.3.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.struts.xwork</groupId>
            <artifactId>xwork-core</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-json-plugin</artifactId>
            <version>2.3.16</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.14</version>
        </dependency>
    </dependencies>
    ...

В этом фрагменте кода мы сообщаем серверу, что Struts 2 будет контролировать маршрутизацию запросов. После этого все входящие запросы на сервер будут отправлены указанному классу, и этот класс решит, что делать с ними дальше.

Теперь нам нужно настроить библиотеку  журналов log4j . Для этого вам нужно создать файл src / main / resources / log4j.xml  со следующим содержимым:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>
    <filter>
        <filter-name>struts2</filter-name>
            <filter-class>
            org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
            </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>*</url-pattern>
    </filter-mapping>
</web-app>

В этом фрагменте кода мы сообщаем серверу, что Struts 2 будет контролировать маршрутизацию запросов. После этого все входящие запросы на сервер будут отправлены указанному классу, и этот класс решит, что делать с ними дальше.

Now we need to configure the logging library log4j. To do this you should create a filesrc/main/resources/log4j.xml with the following content:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration PUBLIC "-//log4j/log4j Configuration//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
       <layout class="org.apache.log4j.PatternLayout"> 
          <param name="ConversionPattern" value="%d %-5p %c.%M:%L - %m%n"/> 
       </layout> 
    </appender>
    <logger name="com.opensymphony">
        <level value="DEBUG" />
    </logger>
    <logger name="org.apache.struts2">
         <level value="DEBUG" />
    </logger>
     <root>
        <priority value="INFO"/> 
        <appender-ref ref="STDOUT" /> 
     </root>     
</log4j:configuration>

Все готово для немедленной настройки Struts2 и маршрутизации. Давайте создадим файл 
src / main / resources / struts.xml :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <constant name="struts.devMode" value="true" />
    <package name="defaultpages" namespace="/" extends="struts-default">
        <action name="index">
            <result>/index.jsp</result>
        </action>
    </package>
</struts>

Этот файл настраивает маршрутизацию запросов. В нашем случае мы указали, что запрос
http: // localhost: 8080 / MyApp / index или
http: // localhost: 8080 / MyApp / получит в ответ содержимое файла index.jsp. Файл index.jsp имеет имя «view» и содержит html-код страницы. 

Moreover, there are more interesting ways of routing. For example, if you specify the name of the class and its method in the tag action, Struts 2 will try to find this method and call it. Depending on the result that is returned by this method you can use different views for successful and incorrect results. Run the server and open the page
http://localhost:8080/MyApp/index action in your browser. If you see the same thing as I do, it means that you’ve done all the steps correctly.

Developing pages of the app and navigation between them

Struts 2 is configured and ready to use, so it is time to develop the front-end part of the application. We will use the library of UI components Webix to create the interface on the client side. Webix will allow you to create an interface based on the ready components in a short time.

Webix is very easy to learn. To start working with the library you should go to the Webix website and download the latest Webix version. Then unpack the archive and copy the codebase directory to the folder src/main/webapp/. After that you should update the project in Eclipse: File — Refresh, to help the web server see the new files.

Include Webix on the page index.jsp:

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Checking the connection</title>
    <link rel="stylesheet" href="./codebase/webix.css" type="text/css" media="screen" charset="utf-8">
    <script src="./codebase/webix.js" type="text/javascript" charset="utf-8"></script>
</head>

Webix uses a treelike object to describe the necessary interface. Each element of this object is called “view”. Every element will have its own characteristics which depend on the type of the view. Webix popular view types are toolbar, button, window, list and datatable. The complete list of all views can be found here:http://docs.webix.com/apitocui.html.

We should also pay attention to the “view: layout”. Firstly, this layout’s property is often omitted as it is always possible to recognize the layout component by the rows and cols properties. Each layout is either a row or a column which consists of several individual cells. You can build a layout of any type and configuration by using the nested layouts.

Example:

 webix.ui({
        container:"layout_div",
        rows:[
            {template:"row 1"},
            {template:"row 2"},
            { cols:[
             { template:"col 1" },
             { template:"col 2" },
             { template:"col 3" }
            ]}
        ]
    });

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

webix.ui({
        container:"myapp",
        cols: [{}, {
            width: 1280,
            template: "Your site is here"
        }, {}]
    });

В этом случае ширина центрального контейнера составит 1280 пикселей, а ширина полей будет рассчитана автоматически. Подробную информацию об использовании компонента Layout можно найти в документации по Webix. 


JavaScript-функции и CSS-стили, общие для всех страниц, будут храниться в файлах 
src / main / webapp / codebase / myapp.js  и
src / main / webapp / codebase / myapp.css . Для этого мы создадим эти файлы и добавим следующее правило в myapp.css:
html, body {
    width: 100%;
    height: 100%;
    margin: 0px;
    padding: 0px;
    overflow-x: hidden;
    background-color: #580B1C;
}
#myapp {
    width: 100%;
    height: 100%;
}

Наш сайт должен включать такие стандартные элементы, как заголовок с логотипом, главное меню и фотографии, нижний колонтитул со ссылками и центральная часть с контентом. Чтобы добавить эти элементы, вы должны внести изменения в файл 
index.jsp :

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Webix - Front-End Events</title>
	<link rel="shortcut icon" href="favicon.ico" />
	<link rel="stylesheet" href="./codebase/webix.css" type="text/css" media="screen" charset="utf-8">
	<link rel="stylesheet" href="./codebase/myapp.css" type="text/css" media="screen" charset="utf-8">
	<script src="./codebase/webix.js" type="text/javascript" charset="utf-8"></script>
	<script src="./codebase/myapp.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
	<div id='myapp'></div>
	<script type="text/javascript" charset="utf-8">
	webix.ui({
		container:"myapp",
		cols: [{}, {
			width: 1280,
			rows: [
				{ template: "header", height: 250 },
				{ template: "content"},
				{ template: "content", height: 30 }
			]
		}, {}]
	});
	</script>
</body>
</html>

To make a website unique you can change its style and color. Fortunately, Webix developers provide an easy to use tool Webix SkinBuilder. This tool allows you to choose the style that you like, change its colors, fonts and then download the result. I will use the color #74182C. If you want to use the same color then here’s a link to my customized style: http://webix.com/skin-builder/78aa39e4

Download your style, unpack it and the files webix.css and webix.js. Next move all these files to the folder src/main/webapp /codebase. Don’t forget to update the project in Eclipse.

Now let’s create the header. For this purpose you should expand the webix configuration in the file index.jsp:

...
<div id='myapp'></div>
<div id="header" style="display: none;">
    <div class="confname">Front-End<br>Events</div>
    <div class="confdsc">All events on web development are here!</div>
</div>
<script type="text/javascript" charset="utf-8">
    var imgTemplate = function(obj){
        return '<img src="'+obj.src+'" class="content" ondragstart="return false"/>'
    };

    webix.ui({
        container:"myapp",
        cols: [{}, {
            width: 1280,
            rows: [
                {
                    height: 250,
                    borderless:true,
                    cols: [{
                        rows: [
                            { view: "template", template: "html->header", css: "header", borderless: true},
                            { cols: [
                                {},
                                { view:"toolbar", height: 40, borderless:true, cols:[
                                    {view:"segmented", multiview:false, value:1, width: 600, options:[
                                        { id:"upcoming", value:"Upcoming events" },
                                        { id:"contacts", value:"Contacts" }
                                    ], on: {
                                        'onChange': function(newValue, oldValue){
                                            window.location.href = newValue;
                                        }
                                    }, value:"upcoming" }
                                ]},
                            {}
                        ]}
                    ]},
                    { rows: [
                        { height: 10},
                        {
                            view:"carousel",
                            id:"carousel",
                            width:410,
                            height: 230,
                            borderless: true,
                            cols:[
                                { css: "image", template:imgTemplate, data:{src:"photos/photo1.jpg"} },
                                { css: "image", template:imgTemplate, data:{src:"photos/photo2.jpg"} },
                                { css: "image", template:imgTemplate, data:{src:"photos/photo3.jpg"} },
                                { css: "image", template:imgTemplate, data:{src:"photos/photo4.jpg"} },
                                { css: "image", template:imgTemplate, data:{src:"photos/photo5.jpg"} },
                                { css: "image", template:imgTemplate, data:{src:"photos/photo6.jpg"} }
                            ]
                        },
                    {}
                ]}
            ]
        },
        { template: "content"},
        { template: "footer", height: 30 }
    ]
}, {}]
});

</script>
</body>
</html>

Here we split the top cell into two columns. In the left column we will display the logo and the menu while in the right column photos from events will be shown. To create the menu we will use the toolbar item with a segmented button. For photos section a carousel which will contain pictures will be used. Photos must be precut to the sizes 400*220 and saved in the folder src/main/webapp/photos/.

Also in the above code we’ve added the main menu with the help of the segmented button. To navigate between the pages the handler of the onChange event was added to the element (the button of the “segmented” type). This event will fire when a user changes the selected value. In this case we need to go to the selected page:

 'onChange': function(newValue, oldValue){
        window.location.href = newValue;
    }

Let’s also add a few CSS code into the file myapp.css:

.header {
	padding: 10px;
	box-sizing: border-box;
	background-color: #580B1C;
	color: #ffffff;
}
.confname {
	font-size: 62px;
	float: left;
	width: 450px;
}
.confdsc {
	font-size: 13px;
	margin: 10px 0px;
	width: 800px;
	float: left;

Start the server, open the page http://localhost:8080/MyApp/index.action in your browser. If you see something similar to the screenshot below, it means that you’ve made all the steps correctly!

Now let’s add the footer to our website. To add it you should replace the configuration {template: «footer», height: 30}  in the file index.jsp with the following code:

 {
        height: 30,
        paddingY: 6,
        cols: [
            {},
            {
                template: "html->footer",
                css: "footer",
                borderless: true,
                width: 160
            }, {
        }]
    }

Add an html-container with the code below  to the index.jsp file to build the footer:

<div id="footer" style="display: none;">
    <ul>
        <li><a href="upcoming">Home</a></li>
        <li><a href="contacts">Contacts</a></li>
    </ul>
</div>

В файл myapp.css мы должны добавить приведенный ниже код для оформления нижнего колонтитула:


  
.footer {
    background-color: #580B1C;
    color: #ffffff;
}
.footer ul {
    margin: 3px;
    padding: 0px
}
.footer ul li {
    display: inline;
    padding-right: 14px;
    list-style-type: none;
}
.footer ul li a {
    color: #ffffff;
    text-decoration: none;
}
.footer ul li a:hover {
    text-decoration: underline;
}

Запустите сервер и откройте в браузере http: // localhost: 8080 / MyApp / index.action . Теперь у нас есть все необходимое на нашем сайте, кроме контента.

The site will have multiple pages. Each page will use the same code snippets for the header, the footer and the main menu. It means that we need to put these snippets into separate files and functions to reuse this code on other pages.

  • the html-code of the header and the footer we will place into the appropriate files:

src/main/webapp/header.jsp:

<%@ page contentType="text/html; charset=UTF-8" %>
    <div id="header" style="display: none;">
        <div class="confname">Front-End<br>Events</div>
        <div class="confdsc">All events on web development are here!</div>
    </div>

src/main/webapp/footer.jsp:

<%@ page contentType="text/html; charset=UTF-8" %>
        <div id="footer" style="display: none;">
            <ul>
                <li><a href="upcoming">Home</a></li>
                <li><a href="contacts">Contacts</a></li>
            </ul>
       </div>
  • into the file myapp.js we will add the functions that return the configuration of the footer, photo gallery and of the main menu:

src/main/webapp/codebase/myapp.js:

function getTopMenu(selectedValue) {
    return { cols: [{}, { view:"toolbar", height: 40, borderless:true, cols:[
        {view:"segmented", multiview:false, value:1, width: 600, options:[
           { id:"upcoming", value:"Upcoming events" },
           { id:"contacts", value:"Contacts" }
        ], on: {
            'onChange': function(newValue, oldValue){
                window.location.href = newValue;
            }
        }, value: selectedValue }
    ]}, {}] };
}

function getFooter() {
    return {
        height: 30,
        paddingY: 6,
        cols: [
            {},
            {
                template: "html->footer",
                css: "footer",
                borderless: true,
                width: 160
            },
            {}
        ]
    };
}

function getPhotos() {
    var imgTemplate = function(obj){
        return '<img src="'+obj.src+'" class="content" ondragstart="return false"/>'
    };
    return { rows: [
 { height: 10},
        {
            view:"carousel",
            id:"carousel",
            width:410,
            height: 230,
            borderless: true,
            cols:[
                { css:"image", template:imgTemplate, data:{src:"photos/photo1.jpg"}},
                { css:"image", template:imgTemplate, data:{src:"photos/photo2.jpg"}},
                { css:"image", template:imgTemplate, data:{src:"photos/photo3.jpg"}},
                { css:"image", template:imgTemplate, data:{src:"photos/photo4.jpg"}},
                { css:"image", template:imgTemplate, data:{src:"photos/photo5.jpg"}},
                { css:"image", template:imgTemplate, data:{src:"photos/photo6.jpg"}}
            ]
        },
        {}
    ]};
}

Теперь страница index.jsp может быть преобразована следующим образом:

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Webix - Front-End Events</title>
    <link rel="shortcut icon" href="favicon.ico" />
    <link rel="stylesheet" href="./codebase/webix.css" type="text/css" media="screen" charset="utf-8">
    <link rel="stylesheet" href="./codebase/myapp.css" type="text/css" media="screen" charset="utf-8">
    <script src="./codebase/webix.js" type="text/javascript" charset="utf-8"></script>
    <script src="./codebase/myapp.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
    <jsp:include page="header.jsp" />
    <jsp:include page="footer.jsp" />
    <div id='myapp'></div>

    <script type="text/javascript" charset="utf-8">
        webix.ui({
            container:"myapp",
            cols: [{}, {
                width: 1280,
                rows: [
                    {
                        height: 250,
                        borderless:true,
                        cols: [{
                            rows: [
                                { view: "template", template: "html->header", css: "header", borderless: true},
                                getTopMenu("upcoming")
                            ]},
                            getPhotos()
                        ]
                    },
                    { template: "content"},
                    getFooter()
                ]
            }, {}]
        });
    </script>
</body>
</html>

Thus, due to the use of Webix and Java-framework Struts 2 we’ve managed to quickly build a website with a user-friendly navigation between several pages. We’ve also easily added the footer, the header, a photo gallery and the main menu on the website pages. For creating a unique website style we’ve used an online Webix tool Skin Builder.

At the moment we’ve got a working site but without content. You will learn how to add content to the site from the second part of our tutorial.

It should be mentioned that Webix can be easily customized according to your requirements and can be effortlessly integrated with other libraries and various technologies. Webix library allows you to reveal your creativity in web development to the full extent.