- Spring MVC Cookbook
- Alex Bretet
- 2809字
- 2021-07-16 13:03:20
Setting up and customizing a responsive single page webdesign with Bootstrap
Bootstrap is a UI Framework initially created by Mark Otto and Jacob Thornton at Twitter. It is an amazing source of styles, icons, and behaviors, abstracted to define and enrich components. Bootstrap offers an easy, rational, and unified set of patterns for defining styles. It had no equivalent before. If you have never used it, you will be excited to get so much visual feedback from a quick definition of the DOM.
In June 2014 it was the number 1 project on GitHub with over 73,000 stars and more than 27,000 forks. Their documentation is very fluid and easy to go through.
Getting ready
In this recipe, we will use Bootstrap to set up the web-design basics for our CloudStreet Market project from an existing Bootstrap theme. We will remake the index.jsp
page to render a better looking welcome page that can be previewed with the following screenshot.

How to do it...
There are three major steps in this recipe:
- Installing a Bootstrap theme
- Customizing a Bootstrap theme
- Creating responsive content
From the Git Perspective in Eclipse, checkout the latest version of the branch v2.x.x
:

Installing a Bootstrap theme
- In the
chapter_2
directory, you can find afreeme.zip
archive. It is a responsive Bootstrap template downloadable for free. This zip comes from the bootstrapmaster.com website. - Inside this archive, you'll see a
css
directory, ajs
directory, animg
directory, and finally anindex.html
file. Opening theindex.html
file with a web browser should render the following home page:We are using this template as a base for the webapp module.
- All the JavaScript files located in the
freeme/js
directory have been copied over to the/cloudstreetmarket-webapp/src/main/webapp/js
directory. - All the CSS files located in the
freeme/css
directory have been copied over to the/cloudstreetmarket-webapp/src/main/webapp/css
directory. - All the pictures located in
freeme/img
have been copied over to the/cloudstreetmarket-webapp/src/main/webapp/img
directory. - The content of the
freeme/index.html
file has been copied and pasted into the/cloudstreetmarket-webapp/src/main/webapp/WEB-INF/jsp/index.jsp
file, as UTF-8. - Also, the
freeme/licence.txt
has been copied and pasted to the/cloudstreetmarket-webapp/src/main/webapp/WEB-INF/jsp
directory. - At this point, calling
http://localhost:8080/portal/index
with a web browser displayed exactly the same visual you saw earlier, but served by our application.
Customising a Bootstrap theme
We will detail in this section what has been done in order to adapt the downloaded template to our use case.
- All the images previously located in
cloudstreetmarket-webapp\src\main\webapp\img\logos
have been removed and replaced with six new images representing brands of technical products that we have been using through out this application and this book. - In the
index.jsp
file located in thecloudstreetmarket-webapp
module has been implemented the following changes:- The following two lines have been added to the top:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page isELIgnored="false" %>
- The
<!-- start: Meta -->
section has been replaced with the following:<!-- start: Meta --> <meta charset="utf-8"> <title>Spring MVC: CloudST Market</title> <meta name="description" content="Spring MVC CookBook: Cloud Street Market"/> <meta name="keywords" content="spring mvc, cookbook, packt publishing, microservices, angular.js" /> <meta name="author" content="Your name"/> <!-- end: Meta -->
- The
<!--start: Logo -->
section has been replaced with the following:<!--start: Logo --> <p class="logo span4"> CLOUD<span class="sub">ST</span><span>Market</span> </p> <!--end: Logo -->
- The navigation menu definition has been changed:
<ul class="nav"> <li class="active"><a href="index">Home</a></li> <li><a href="markets">Prices and markets</a></li> <li><a href="community">Community</a></li> <li><a href="sources">Sources</a></li> <li><a href="about">About</a></li> <li><a href="contact">Contact</a></li> </ul>
- The
<!-- start: Hero Unit -->
and<!-- start: Flexslider -->
sections have been removed and<p class="row">
coming after the navigation menu (<!--end: Navigation-->
) has been emptied:<!-- start: Row --> <p class="row"></p> <!-- end: Row -->
- The
<!-- start: Row -->
section to the<!-- end: Row -->
section, which is located after the<!-- end Clients List -->
, has been removed along with the<hr>
just after it. - The footer section
<!-- start: Footer Menu -->
to<!-- end: Footer Menu -->
has been replaced with the following content:<!-- start: Footer Menu --> <p id="footer-menu" class="hidden-tablet hidden-phone"> <!-- start: Container --> <p class="container"> <!-- start: Row --> <p class="row"> <!-- start: Footer Menu Logo --> <p class="span1"> <p class="logoSmall">CLOUD<span class="sub">ST</span><span>M!</span> </p> </p> <!-- end: Footer Menu Logo --> <!-- start: Footer Menu Links--> <p class="span10" > <p id="footer-menu-links"> <ul id="footer-nav" style="margin-left:35pt;"> <li><a href="index">Home</a></li> <li><a href="markets">Prices and markets</a></li> <li><a href="community">Community</a></li> <li><a href="sources">Sources</a></li> <li><a href="about">About</a></li> <li><a href="contact">Contact</a></li> </ul> </p> </p> <!-- end: Footer Menu Links--> <!-- start: Footer Menu Back To Top --> <p class="span1"> <p id="footer-menu-back-to-top"> <a href="#"></a> </p> </p> <!-- end: Footer Menu Back To Top --> </p> <!-- end: Row --> </p> <!-- end: Container --> </p> <!-- end: Footer Menu -->
- The section:
<!-- start: Photo Stream -->
to<!-- end: Photo Stream -->
has been replaced with:<!-- start: Leaderboard --> <p class="span3"> <h3>Leaderboard</h3> <p class="flickr-widget"> <script type="text/javascript" src=""></script> <p class="clear"></p> </p> </p> <!-- end: Leaderboard -->
- As a last change in the
index.jsp
file, the copyright section has been adapted.
- The following two lines have been added to the top:
- In the previously copied
cloudstreetmarket-webapp/src/main/webapp/css/style.css
file, the following classes have been added:.logo{ font-family: 'Droid Sans'; font-size: 24pt; color: #666; width:157pt; font-weight:bold; margin-top:18pt; margin-left:10pt; height:30pt; } .logo span{ position:relative;float:right; margin-top: 3pt; font-weight:normal; font-family: 'Boogaloo'; font- style:italic; color: #89C236; padding-right: 3pt; } .logo .sub { vertical-align: super; font-style:normal;font-size: 16pt; font-family: 'Droid Sans'; font-weight:bold; position: absolute; color: #888; margin:-4pt 0 -4pt 0; } .logoSmall{ font-family: 'Droid Sans'; font-size: 16pt; color: #888;width:80pt; font-weight:bold; margin-top:10pt;height:20pt; margin-right:30pt; } .logoSmall span{ position:relative; float:right; margin-top: 3pt; font-weight:normal;font-family: 'Boogaloo'; font-style:italic;color: #89C236; } .logoSmall .sub { vertical-align: super; font-style:normal; font-size: 10pt;font-family: 'Droid Sans';font-weight:bold;position: absolute; color: #666;margin:-2pt 0 -4pt 0; }
- At this point, after all these changes, restarting Tomcat and calling the same URL
http://localhost:8080/portal/index
resulted in the following state:
Creating responsive content
We will focus in this section on the changes that have been made to fill the welcome page with responsive content. By responsive, understand that the content will be rendered under a style appropriate for the device size and orientation.
- In the
index.jsp
file:- The
<p class="row">
has been added the following content:<p class='span12'> <p class="hero-unit hidden-phone"><p>Welcome to CloudStreet Market, the educational platform.</p></p> </p> <p class='span5'> <p id='landingGraphContainer'></p> <p id='tableMarketPrices'> <table class="table table-hover table-condensed table-bordered table-striped"> <thead> <tr> <th>Index</th> <th>Value</th> <th>Change</th> </tr> </thead> <tbody> <tr> <td>Dow Jones-IA</td><td>17,634.74</td> <td class='text-success'><b>-18.05</b></td> </tr> ... <tr> <td>FTSE MIB</td><td>18,965.41</td> <td class='text-error'><b>-182.86</b></td> </tr> ... </tbody> </table> </p> </p> <p id="containerCommunity" class='span7'> <p id="pRss3"></p> </p>
Note
In the previously added landingGraphContainer, we have inserted a generated graph that renders the evolution of specific markets during the last opened day. The graph uses the
morris.js
library (http://morrisjs.github.io/morris.js), which also relies on theraphael.js
library (https://cdnjs.com/libraries/raphael). - At the bottom of the file, the
<!-- start: Java Script -->
section to the<!-- end: Java Script -->
section has been added the following content:<script src="js/jquery-1.8.2.js"></script> <script src="js/bootstrap.js"></script> <script src="js/flexslider.js"></script> <script src="js/carousel.js"></script> <script def src="js/custom.js"></script> <script src="js/FeedEk.js"></script> <script src="js/raphael.js"></script> <script src="js/morris.min.js"></script> <script> $(function () { var financial_data = [ {"period": "08:00", "index": 66},{"period": "09:00", "index": 62}, {"period": "10:00", "index": 61},{"period": "11:00", "index": 66}, {"period": "12:00", "index": 67},{"period": "13:00", "index": 68}, {"period": "14:00", "index": 62},{"period": "15:00", "index": 61}, {"period": "16:00", "index": 61},{"period": "17:00", "index": 54} ]; Morris.Line({ element: 'landingGraphContainer', hideHover: 'auto', data: financial_data, ymax: 70, ymin: 50, pointSize: 3, hideHover:'always', xkey: 'period', xLabels: 'month', ykeys: ['index'], postUnits: '', parseTime: false, labels: ['Index'], resize: true, smooth: false, lineColors: ['#A52A2A'] }); }); </script>
- The
- In the
cloudstreetmarket-webapp\src\main\webapp\js
directory, themorris.min.js
andraphael.js
libraries have been copied and pasted from their respective websites. - Back to the
index.jsp
file:- The previously created
<p id='containerCommunity'>
has been filled with the following content:<p id="pRss3"> <ul class="feedEkList"> <li> <p class="itemTitle"> <p class="listUserIco"> <img src='img/young- lad.jpg'> </p> <span class="ico-white ico-up-arrow listActionIco actionBuy"></span> <a href="#">happyFace8</a> buys 6 <a href="#">NXT.L</a> at $3.00 <p class="itemDate">15/11/2014 11:12 AM</p> </p> </li> <li> <p class="itemTitle"> <p class="ico-user listUserIco"></p> <span class="ico-white ico-down-arrow listActionIco actionSell"></span> <a href="#">actionMan9</a> sells 6 <a href="#">CCH.L</a> at $12.00 <p class="itemDate">15/11/2014 10:46 AM</p> </p> </li> ... </ul> </p>
- The section here uses the feedEk jQuery plugin. It comes with its own CSS and JavaScript file.
- The previously created
- The
cloudstreetmarket-webapp\src\main\webapp\js
directory includes theFeedEk.js
file related to the feedEk jQuery plugin. This plugin can be found online (http://jquery-plugins.net/FeedEk/FeedEk.html). - The
cloudstreetmarket-webapp\src\main\webapp\css
directory also has the relatedFeedEk.css
file. - Still in
index.jsp
, under the<!-- start: CSS -->
comment, theFeedEk css
document has been added:<link href="css/FeedEk.css" rel="stylesheet">
- In the
style.css
file, before the first media query definition(@media only screen and (min-width: 960px)
), the following style definitions have been added:.listUserIco { background-color:#bbb; float:left; margin:0 7px 0 0; } .listActionIco { float:right; margin-top:-3px; } .actionSell { background-color:#FC9090; } .actionBuy { background-color:#8CDBA0; } #landingGraphContainer{ height:160px; padding: 0px 13px 0 10px; } .tableMarketPrices{ padding: 13px 13px 0 15px; }
- Finally, two new images (profile pictures) have been added to
cloudstreetmarket-webapp\src\main\webapp\img
. - Try to dynamically resize a browser window that renders:
http://localhost:8080/portal/index
. You should observe a responsive and adaptive style as in the following picture:
How it works...
To understand our Bootstrap deployment, we are going to review now how it has been installed as a predesigned theme. We will then discover some key features of the Bootstrap Framework—not only the implemented features because, logically enough, only a few features of the Framework can visually be used on one single page example.
The theme installation
The theme we have obtained is no more than a classical static theme, as you can find thousands of them over the Internet. They are made by web designers and distributed for free or commercially. This one is made with the basic structure of HTML files, a JS directory, a CSS directory, and an IMG directory.
The theme installation is quite straightforward to understand, since we have just placed the JavaScript files, CSS files, and images in their expected locations for our application.
Tip
The Bootstrap core features are self-contained in bootstrap.js
, bootstrap.css
, and bootstrap-responsive.css
. You should not really have to tweak these files directly.
Bootstrap highlights
The implemented theme (FreeME) uses Bootstrap 2. We are going to review a couple of features that have been implemented in the template and for the needs of our project.
Bootstrap scaffolding
The Bootstrap scaffolding helps with designing the HTML structure usually built from a grid model. The Bootstrap strategy on this topic is described in the following sections.
Grid system and responsive design
Bootstrap offers a styleframe to handle a page-specific grid system. The key point is in the default grid-system made up of 12 columns and designed for a 940px wide nonresponsive container.
The Bootstrap responsive features are activated with the use of <meta name="viewport"…>
tag and with the import of the boostrap-responsive.css
file. The container width can extend from 724px to 1170px in that case.
Tip
Also, below 767px, the columns become fluid and stack vertically.
These Bootstrap specifications define quite a drastic set of constraints but Bootstrap somehow creates an easy-to-understand design uniformity for its implementations.
In the case of our template, the viewport metatag is the following:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
Note
If you are not familiar with this tag, its main purpose is to define device-specific sizes in the document. From these sizes, rules are defined for orientation-specific and device-specific rendering. These rules that are bound to style definitions are called mediaqueries. You can find an example of a mediaquery in the style.css file:
/* Higher than 960 (desktop devices) ================================================================ */ @media only screen and (min-width: 960px) { ... #footer-menu { padding-left: 30px; padding-right: 30px; margin-left: -30px; margin-right: -30px; } ... }
This media query overrides the style that is specific to the id footer menu only where the device presents a width greater than 960px.
Defining columns
To define columns within the grid system, Bootstrap drives us towards the use of a row
p tagged as a row
class element. Then, the idea is to define subps marked with custom span*
class elements where the *
characters represents subpisions of the 12-column grid we have to deal with.
For example, consider the following two possible designs:

The two columns on the left example can be rendered from the DOM definition:
<p class="row"> <p class="span4">...</p> <p class="span8">...</p> </p>
The two columns on the right example can be rendered from the DOM definition:
<p class="row"> <p class="span6">...</p> <p class="span6">...</p> </p>
With this in mind, the grid of our welcome page is actually the following:

Offsetting and nesting
Offsetting a column allows you to create a fixed-sized decay corresponding to one or more invisible columns. For example, consider the following snippet:
<p class="row"> <p class="span6">...</p> <p class="span4 offset2">...</p> </p>
This DOM definition will correspond to the following columns:

A column can also be nested inside another column redefining a new row. The sum of the newly created columns must correspond to the parent's size:
<p class="row"> <p class="span6"> <p class="row"> <p class="span2">...</p> <p class="span4">...</p> </p> </p> </p>
Fluid gridding
We were saying earlier that, with Boostrap2, below 767px the columns become fluid and stack vertically. The template gridding can be changed from static to fluid turning .row
classes to .row-fluid
. Rather than fixed pixels sized columns, this system will use percentages.
Bootstrap CSS utilities
Bootstrap also provides a few pre-designed elements such as buttons, icons, tables, forms and also utilities to support typography or images.
Uniform Buttons
Default styled buttons can be created from the <a>
and <button>
tags with only addition of the .btn
class element. The created default gray button with a gradient can then be declined in different colour variations. For example, by default, the following classes combination:
.btn .btn-primary
: This produces an intense ultramarine blue button to identify the primary action among other buttons.btn .btn-info
: This produces a moderate turquoise blue button.btn .btn-success
: This produces a positive green button.btn .btn-warning
: This produces a warning orange button.btn .btn-danger
: This produces a dangerous red button.btn .btn-inverse
: This produces a black button with white text.btn .btn-link
: This produces a link while maintaining a button behavior
These buttons are also resizable declaratively by adding a .btn-large
class, adding a .btn-small
class, or adding a .btn-mini
class:

A button can be disabled by adding it as a disabled attribute. Similarly, a <a>
tagged button can be disabled with the addition of a .disabled
class. We didn't make use of buttons yet, but it is a great feature to be presented at this point.
Icons
Bootstrap 2 comes with an impressive set of 140 dark gray icons available as sprites and provided by Glyphicons:

Tip
These icons are normally available commercially but they are also usable for free as part of the Bootstrap product. However Bootstrap asks us to provide an optional backlink to http://glyphicons.com.
All these icons can be pulled from the DOM with a simple class within a <i>
tag such as <i class="icon-search"></i>
.
The amazing thing is that you can actually embed these icons in every suitable Bootstrap component. For example, the button definition: <a class="btn btn-mini" href="#"><i class="icon-star"></i> Star</a>
, produces the following:

Tables
We have implemented a Bootstrap table for the market activity overview. We have basically shaped the following table:
<table class="table table-hover table-condensed table-bordered table-striped"> <thead> <tr><th>Index</th> <th>Value</th> <th>Change</th></tr> </thead> <tbody> <tr><td>...</td> <td>...</td> <td>...</td> </tr> </tbody> </table>
In the same way as we can define a button class overridden with customization classes, we have defined a generic Bootstrap table with the class .table
, and then we have made use of the following customization classes:
.table .table-hover
: This enables a hover state on table rows within a<tbody>
.table .table-condensed
: This makes tables more compact.table .table-bordered
: This adds borders and rounded corners to the table.table .table-striped
: This adds zebra-striping to any table row within the<tbody>
Bootstrap components
The framework has other pre-designed elements identified as Components. Among them, dropdowns, button groups, breadcrumbs, pagination, Navbars, labels and badges, thumbnails, alerts, progress bars, and so on. Here we only present some of them:
Navbars
The Bootstrap navigation bars provide support for a basic navigation menu. They are not by default fixed to the top of the page; they must be included in a .container
. The code is as follows:
<p class="navbar navbar-inverse"> <p class="navbar-inner"> ... <ul class="nav"> <li class="active"><a href="index">Home</a></li> <li><a href="markets">Prices and markets</a></li> <li><a href="community">Community</a></li> <li><a href="sources">Sources</a></li> <li><a href="about">About</a></li> <li><a href="contact">Contact</a></li> </ul> ...
The most basic feature in the navbar is the activable link:

The example above can be designed from the following DOM definition:
<ul class="nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">Link</a></li> </ul>
We strongly recommend reading the Bootstrap documentation. More details can be found on how to implement other features. For example, Bootstrap provides tools for:
- Form elements such as input texts, search fields, and submit buttons.
- Different positioning variations such as fixed-to-top (with
.navbar-fixed-top
), fixed-to-bottom (with.navbar-fixed-bottom
), at the opposite of the full-width navbar that scrolls away with the page (with.navbar-static-top
). - Collapsible responsive navbars (
.nav-collapse.collapse
) that allow significant space savings. With the use of the data-toggle HTML5 attribute, dynamic handling is performed with no extra JavaScript configuration.
Hero units
There was a hero unit defined in the provided template. We've just moved it a bit to suit our responsive needs.
It is a lightweight, flexible component to showcase key content on your site.

The example above can be designed from the following DOM definition:
<p class="hero-unit"><p>Welcome to CloudStreet Market, the educational platform.</p></p>
Alerts
Bootstrap alerts are great to quickly generate a predefined style for a warning message or another contextual message. A Bootstrap alert comes with an optional dismiss button (which will hide the alert with no extraJavaScript configuration). The code is as follows:
<p class="alert"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>Warning!</strong> Best check yo self, you're not looking too good. </p>
This definition produces the output presented here:

An Alert is defined with the class .alert
on a <p>
tag , from which contextual color variations can be set up, providing extra overriding classes such as .alert-success
, .alert-info
, or .alert-error
.
Badges and labels
Bootstrap labels are very nice for enriching content. They render particularly well in list or in tables. Find here an overview of the possible contextual variations:

The labels here would be defined with:
<span class="label">Default</span> <span class="label label-success">Success</span> <span class="label label-important">Important</span> …
The badges would be defined with:
<span class="badge">1</span> <span class="badge badge-warning">4</span> <span class="badge badge-important">6</span> …
There's more...
There is much more to Bootstrap than this tiny overview for enriching official documentation. Again, the official documentation is very well done and very comprehensible.
Visit http://getbootstrap.com for the documentation related to the latest supported version of the framework. Go to http://getbootstrap.com/2.3.2 for the documentation related to the version we use in our project.
We will implement more features in the coming chapters and care will be taken to highlight them wherever possible.
See also
If you like Bootstrap and feel you want to use it in your projects, you must consider Version 3.
Tip
Bootstrap 3 is not directly retro-compatible with Bootstrap 2 but it implements a very similar gridding system and slightly different markups.
- Bootstrap 3 new features: Here's a preview of important changes from Bootstrap 2 to Bootstrap 3.
- New flat-styled design: The new design is easily noticeable with the end of 3D and textures on buttons, navbars and other menus. They have now gone for a new flat style with no gradients. It certainly goes along with the actual global design trend.
- Column naming span* renamed to col-*: In addition to the row-fluid class that is no longer available as such (all rows are now fluid automatically) for less confusion, the column naming pattern has been rethought for more consistency.
- Mobile-first: The responsive features of the framework are now natively included in the
bootstrap.js
andbootstrap.css
files (there is no morebootstrap-responsive.js
orbootstrap-responsive.css
). It is now possible to drive media-query duties directly from the DOM using a set of new device-specific classes.
- Node.js Design Patterns
- Python for Secret Agents:Volume II
- Visual Basic 6.0程序設計計算機組裝與維修
- C語言程序設計
- Ray分布式機器學習:利用Ray進行大模型的數據處理、訓練、推理和部署
- Learn Swift by Building Applications
- C語言程序設計
- Java程序設計入門
- Java面向對象程序設計
- Access 2010中文版項目教程
- Web App Testing Using Knockout.JS
- 零基礎學Java(第5版)
- HTML5程序開發范例寶典
- C++ Data Structures and Algorithm Design Principles
- Mastering PostgreSQL 11(Second Edition)