Spring MVC Cookbook 1st Edition Bretet Alex pdf download
Spring MVC Cookbook 1st Edition Bretet Alex pdf download
download
https://textbookfull.com/product/spring-mvc-cookbook-1st-edition-
bretet-alex/
https://textbookfull.com/product/spring-cookbook-1st-edition-
jaglale-jerome/
https://textbookfull.com/product/pro-spring-mvc-with-webflux-web-
development-in-spring-framework-5-and-spring-boot-2-2nd-edition-
marten-deinum/
https://textbookfull.com/product/pro-spring-mvc-with-webflux-web-
development-in-spring-framework-5-and-spring-boot-2-2nd-edition-
marten-deinum-2/
https://textbookfull.com/product/pro-spring-mvc-with-webflux-web-
development-in-spring-framework-5-and-spring-boot-2-second-
edition-marten-deinum-iuliana-cosmina/
Quarkus Cookbook Kubernetes Optimized Java Solutions
1st Edition Alex Soto Bueno Jason Porter
https://textbookfull.com/product/quarkus-cookbook-kubernetes-
optimized-java-solutions-1st-edition-alex-soto-bueno-jason-
porter/
https://textbookfull.com/product/quarkus-cookbook-kubernetes-
optimized-java-solutions-1st-edition-alex-soto-bueno-jason-
porter-2/
https://textbookfull.com/product/oauth-2-0-cookbook-protect-your-
web-applications-using-spring-security-nascimento/
https://textbookfull.com/product/essential-docker-for-asp-net-
core-mvc-1st-edition-adam-freeman/
https://textbookfull.com/product/a-postcard-from-paris-
postcard-2-1st-edition-alex-brown-brown-alex/
1
Spring MVC Cookbook
Alex Bretet
BIRMINGHAM - MUMBAI
Spring MVC Cookbook
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the publisher,
except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or alleged to be caused directly or
indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies
and products mentioned in this book by the appropriate use of capitals. However, Packt
Publishing cannot guarantee the accuracy of this information.
ISBN 978-1-78439-641-1
www.packtpub.com
Credits
Reviewers Proofreader
Bartosz Kielczewski Safis Editing
David Mendoza
Indexer
Commissioning Editor Monica Ajmera Mehta
Amarabha Banerjee
Production Coordinator
Acquisition Editor Nilesh Mohite
Manish Nainani
Cover Work
Content Development Editor Nilesh Mohite
Mayur Pawanikar
Technical Editor
Pranjali Mistry
Copy Editor
Neha Vyas
About the Author
Alex Bretet is a certified Java and Spring Integration engineer. Currently working at
Thunderhead, a pioneer company and global actor among SaaS providers, he has a rich
developer background from different industries including energy, insurance, finance, and
the Internet.
He also defends a number of open source initiatives and indeed Spring technologies,
whose pragmatism constantly disrupts the most established practices and offers valuable
alternatives for the benefit of all.
I would like first to thank all the people who have been directly related to
this book, starting with all the reviewers, content development editors,
technical and acquisition editors.
My thoughts go to my French engineering school and all the people I've met
since then who have expressed and communicated their enthusiasm for the
technology.
I am very grateful for being able to work in the IT industry nowadays. Thank
you to all the elements around me that supported me going in this direction.
When my interest for this topic grew, I couldn't imagine making a career out
of it.
Writing this book has been a long project. I must mention my partner,
Helena, for her patience and support throughout these months; my family
and friends, who have been a source of encouragement; my dad, a source
of inspiration.
My best regards go to Packt Publishing for producing this book and
endorsing the project.
I acknowledge the expertise from the engineers at Pivotal Software, Inc. and
the Spring community, their approachable set of documentation and their
official references.
Finally, I want to thank you, who are reading these lines and have probably
purchased this book. I hope it will provide you help, spark, and Big Picture.
About the Reviewer
David Mendoza is a software engineer working on web development since 1999 with Java.
He started his journey with JSPs and Servlets, creating a custom web framework to later find
AppFuse, which introduced him to Spring and Struts. Then, he moved to Spring MVC and never
looked back. David has worked as a Java consultant in Mexico, the United States, Canada,
Venezuela, and Spain with companies such as ING Bank, Citi, and Telefonica. He is currently
working for Southwestern Adventist University, a private university south of Dallas, Texas,
where he's responsible for their entire web platform.
www.PacktPub.com
At www.PacktPub.com, you can also read a collection of free technical articles, sign up
for a range of free newsletters and receive exclusive discounts and offers on Packt books
and eBooks.
TM
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book
library. Here, you can search, access, and read Packt's entire library of books.
Why Subscribe?
ff Fully searchable across every book published by Packt
ff Copy and paste, print, and bookmark content
ff On demand and accessible via a web browser
Table of Contents
Preface iii
Chapter 1: Setup Routine for an Enterprise Spring Application 1
Introduction 1
Installing Eclipse for JEE Developers and Java SE 8 3
Configuring Eclipse for Java 8, Maven 3, and Tomcat 8 5
Defining the project structure with Maven 15
Installing Spring, Spring MVC, and a web structure 29
Chapter 2: Designing a Microservice Architecture with Spring MVC 41
Introduction 41
Configuring a controller with simple URL mapping 43
Configuring a fallback controller using ViewResolver 58
Setting up and customizing a responsive single page webdesign
with Bootstrap 63
Displaying a model in the View, using the JSTL 83
Defining a common WebContentInterceptor 94
Designing a client-side MVC pattern with AngularJS 101
Chapter 3: Working with Java Persistence and Entities 115
Introduction 115
Configuring the Java Persistence API in Spring 117
Defining useful EJB3 entities and relationships 121
Making use of the JPA and Spring Data JPA 133
Chapter 4: Building a REST API for a Stateless Architecture 141
Introduction 141
Binding requests and marshalling responses 142
Configuring content-negotiation (JSON, XML, and so on) 154
Adding pagination, filters, and sorting capabilities 159
i
Table of Contents
Handling exceptions globally 173
Documenting and exposing an API with Swagger 180
Chapter 5: Authenticating with Spring MVC 187
Introduction 187
Configuring Apache HTTP to proxy your Tomcat(s) 188
Adapting users and roles to Spring Security 197
Authenticating over a BASIC scheme 208
Authenticating with a third-party OAuth2 scheme 218
Storing credentials in a REST environment 237
Authorizing on services and controllers 247
Chapter 6: Implementing HATEOAS 263
Introduction 263
Turning DTOs into Spring HATEOAS resources 265
Building links for a hypermedia-driven API 273
Choosing a strategy to expose JPA Entities 282
Retrieving data from a third-party API with OAuth 289
Chapter 7: Developing CRUD Operations and Validations 297
Introduction 297
Extending REST handlers to all HTTP methods 298
Validating resources using bean validation support 311
Internationalizing messages and contents for REST 327
Validating client-side forms with HTML5 AngularJS 337
Chapter 8: Communicating Through WebSockets and STOMP 345
Introduction 345
Streaming social events with STOMP over SockJS 346
Using RabbitMQ as a multiprotocol message broker 360
Stacking and consuming tasks with RabbitMQ and AMQP 367
Securing messages with Spring Session and Redis 373
Chapter 9: Testing and Troubleshooting 393
Introduction 393
Automating Database Migrations with FlyWay 394
Unit testing with Mockito and Maven Surefire 400
Integration testing with Cargo, Rest-assured, and Maven failsafe 408
Injecting Spring Beans into integration tests 417
Modern application Logging with Log4j2 422
Index 431
ii
Preface
Welcome to the singular universe of Spring MVC Cookbook. We hope you are ready for this
journey that will take you through modern Spring web development practices. We have been
building the cloudstreetmarket.com , a stock exchange platform with social capabilities.
We are about to take you through each step of its development process.
This chapter is more than a guide through the first development stage of the book's
application, Cloud Street Market. A bunch of standard practices are presented here as a
routine for developers toward enterprise Spring applications.
Chapter 2, Designing a Microservice Architecture with Spring MVC, is a slightly longer chapter.
It covers the core principles of Spring MVC, such as its request flow or the central role of
DispatcherServlet. It is also about learning how to configure Spring MVC controllers and
controller method-handlers with an extended source of information related to a controller's
annotations.
In the path of a Microservice architecture, we install Spring and Spring MVC across modules
and web projects to build functional units that are easy to deploy and easy to scale. In this
perspective, we are going to shape our application with a web module that is responsible for
serving a Twitter Bootstrap template along with another web module specialized in REST Web
Services.
iii
Preface
In this chapter, you also will learn how to transfer the model from controllers to JSP views
using the JSTL and how to design a JavaScript MVC pattern with AngularJS.
Chapter 3, Working with Java Persistence and Entities, gives you a glimpse of . It is necessary
at this stage to learn how persistent data can be handled in a Spring ecosystem and thus in a
Spring MVC application. We will see how to configure, a JPA persistence provider (Hibernate)
from dataSource and entityManagerFactory in Spring. You will learn how to build a beneficial JPA
object-relational mapping from EJB3 Entities and then how to query repositories using Spring
Data JPA.
Chapter 4, Building a REST API for a Stateless Architecture, provides insights into Spring MVC
as a REST Web Services engine. We will see the amazing support the Framework provides,
with several annotations acting as doorknobs on method-handlers to abstract web-related
logic and thus only focus on the business. This principle appears with annotations for request
binding (binding of parameters, URL paths, headers, and so on) and Response Marshalling
and also for integrated support of Spring Data pagination.
This chapter also presents how to set up exception handling as part of Spring MVC to translate
predefined exception-Types into generic error responses. You will understand how to configure
the content negotiation, an important bit for REST APIs, and finally, how to expose and
document REST Endpoints using Swagger and the Swagger UI.
Chapter 6, Implementing HATEOAS, demonstrates how to take a RESTful Spring MVC API a
step further. A Hypermedia-driven application provides links along with every single requested
resource. These links reflect URLs of related resources. They provide to the user client
(whatever type of client it may be) real-time navigation options—precious documentation that
is also the actual implementation.
We will see how to build such links from JPA Entities associations or from the controller layer.
Chapter 7, Developing CRUD Operations and Validations, goes into the more advanced concepts
of Spring MVC. Presenting the tools and techniques that support interactive HTTP methods
(PUT, POST, and DELETE), we will lean on the HTTP1/1 specification (RFC 7231 Semantics and
Content) to learn how to return the appropriate response status code or headers.
Our use of the Spring Validator together with the ValidationUtils utility class provides a
compliant implementation of the validation-related JSR-303 and JSR-349 specifications.
iv
Preface
The last recipe is the place where an internationalization (I18N) of messages and content
happens. We also present a client-side implementation, with AngularJS, that relies on
published internationalization web services.
You will learn how to dynamically create private queues and how to get authenticated clients
to post and receive messages from these private queues.
Chapter 9, Testing and Troubleshooting, introduces a set of tools and common practices to
maintain, debug, and improve an application's state. As a way of finishing this journey, we will
visit how to upgrade the database schema from one version of the application to another as
part of the Maven builds with the Flyway Maven Plugin. We will also go through how to write
and automate unit tests (with Maven Surefire and Mockito) and integration tests (using a set
of libraries such as Cargo, Rest-assured, and Maven Failsafe).
The last recipe provides insightful guidelines in order to apply Log4j2 globally as a logging
framework, as it is more than important to rely on a relevant logging solution to troubleshoot
efficiently, whichever environment we may be on.
Also, and even more importantly, you will see that we use the Git versioning system to manage
(and work from) the codebase for each chapter. Your local Git repository will correspond to
the remote repository for the project (on GitHub), and you will be required to reach out to this
remote repository.
To rephrase the hardware and software list, we will support three operating systems
throughout the book: MS Windows, Linux, and Mac OS X.
v
Preface
We believed that most of you, with an interest in a cookbook about Spring MVC, are primarily
looking for a starter kit and a toolbox to develop modern Spring-based web applications.
We also believed that most of you would tend to prefer conceptualizing from experience
and not from theory. Nowadays, it is clear that people have different mindsets and learning
preferences.
Under this light, chapters will have increasing exigence levels one after the other, from
the intuitive Chapter 1, Setup Routine for an Enterprise Spring Application, to the more
challenging Chapter 8, Communicating Through WebSockets and STOMP. The initial few
chapters will definitely suit a broader audience of Java developers than the final ones.
Having said this, we have everything in this book! The prerequisites here are mostly pointing
to external sources of information. And our showcase application is running and waiting for
you to dive into it and understand how things work.
More generally, we assume you to be a Java developer with prior web experience. Beyond
everything, we expect you to have a motivated interest in learning Spring web technologies.
Sections
In this book, you will find several headings that appear frequently (Getting ready, How to do it,
How it works, There's more, and See also).
To give clear instructions on how to complete a recipe, we use these sections as follows:
Getting ready
This section tells you what to expect in the recipe, and describes how to set up any software or
any preliminary settings required for the recipe.
How to do it…
This section contains the steps required to follow the recipe.
How it works…
This section usually consists of a detailed explanation of what happened in the previous
section.
vi
Preface
There's more…
This section consists of additional information about the recipe in order to make the reader
more knowledgeable about the recipe.
See also
This section provides helpful links to other useful information for the recipe.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of
information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We are going
to review the configuration changes applied to the cloudstreetmarket-api webapp in
order to set up a type conversion".
New terms and important words are shown in bold. Words that you see on the screen,
for example, in menus or dialog boxes, appear in the text like this: "Then select Add and
Remove… from the right-click menu."
vii
Preface
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this
book—what you liked or disliked. Reader feedback is important for us as it helps us develop
titles that you will really get the most out of.
If there is a topic that you have expertise in and you are interested in either writing or
contributing to a book, see our author guide at www.packtpub.com/authors.
The master branch will probably continue to evolve but the chapters' branches will always
match the book.
Feel absolutely free to fork the repository for whichever reason you might have. We also
welcome Pull Requests, if you feel things could be made differently. Also, a big amount of
tests are yet to be added.
https://github.com/alex-bretet/cloudstreetmarket.com
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to
get the most from your purchase.
viii
Preface
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen.
If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be
grateful if you could report this to us. By doing so, you can save other readers from frustration
and help us improve subsequent versions of this book. If you find any errata, please report them
by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on
the Errata Submission Form link, and entering the details of your errata. Once your errata are
verified, your submission will be accepted and the errata will be uploaded to our website or
added to any list of existing errata under the Errata section of that title.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At
Packt, we take the protection of our copyright and licenses very seriously. If you come across
any illegal copies of our works in any form on the Internet, please provide us with the location
address or website name immediately so that we can pursue a remedy.
We appreciate your help in protecting our authors and our ability to bring you valuable
content.
Questions
If you have a problem with any aspect of this book, you can contact us at questions@
packtpub.com, and we will do our best to address the problem.
ix
Setup Routine for an
1
Enterprise Spring
Application
The topics covered in this chapter correspond to this four-step routine:
Introduction
Before we dive into this routine for initializing the developments, we are going to answer, as an
introduction, a couple of questions that should help you understand the routine better.
Remember that the result of this chapter will also constitute the minimal starting point for all
the further chapters.
1
Setup Routine for an Enterprise Spring Application
The idea beyond the routine itself is to share a bootstrap methodology to kick off the project
base that you need now and that will support your needs tomorrow. The routine is also a key
to drive your product thoughts toward a sustainable architecture which will be easy to refactor
and to maintain.
Setting up a new project for an enterprise-level architecture will not kill the excitement
and creativity!
Choosing Maven secures these points and fulfills our project's need to make our project
reusable, secure, and testable (under automation).
2
Chapter 1
Getting ready
This first recipe could appear redundant or unnecessary in regard to your education or
experience. However, having a uniform configuration all along this book will provide you with
many benefits.
For instance, you will certainly avoid unidentified bugs (integration or development). You will
also experience the same interfaces as seen in the presented screenshots. Also, because
the third-party products are living, you will not have the surprise of encountering unexpected
screens or windows.
How to do it...
The whole first chapter in general requires a step by step cooperation. From the next chapter,
we will be using GIT and your active involvement will be lightened.
3
Setup Routine for an Enterprise Spring Application
2. Extract the downloaded archive into an eclipse directory from the steps:
C:\Users\{system.username}\eclipse: Extract it here if you are
on Windows
/home/usr/{system.username}/eclipse: Extract it here if you are
on Linux
/Users/{system.username}/eclipse: Extract it here if you are on
Mac OS X
4. Install JDK 8 on the operating system of your choice using the following instructions:
On Windows, this is a monitored installation initiated with an executable file:
1. Execute the downloaded file and wait until you reach the next installation step
2. On the installation-step window, pay attention to the destination directory
and change it to C:\java\jdk1.8.X_XX (X_XX refers to the latest current
version here. We will be using jdk1.8.0_25 in this book. Also, it won't be
necessary to install an external JRE, so uncheck the public JRE feature.)
4
Chapter 1
4. Unpack the archive with the following command line targeting the name of
your archive: tar zxvf jdk-8u25-linux-i586.tar.gz (this example is
for a binary archive corresponding to a Linux x86 machine)
You must end up with the /usr/java/jdk1.8.0_25 directory structure that contains the
/bin, /db, /jre, /include subdirectories.
How it works…
In this section we are going to provide more insights about the version of Eclipse we used and
about how we chose this specific version of JVM.
Choosing a JVM
The choice of the JVM implementation could be discussed over performance, memory
management, garbage collection, and optimization capabilities.
There are lots of different JVM implementations, including couple of open source solutions
such as OpenJDK and IcedTea (RedHat). The choice of JVM really depends on the
application's requirements. We have chosen Oracle Hotspot from experience and from
reference implementations deployed in production; this JVM implementation can be trusted
for a wide range of generic purposes. Hotspot also behaves very well if you have to run Java UI
applications. Eclipse is one of them.
Java SE 8
If you haven't already played with Scala or Clojure, it is time that you took the functional
programming train with Java! With Java SE 8, Lambda expressions reduce the amount of code
dramatically providing improved readability and maintainability. We won't implement this Java 8
feature, but since it is probably the most popular, it must be highlighted as it has given a massive
credit to the paradigm change. It is important, nowadays, to be familiar with these patterns.
Getting ready
Once the different products are installed, there are a couple of steps that we need to follow,
mainly to make Eclipse work properly with Java SE 8, Maven 3, and Tomcat 8. In this recipe,
we will also look at how to customize the Eclipse configuration file (Eclipse.ini) in order
to make the most of the platform that runs Java and to make sure that it will cope with any
significant growth of the application.
How to do it...
Let's take a look at the following steps to configure Eclipse on your desktop:
1. You can start by creating a shortcut on your desktop to point to the Eclipse
executable:
On Windows, the executable file is Eclipse.exe and is located at the
eclipse directory root
On Linux/Mac, the file is named Eclipse and is also is located at the
eclipse directory root
The Eclipse community recommends to specify the path to our JVM here.
Hence, depending on your system, add the following two lines at the top of
the file:
-vmargs
-Xms128m
6
Chapter 1
-Xmx512m
-Xverify:none
-Dosgi.requiredJavaVersion=1.6
-XX:MaxGCPauseMillis=10
-XX:MaxHeapFreeRatio=70
-XX:+UseConcMarkSweepGC
-XX:+CMSIncrementalMode
-XX:+CMSIncrementalPacing
If your machine has less than 2 GB of RAM, you can still enter this set of options
without overriding the default –Xms and –Xmx arguments.
3. After this we will go through the following steps to start Eclipse and set the
workspace:
Launch the executable described in the Step 2.
For our project, specify the path: <home-directory>/workspace
This path is different for each Operating System:
The workspace is the place from where you manage your Java
projects. It can be specific to one application, but not necessarily.
After completing these steps, you should end up with the following configuration:
5. For the User Settings field, create a settings.xml file in the .m2
directory: <home-directory>/.m2/settings.xml.
8
Chapter 1
7. Go back to the navigation panel and click on Maven. Follow the configuration
given in this screenshot:
9
Setup Routine for an Enterprise Spring Application
7. Now we will install Tomcat 8 in the Eclipse IDE. For this, go through these steps:
1. Download a ZIP archive for the latest Core version of Tomcat8 from the
Tomcat website: http://tomcat.apache.org/download-80.cgi.
2. Extract the downloaded archive to the following directory:
On Windows, extract the archive at C:\tomcat8
On Linux, extract the archive at /home/usr/{system.username}/
tomcat8
On Mac OS X, extract the archive at /Users/{system.username}/
tomcat8
10
Random documents with unrelated
content Scribd suggests to you:
conséquences, maintenant dévoilées, de la philosophie qui les a
également asservis!
Car tel est le but, sinon atteint, du moins visé, du nouvel ouvrage de
Rémusat. Maintenir le fondement de la philosophie rationaliste, de
cette philosophie qui n'est pas autre chose que le protestantisme en
métaphysique, mais échapper aux conséquences panthéistiques de
cette philosophie, devant lesquelles le monde, plus chrétien encore
qu'il ne pense, se cabre encore avec effroi, tel est le but que s'est
proposé Rémusat dans sa monographie intellectuelle de saint
Anselme. Pourquoi s'est-il donné un pareil but? A-t-il tremblé, dans
sa conscience logique ou dans sa conscience morale, en voyant les
conséquences terribles dégagées enfin de ce qu'il crut la vérité si
longtemps? Est-ce la chose en soi qui l'a révolté, ou l'effet actuel de
cette chose sur le monde qui lui a paru compromettant? Nous
n'avons point à faire un travail d'Hercule en sondant les reins ou le
cœur des philosophes, ces étables d'Augias humaines. Mais toujours
est-il que ce but impossible d'une charte taillée entre un principe et
sa conclusion, Rémusat se l'est donné. Très au courant du
mouvement d'idées qui s'est produit du côté du Rhin, et modifié par
ces idées, c'est par l'Allemagne et sur les pas de l'Allemagne qu'il est
entré dans l'étude du moyen âge et de la scolastique. Mauvaise
porte et mauvais guide pour y pénétrer! Ce n'est pas l'instinct de la
pensée chrétienne qui l'a poussé de ce côté et qui l'a fait aller
d'Abélard, de l'hérétique Abélard, jusqu'à l'orthodoxe Anselme.
L'Allemagne, curieuse comme si elle n'avait pas d'idées à elle, et
personnelle au point de chercher ses idées partout, l'Allemagne
depuis longtemps cherchait l'or que Leibnitz avait dit briller dans le
fumier du moyen âge. Elle l'avait trouvé; mais en mettant la main
dessus, comme Galatée touchant Pygmalion, elle avait dit: «C'est
moi encore!» Rémusat, plus ou moins hegelien, avait pu lire dans
Hegel: «Anselme, dans son célèbre argument de l'existence de Dieu,
montra, le premier, la pensée dans son opposition à l'être et chercha
à en prouver l'identité.» Après un pareil hommage rendu par le
grand théoricien de l'identité de la pensée et de l'être, qui semblait
reconnaître dans le saint métaphysicien une paternité éloignée,
comment ne pas se préoccuper de cet homme, qui, quoique saint,
avait été philosophe, et qui, par Descartes, touchait à Hegel?
Rémusat a beau nous dire, avec une intention qui ne trompe
personne: «Descartes ne serait pas aisément convenu que saint
Anselme fut un de ses maîtres», tout ce qui s'occupe de philosophie
n'en sait pas moins que l'argument de saint Anselme sur l'existence
de Dieu (et l'existence de Dieu c'est toutes les questions de la
philosophie dans une seule) est le même dans le Monologium que
dans les Méditations. Par la nature de son esprit, par la prétention
de son système, par l'isolante force ou faiblesse de son principe: «Je
pense, donc je suis,» Descartes est l'orgueil de la personnalité
solitaire. Avec la hache de son scepticisme il a coupé tous les câbles
qui attachent la pensée humaine à la tradition. Robinson intellectuel
d'un désert qu'il a fait autour de sa propre pensée, il a voulu créer
tout dans le vide qu'il avait creusé. Il est évident qu'un tel homme
n'admet ni ancêtres ni prédécesseurs; mais il n'est pas moins
évident non plus que si la parenté n'est pas reconnue par la volonté
elle subsiste dans la pensée, car si elle n'y était pas, croyez-le bien!
les philosophes modernes, plus ou moins issus de Descartes,
auraient laissé bien tranquille dans sa niche de saint le grand
Anselme de Cantorbéry, et ne lui auraient pas fait cette gloire
posthume qu'ils se sont mis à lui faire, moins pour lui encore que
pour eux!
I
Voici un de ces ouvrages que la critique n'est pas obligée d'ajuster,
en se pressant, au passage. Un pareil livre ne passe pas. Il existe
depuis 1441 à peu près, et il est bien probable qu'il vivra autant que
le sentiment du christianisme qui l'a inspiré et que le sentiment de la
langue charmante dans laquelle il a été traduit. C'est le livre de
l'Internelle Consolacion[64], sorti au XVe siècle de l'Imitation de
Jésus-Christ. Traduction, imitation, paraphrase de cet ouvrage
célèbre, dans la langue naïve et prime-sautière que le moyen âge a
créée, ceci, tel qu'on nous l'exhume et tel que Charles d'Héricault et
Moland le publient, nous paraît supérieur, non seulement à toutes les
traductions que l'on a faites, depuis, de l'Imitation, mais, le croira-t-
on, et n'est-ce pas là une de ces choses qui vont paraître d'une
singularité un peu forte à beaucoup d'esprits? supérieur au texte
même si vanté de l'original.
II
C'est Fontenelle, cette belle autorité religieuse et même littéraire, qui
a écrit le mot fameux et qu'on cite toujours quand il est question de
l'Imitation: «L'Imitation est le premier des livres humains, puisque
l'Évangile n'est pas de main d'homme.» Seulement, rappelons-nous
que quand il grava cette ingénieuse inscription lapidaire pour les
rhétoriques des temps futurs il s'agissait de la traduction de
monsieur son oncle, le grand Corneille, et que, sans cette
circonstance de famille, l'Imitation lui aurait paru moins sublime. De
plus, avec tout son esprit, Fontenelle disait deux bêtises dans son
mot fameux, si ce n'est trois, ce pauvre Tircis!
É
D'abord, l'Évangile n'est point écrit des mains de Jésus-Christ, mais
de la main de saint Mathieu, de saint Luc, de saint Marc et de saint
Jean, et, d'ailleurs, Jésus-Christ était aussi un homme. Inspirés, oui!
martyrs plus tard, c'est-à-dire témoins, les évangélistes ne sont que
des hommes... inspirés! et par ce côté le mot de Fontenelle est
pourpré et faux comme l'est un madrigal. Il n'en était pas un
pourtant;—c'était une précaution. On sait s'ils s'entendent en
précautions, messieurs les philosophes!
III
Mais, faux par l'accessoire, le mot est faux aussi en lui-même.
L'Imitation n'est point et ne saurait être le premier des livres
humains, car il n'est pas humain de confondre la cité domestique et
la cité monastique comme le faisait le vieux Tircis, qui ne comprenait
pas plus l'une que l'autre, et comme le feraient tous ceux qui ne
verraient pas que l'Imitation est une œuvre exclusivement monacale.
Pour qui la lit, en effet, avec le genre d'esprit et d'attention qui
pénètre les livres, celui-ci, pâle, exsangue, d'un amour exténué, avec
son expression bien plus métaphysique que vivante, s'adresse
formellement et essentiellement à des moines, tournant le dos au
monde proprement dit, voulant rendre le correct plus correct,
proposant—et il ne faut pas s'y tromper! car la méprise serait
grossière,—la vie parfaite et de conseil, et non pas la vie de
précepte. Si l'on avait dit de l'Imitation qu'elle était le premier des
livres de moines, l'erreur eût été moindre; mais ce n'eût pas été le
vrai encore.
IV
Eh bien, par ce côté-là comme par l'autre, par la forme comme par
le fond, l'Imitation n'est pas en rapport avec l'admiration
traditionnelle qu'elle a inspirée! Un homme de nos jours, tout
ensemble métaphysicien et poète, et dont l'habitude n'est pas de
céder aux influences du monde qui l'entoure, a dit de l'Imitation
qu'elle avait été laissée sur le seuil du moyen âge pour donner
l'envie d'y pénétrer. S'il avait parlé en ces termes de l'Internelle
Consolacion, dans sa langue artiste et populaire, le mot aurait peut-
être été vrai; mais, appliqué au texte latin de l'original, un tel mot
n'est plus que poétique. Non! l'Imitation ne traduit pas le moyen âge
avec cette puissance qu'il est impossible d'y résister. Cette vignette
de l'âme et de Jésus-Christ, qui ressemble à la patiente enluminure
des marges d'un missel, n'égale pas, sous son latin de cloître
harmonieux et limpide, les figures idéales, mais si profondément
touchantes dans leur sainteté émaciée et splendide, de frère Ange
de Fiesole (un moine aussi), le plus profond interprète du moyen
âge, ni même les lignes expressives et nettes d'Overbeck, aussi loin
pourtant que l'homme l'est de l'ange, du monastique Angelico.
V
Ainsi, nous n'hésitons point à le répéter, de toutes les traductions qui
ont été faites du livre de l'Imitation, et elles sont nombreuses,—
depuis celle du chancelier de Marillac, rééditée de nos jours, et dans
laquelle on a une naïveté bien inférieure à celle de la traduction du
XVe siècle, jusqu'à celle que s'imposa Lamennais (il était chrétien
alors), pour mortifier, je crois, son génie,—la meilleure, celle-là qui
complète le mieux son auteur en le traduisant, est celle que
d'Héricault et Moland nous ressuscitent. Toutes les autres ne valent
pas le texte, parce qu'elles veulent seulement nous le donner. Malgré
le succès qui s'est attaché à l'entreprise de Lamennais, comme s'il
était de la destinée de l'Imitation, ce livre heureux, de créer des
succès à ses traducteurs eux-mêmes, combien n'avons-nous pas
souffert de voir le génie éclatant et sombre de l'auteur de
l'Indifférence se débattre dans un genre de travail si antipathique à
sa nature! Le parti qu'il a pris d'être simple en traduisant cette
simplicité l'a fait verser dans ce que nous appelons l'inconvénient de
l'Imitation, c'est-à-dire la métaphysique.
Pourvu que nous ne tombions pas dans le système rasé de bien près
par les éditeurs, à la page 14 de leur Introduction, dans cette
immense bourde allemande, qui a décapité Homère et qui répugne à
la constitution même de l'esprit humain, que nous importe de savoir
si l'auteur de l'Imitation s'appelait A. Kempis ou de toute autre
réunion de syllabes! C'est une question de bal masqué. Ce qu'il y a
de certain, c'est que ce fut un moine, comme Homère fut un poète,
un moine dont l'individualité n'eut probablement de nom que devant
Dieu, et ce qu'il y a de certain encore c'est que ce ne fut point
Gerson, malgré la croyance des éditeurs, mêlée pourtant d'un
invincible doute. Gerson, à notre estime, ne fut ni l'auteur de
l'Imitatio Christi ni celui de l'Internelle Consolacion. Les germanismes
du texte latin le prouvent suffisamment pour l'Imitation, et, pour
l'Internelle Consolacion, le génie de Gerson lui-même, qui n'eut
jamais le moelleux et le laisser-aller du livre délicieux remis en
lumière aujourd'hui.
FIN
TABLE
Dédicace v
Préface vii
Saint Thomas d'Aquin 1
Jean Reynaud 12
Donoso Cortès 29
Saisset 45
Saint-René Taillandier 59
Jules Simon 73
Vera 86
Du mysticisme et de Saint Martin 99
L'abbé Mitraud 117
Ernest Renan 133
Gorini 161
Doublet et Taine 175
Pascal 189
Auguste Martin 203
Buffon 217
Saint-Bonnet et le Père Daniel 233
Le P. Lacordaire 249
Montalembert 265
Philosophie positive 279
Philosophie politique 297
P. Enfantin 311
Le P. Ventura 323
Le docteur Tessier 337
Flourens 351
Eugène Pelletan 365
Saint Anselme de Cantorbéry 381
L'Internelle Consolacion 397
NOTES
[7] Vaton.
[9] Charpentier.
[11] Lévy.
[16] Ladrange.
[17] A. Franck.
[30] Ibid.
[34] Bestel.
[36] On verra plus loin les titres à cette grande chose qu'a
Flourens par ses travaux personnels.
[38] Ibid.
[40] L. Hervé.
[47] Delahays.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com