Spring Essentials - Sample Chapter
Spring Essentials - Sample Chapter
$ 44.99 US
28.99 UK
P U B L I S H I N G
E x p e r i e n c e
D i s t i l l e d
Spring Essentials
Build mission-critical enterprise applications using Spring
Framework and Aspect Oriented Programming
Sa
m
pl
C o m m u n i t y
Shameer Kunjumohamed
Hamidreza Sattari
Spring Essentials
Spring Essentials
ee
Shameer Kunjumohamed
Hamidreza Sattari
Shameer has co-authored another book, Spring Web Services 2 Cookbook, Packt
Publishing with Hamidreza Sattari, who is the co-author of this book as well.
Based in Dubai, UAE, Shameer has over 15 years of experience in various functional
domains. He currently works as a principal applications architect for a major
shipping company in Dubai.
Preface
There are a lot of books written about Spring Framework and its subprojects.
A multitude of online references are also available. Most of these massive
resources discuss Spring in a lot of detail, which makes learning Spring a very
time-consuming and sometimes tedious effort. The idea of this book is to allow
novice Java developers or architects to master Spring without spending much time
and effort and at the same time provide them with a strong foundation on the topic
in order to enable them to design high-performance systems that are scalable and
easily maintainable.
We have been using Spring Framework and its subprojects for more than a
decade to develop enterprise applications in various domains. While the usage of
Spring quickly raises the design quality of projects with its smart templates and
subframeworks abstracting many error-prone and routine programming tasks, a
developer needs a thorough understanding of its concepts, features, best practices,
and above all, the Spring programming model in order to utilize Spring to its best.
We have seen Spring used wrongly inside many projects mainly because the
developer either didn't understand the right use of a particular Spring component
or didn't bother to follow the design approach Spring suggests for that component.
Often, developers didn't appear to have the right knowledge of Spring Framework;
when asked, their complaint mostly was the uphill task of learning such a vast
framework from huge documentation. Most of this category of developers find
Spring a mammoth framework that is difficult to learn, which is not really true.
Spring, if the basics are understood correctly, is very easy to conquer further.
A developer needs to understand the Spring style of programming and architecting
applications, and the result will be a piece of art. The design will look simple,
pretty straightforward, and easily understandable, which is very important for the
evolution of applications in the long run. This book is an attempt to fill that gap
and provide a very solid foundation in Spring, its concepts, design styles, and best
practices, in a very quick and easy way.
Preface
This book tries to engage the reader by providing the feeling of developing a
realistic, modern enterprise application using Spring and its necessary features
while giving him or her a solid understanding of its concepts, benefits, and usage
with real-life examples. It covers the most important concepts and features of Spring
Framework and a few of its critical subprojects that are necessary for building
modern web applications.
The goal of Spring is to simplify enterprise application development. We hope this
book simplifies mastering Spring so that developers can build smarter systems that
make the world a better place.
Preface
Chapter 5, Securing Your Applications, teaches the reader how to secure his or her
Spring applications. It starts with authentication and explains Spring flexibility on
authorization. You learn how to integrate your existing authentication framework
with Spring. On authorization, it shows how to use Spring EL expressions for
web, method, and domain object authorization. It also explains the OAuth 2.0
Authorization Framework and how to allow third-party limited access to user's
protected resources on a server without sharing user's username and password.
Chapter 6, Building a Single-Page Spring Application, demonstrates how Spring can be
used as the API server for modern single-page applications (SPAs) with an example
of an Ember JS application. At first, it introduces the concept of SPAs, and then it
explores using Ember JS to build the SPA. Finally, it covers building the backend
API that processes requests asynchronously using Spring MVC and implements
persistence using Spring Data JPA.
Chapter 7, Integrating with Other Web Frameworks, demonstrates how Spring can
be integrated with Java web frameworks such as JSF and Struts so that even web
applications not based on Spring MVC can leverage the power of Spring.
Understanding WebSocket
The idea of web applications was built upon a simple paradigm. In a unidirectional
interaction, a web client sent a request to a server, the server replied to the request,
and the client rendered the server's response. The communication started with a
client-side request and ended with the server's response.
We built our web applications based on this paradigm; however, some drawbacks
existed in the technology: the client had to wait for the server's response and refresh
the browser to render it. This unidirectional nature of the communication required
the client to initiate a request. Later technologies such as AJAX and long polling
brought major advantages to our web applications. In AJAX, the client initiated a
request but did not wait for the server's response. In an asynchronous manner, the
AJAX client-side callback method got the data from the server and the browsers'
new DHTML features rendered the data without refreshing the browser.
Apart from unidirectional behavior, the HTTP dependencies of these technologies
required the exchange of extra data in the form of HTTPS headers and cookies.
This extra data caused latency and became a bottleneck for highly responsive
web applications.
WebSocket reduced kilobytes of transmitted data to a few bytes and reduced
latency from 150 milliseconds to 50 milliseconds (for a message packet plus the TCP
round trip to establish the connection), and these two factors attracted the Google's
attention (Ian Hickson).
[ 131 ]
Understanding WebSocket
WebSocket (RFC 6455) is a full duplex and bidirectional protocol that transmits
data in the form of frames between client and server. A WebSocket communication,
as shown in the following figure, starts with an HTTP connection for a handshake
process between a client and a server. Since firewalls let certain ports be open to
communicate with the outside, we cannot start with the WebSocket protocol:
Client browser
Server
OpenFlow
Controller
WebSocket communication
During the handshake process, the parties (client and server) decide which
socket-based protocol to choose for transmitting data. At this stage, the server can
validate the user using HTTP cookies and reject the connection if authentication or
authorization fails.
Then, both parties upgrade from HTTP to a socket-based protocol. From this point
onward, the server and client communicate on a full duplex and bidirectional
channel on a TCP connection.
Either the client or server can send messages by streaming them into frame format.
WebSocket uses the heartbeat mechanism using ping/pong message frames to keep
the connection alive. This looks like sending a ping message from one party and
expecting a pong from the other side. Either party can also close the channel and
terminate the communication, as shown in the preceding diagram.
[ 132 ]
Chapter 4
Like a web URI relies on HTTP or HTTPS, WebSocket URI uses ws or wss schemes
(for example, ws://www.sample.org/ or wss://www.sample.org/) to communicate.
WebSocket's ws works in a similar way to HTTP by transmitting non-encrypted data
over TCP/IP. By contrast, wss relies on Transport Layer Security (TLS) over TCP,
and this combination brings data security and integrity.
A good question is where to use WebSocket. The best answer is to use it where low
latency and high frequency of communication are criticalfor example, if your
endpoint data changes within 100 milliseconds and you expect to take very quick
measures over the data changes.
Spring Framework 4 includes a new Spring WebSocket module with Java
WebSocket API standard (JSR-356) compatibility as well as some additional
value-adding features.
While using WebSocket brings advantages to a web application, a lack of
compatibility in a version of some browser blocks WebSocket communication. To
address this issue, Spring 4 includes a fallback option that simulates the WebSocket
API in case of browser incompatibility.
WebSocket transmits data in the frame format, and apart from a single bit to
distinguish between text and binary data, it is neutral to the message's content. In
order to handle the message's format, the message needs some extra metadata, and
the client and server should agree on an application-layer protocol, known as a
subprotocol. The parties choose the subprotocol during the initial handshake.
WebSocket does not mandate the usage of subprotocols, but in the case of their
absence, both the client and server need to transmit data in a predefined style
standard, framework-specific, or customized format.
Spring supports Simple Text Orientated Messaging Protocol (STOMP) as a
subprotocolknown as STOMP over WebSocketin a WebSocket communication.
Spring's Messaging is built upon integration concepts such as messaging and
channel and handler, along with annotation of message mapping. Using STOMP
over WebSocket gives message-based features to a Spring WebSocket application.
Using all of these new Spring 4 features, you can create a WebSocket application and
broadcast a message to all subscribed clients as well as send a message to a specific
user. In this chapter, we start by creating a simple Spring web application, which will
show how to set up a WebSocket application and how a client can send and receive
messages to or from an endpoint. In the second application, we will see how Spring
WebSocket's fallback option can tackle browser incompatibly, how a broker based
messaging system works with STOMP over WebSocket, and how subscribed clients
can send and receive messages. In the last web application, however, we will show
how we can send broker-based messages to a specific user.
[ 133 ]
Understanding WebSocket
Chapter 4
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
[ 135 ]
Understanding WebSocket
In order to tell Spring to forward client requests to the endpoint (or handler here),
we need to register the handler:
@Configuration
@EnableWebSocket
public class SampleEhoWebSocketConfigurer {
@Bean
WebSocketConfigurer webSocketConfigurer(final WebSocketHandler
webSocketHandler) {
return new WebSocketConfigurer() {
@Override
public void registerWebSocketHandlers
(WebSocketHandlerRegistry registry) {
registry.addHandler(new
SampleTextWebSocketHandler(), "/path/wsAddress");
}
};
}
@Bean
WebSocketHandler myWebsocketHandler() {
return new SampleTextWebSocketHandler();
}
And now the question is how to set up a Spring application and glue all of this stuff
together. Spring Boot provides an easy way to set up a Spring-based application with
a configurable embedded web server that you can "just run":
package com.springessentialsbook.chapter4;
...
@SpringBootApplication
public class EchoWebSocketBootApplication {
public static void main(String[] args) {
SpringApplication.run(EchoWebSocketBootApplication
.class, args);
}
}
[ 136 ]
Chapter 4
application context
[ 137 ]
Understanding WebSocket
This runs and deploys the web application on an embedded server on port 8090
(8080 is not used here as it may conflict with your running Apache service). So, the
index page of the application will be accessible at http://localhost:8090/ (follow
the instructions in read-me.txt to run the application). It should look like this:
Chapter 4
Understanding WebSocket
the message broker (that is, broadcasted to other connected clients). Since
we are using an in-memory broker, we can specify any topic. If we use a
dedicated broker, the destination's name would be /topic or /queue,
based on the subscription model (pub/sub or point-to-point).
Chapter 4
public ReturnedDataModelBean
broadCastClientMessage(ClientInfoBean message) throws
Exception {
String returnedMessage=message.getClientName() +
":"+message.getClientMessage();
return new ReturnedDataModelBean(returnedMessage );
}
}
package com.springessentialsbook.chapter4;
public class ReturnedDataModelBean {
private String returnedMessage;
public ReturnedDataModelBean(String returnedMessage) {
this.returnedMessage = returnedMessage; }
public String getReturnedMessage() {
return returnedMessage;
}
}
[ 141 ]
Understanding WebSocket
To add some sort of security, we can add basic HTTP authentication, as follows (we
are not going to explain Spring security in this chapter, but it will be detailed in the
next chapter):
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic();
http.authorizeRequests().anyRequest().authenticated();
}
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws
Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
To add Spring Security features, we should add the following Maven dependencies:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-messaging</artifactId>
<version>4.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
[ 142 ]
Chapter 4
This runs and deploys the web application on an embedded web server on port 8090
(8080 is not used as it may conflict with your running Apache service). So, the index
page of the application will be accessible at http://localhost:8090/ (follow
read-me.txt to run the application):
<script src="sockjs-0.3.4.js"></script>
<script src="stomp.js"></script>
<script type="text/javascript">
...
function joinChatroom() {
var topic='/chatroomTopic/broadcastClientsMessages';
var servicePath='/broadcastMyMessage';
var socket = new SockJS(servicePath);
stompClient = Stomp.over(socket);
stompClient.connect('user','password', function(frame) {
setIsJoined(true);
console.log('Joined Chatroom: ' + frame);
stompClient.subscribe(topic, function(serverReturnedData){
renderServerReturnedData(JSON.parse
(serverReturnedData.body).returnedMessage);
});
});
}
...
function sendMyClientMessage() {
var serviceFullPath='/myApp/broadcastMyMessage';
var myText = document.getElementById('myText').value;
[ 143 ]
Understanding WebSocket
stompClient.send(serviceFullPath, {}, JSON.stringify({
'clientName': 'Client-'+randomnumber,
'clientMessage':myText}));
document.getElementById('myText').value='';
}
On the client side, notice how the browser connects (with joinChatRoom) and sends
data (in the sendMyClientMessage method). These methods use the JavaScript
libraries SockJS and Stomp.js.
As you can see, when a client subscribes to a topic, it registers a listener method
(stompClient.subscribe(topic, function(serverReturnedData){.}).
The listener method will be called when any message (from any client) arrives
in the topic.
As discussed earlier, some versions of browsers do not support WebSocket. SockJS
was introduced to handle all versions of browsers. On the client side, when you try
to connect to the server, the SockJS client sends the GET/info message to get some
information from the server. Then it chooses the transport protocol, which could
be one of WebSocket, HTTP streaming, or HTTP long-polling. WebSocket is the
preferred transport protocol; however, in case of browser incompatibility,
it chooses HTTP streaming, and in the worse case, HTTP long-polling.
In the beginning of this section, we described how our WebSocket application
integrates with the Spring messaging system and works in a way similar to legacy
messaging systems.
The overridden method settings of @EnableWebSocketMessageBroker and
ChatroomWebSocketMessageBrokerConfigurer create a concrete message flow
The client inbound channel (Request channel) for request messages sent
from the client side
The client outbound channel (Response channel) for messages sent to the
client side
Our system uses STOMP destinations for simple routing by prefix. Any client
message whose destination starts with /myApp will be routed to controller
message-handling methods. Any message whose destination starts with
/chatroomTopic will be routed to the message broker.
[ 144 ]
Chapter 4
Annotated controller
/myApp
Send destination:
/myApp/broadcastMyMessage
Request channel
Broker channel
/chatroomTopic
Simple broker
Message destination:
/chatroomTopic/broadcastClientsMessages
Response channel
[ 145 ]
Understanding WebSocket
[ 146 ]
Chapter 4
}
@Service
public class AutoAnsweringServiceImpl implements AutoAnsweringService
{
@Override
public String answer(ClientInfoBean bean) {
StringBuilder mockBuffer=new StringBuilder();
mockBuffer.append(bean.getClientName())
.append(", we have received the message:")
.append(bean.getClientMessage());
return mockBuffer.toString();
}
}
[ 147 ]
Understanding WebSocket
var myText = document.getElementById('myText').value;
stompClient.send(serviceFullPath, {}, JSON.stringify({
'clientName': 'Client-'+randomnumber,
'clientMessage':myText}));
document.getElementById('myText').value='';
}
Summary
In this chapter, we explained WebSocket-based communication, how Spring 4 has
been upgraded to support WebSocket, and the fallback option to overcome browsers'
WebSocket incompatibility. We also had a small sample of adding basic HTTP
authentication, which is a part of Spring Security. We will discuss more on security
in Chapter 5, Securing Your Applications.
[ 148 ]
www.PacktPub.com
Stay Connected: