Mastering Spring Application Development - Sample Chapter
Mastering Spring Application Development - Sample Chapter
$ 44.99 US
29.99 UK
P U B L I S H I N G
Anjana Mankale
Mastering Spring
Application Development
ee
pl
C o m m u n i t y
E x p e r i e n c e
D i s t i l l e d
Mastering Spring
Application Development
Gain expertise in developing and caching your applications
running on the JVM with Spring
Sa
m
Anjana Mankale
), where
Chapter 7, Spring with Hadoop, shows how Spring integrates with Apache Hadoop
and provides Map and Reduce processes to search and count data. The chapter also
discussed installing a Hadoop instance on Unix machines and configuring Hadoop jobs
in a Spring framework.
Chapter 8, Spring with OSGI, develops a simple OSGI application, and also demonstrates
how a Spring dynamic module supports OSGI development and reduces the creation of
files, thereby making things easier with configuration.
Chapter 9, Bootstrap your Application with Spring Boot, starts with setting up a simple
Spring boot project, along with the process of using a Spring Boot to bootstrap
applications. This chapter also gives information about how a Spring Boot supports a
cloud foundry server and helps to deploy applications on cloud.
Chapter 10, Spring Cache, implements our own caching algorithm and teaches you to
make a generic algorithm. This chapter also discusses the classes and interface that
support a caching mechanism in a Spring Framework.
Chapter 11, Spring with Thymeleaf Integration, integrates the Thymeleaf templating
engine into a Spring MVC application, and also uses a Spring Boot to start Spring with a
Thymeleaf application.
Chapter 12, Spring with Web Service Integration, integrates JAX_WS with Spring Web
Service. It demonstrates how to create spring Web services and an endpoint class,
accessing the web service by accessing the WSDL URL.
MongoDB
Table
Collection
Row
Document
Column
Field
Joins
[1]
In the next section, we shall see how we can get started with MongoDB, beginning
with installing it, using the Spring Framework, and integrating MongoDB. To
get started, we shall show basic Create, Retrieve, Update, and Delete (CRUD)
operations with various use cases.
6. Executing > show dbs will still show that eshopdb hasn't been created yet;
this is because it doesn't contain any collections. Let's add some collections in
the next step, once a collection is added.
7. Execute the following snippet in the Command Prompt. The following
snippets will insert sample documents into the collection:
db.eshopdb.insert({cust_id:1,name:"kishore",address:"jayangar"
})
db.eshopdb.insert({cust_id:2,name:"bapi",address:"HAL
Layout"})
db.eshopdb.insert({cust_id:3,name:"srini",address:"abbigere
street"})
db.eshopdb.insert({cust_id:4,name:"sangamesha",address:
"Kattarigupee layout"})
[2]
Chapter 1
The next time you want to start MongoDB, just click on the batch file.
Mongo Collections
db.customer.find()
db.order.find()
db.product.find()
[3]
2. Create a simple Maven project with a web application archetype. Add the
latest 4.0.2.RELEASE spring dependency.
3. The following is an extract from the pom.xml file. These are the mandatory
dependencies to be added to the pom.xml file.
<!-- Spring dependencies -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.2.RELEASE </version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
[4]
Chapter 1
<version>4.0.2.RELEASE </version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.0.2.RELEASE </version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.0.2.RELEASE </version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.2.RELEASE </version>
<scope>runtime</scope>
</dependency>
Application design
The following table contains the classes used to develop a simple CRUD application.
The request flows from controller to model and back. The Repository classes are
marked with the @Repository annotation and connect to MongoDB using the
mongoTemplate class.
Controller
Model
JSP
Bean
Customer
Controller.java
Customer
Repository.java
customer.jsp
Customer.java
editcutomer.jsp
allcustomers.jsp
Order
Controller.java
Order
Repository.java
order.jsp
Order.java
editorder.jsp
allorders.jsp
Product
Controller.java
Product
Repository.java
product.jsp
editproduct.jsp
allproducts.jsp
[5]
Product.java
Request Method
Model Attributes
/product
GET
productList
/product/save
POST
productList
/product/update
POST
productList
/product/geteditproduct
GET
productAttribute
/product/deleteproduct
GET
productAttribute
/product/getallproducts
GET
productList
Chapter 1
public void init(){
this.productList=respository.getAllObjects();
}
//to get the list of products
@RequestMapping(value="/product", method = RequestMethod.GET)
public String getaddproduct(Model model) {
model.addAttribute("productList", productList);
model.addAttribute("productAttribute", new Product());
return "product";
}
//to save the product
@RequestMapping(value="/product/save", method =
RequestMethod.POST)
public String addproduct(@ModelAttribute Product prod,Model
model) {
if(StringUtils.hasText(prod.getProdid())) {
respository.updateObject(prod);
} else {
respository.saveObject(prod);
}
this.productList=respository.getAllObjects();
model.addAttribute("productList", productList);
return "product";
}
//to update the edited product
@RequestMapping(value="/product/update", method =
RequestMethod.POST)
public String updatecustomer(@ModelAttribute Product prod,Model
model) {
respository.updateObject(prod);
this.productList=respository.getAllObjects();
model.addAttribute("productList", productList);
return "product";
}
//to edit a product based on ID
@RequestMapping(value = "/product/geteditproduct", method =
RequestMethod.GET)
public String geteditproduct(
@RequestParam(value = "prodid", required = true) String prodid,
Model model) {
model.addAttribute("productList", productList);
model.addAttribute("productAttribute",
respository.getObject(prodid));
return "editproduct";
}
[7]
The Product.java file has an @Document annotation and an @ID annotation, which
is identified as a MongoDB collection that maps the Product entity to product
collection in MongoDB.
@Document
public class Product {
/*Bean class product with getter and setters*/
@Id
private String prodid;
private Double price;
private String name;
public Product() {
super();
}
public String getProdid() {
return prodid;
}
public void setProdid(String prod_id) {
this.prodid = prod_id;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
[8]
Chapter 1
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
[9]
Chapter 1
The .jsp file displays the products available and allows the user to perform CRUD
operations on the Product bean. The following screenshot is the output of editing
product information using the product ObjectId stored in MongoDB.
Product.jsp file
This file serves as a view layer to the user. This has the product creation form and
includes a file that lists all the products stored in MongoDB.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form"
prefix="form" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="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=UTF8">
<title>Register Product</title>
</head>
<body>
<h1>Register Product</h1>
<ul>
[ 11 ]
If all goes well, you should see the following screen, where you can play around with
products. The following screenshot is the output of the Register Product and list
Product functionality using Spring and MongoDB.
[ 12 ]
Chapter 1
You can see that the mongoDbFactory bean has been configured with MongoDB
database details. You will also observe that mongoTemplate has also been configured.
The property of the mongoTemplate bean is mongoDbFactory bean, and so when the
template is called the connection gets established.
Just run the following commands in the MongoDB database in order to test the
Order use case:
db.order.find()
db.order.remove()
RoboMongo is a free tool like Toad to access the MongoDB
database.
[ 14 ]
Chapter 1
public Order() {
super();
// TODO Auto-generated constructor stub
}
@Id
public String getOrder_id() {
return order_id;
}
public void setOrder_id(String order_id) {
this.order_id = order_id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getOrder_status() {
return order_status;
}
public void setOrder_status(String order_status) {
this.order_status = order_status;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
}
[ 15 ]
The next step would be to define the methods in the OrderRepository.java file.
Below are the code snippets of the update and save methods in the repository class.
The saveObject method only accepts the Order object and sets the ID to the Order
object before saving it.
[ 16 ]
Chapter 1
We have seen how to perform an update and an insert. The following method is
invoked to save the Order details. This shows that mongoTemplate has the methods
insert() and save().
public void saveObject(Order Order) {
Order.setOrder_id(UUID.randomUUID().toString());
mongoTemplate.insert(Order);
}
[ 18 ]
Chapter 1
@RequestMapping(value = "/orde`r/update", method =
RequestMethod.POST)
public String updatecustomer(@ModelAttribute("Order") Order
order,
Map<String, Object> model) {
order.setCustomer(customerRespository.getObject
(order.getCustomer().getCust_id()));
order.setProduct(product_respository.getObject
(order.getProduct().getProdid()));
respository.updateObject(order);
model.put("customerList", customerList);
model.put("productList", productList);
return "order";
}
@RequestMapping(value = "/order/geteditorder", method =
RequestMethod.GET)
public String editOrder(
@RequestParam(value = "order_id", required = true)
String order_id, @ModelAttribute("Order") Order order,
Map<String, Object> model) {
model.put("customerList", customerList);
model.put("productList", productList);
model.put("Order",respository.getObject(order_id));
return "editorder";
}
@RequestMapping(value = "/order/deleteorder", method =
RequestMethod.GET)
public String deleteorder(
@RequestParam(value = "order_id", required = true)
String order_id, @ModelAttribute("Order") Order order,
Map<String, Object> model) {
respository.deleteObject(order_id);
model.put("customerList", customerList);
model.put("productList", productList);
return "order";
}
}
JSP files
The Order.jsp file demonstrates the use of @ModelAttribute, which gets mapped
to the Model Order defined in the controller class. The setter methods set the values
to the objects, which minimizes the coding. This showcases a feature in spring, which
simplifies the coding process.
[ 19 ]
Orders.jsp
<h1>Orders </h1>
<ul>
<li><a href="/Spring4MongoDB_Chapter1/customer">Customer</a>
</li>
<li>r<a href="/Spring4MongoDB_Chapter1/product">Product</a>
</li></ul>
<form:form action="/Spring4MongoDB_Chapter1/order/save"
modelAttribute="Order">
<table>
<tr>
<td>Add your Order:</td>
<td><form:input path="quantity" size="3"/></td>
</tr>
<tr>
<td>Select Product:</td>
<td>
<form:select path="product.prodid">
<form:option value="" label="--Please Select"/>
<form:options items="${productList}" itemValue="prodid"
itemLabel="name"/>
</form:select>
</td>
</tr>
<tr>
<td>Select Customer:</td>
<td>
<form:select path="customer.cust_id">
<form:option value="" label="--Please Select"/>
<form:options items="${customerList}" itemValue="cust_id"
itemLabel="name"/>
</form:select>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form:form>
<%@ include file="allorders.jsp" %>
</body>
</html>
[ 20 ]
Chapter 1
The allorders.jsp file displays the list of orders with an option to edit. Use of
MongoDB has made displaying the orderList simpler.
Allorders.jsp
<h1> E-shop Orders</h1>
<table style="border: 1px solid; width: 500px; text-align:center">
<thead style="background:#fffcc">
<tr>
<th>Order Id</th>
<th>Customer Name</th>
<th>Customer Address</th>
<th>Product Address</th>
<th>Product Price</th>
<th>Product Quantity</th>
<th colspan="2"></th>
</tr>
</thead>
<tbody>
<c:forEach items="${orderList}" var="order">
<c:url var="editUrl"
value="/order/geteditorder?order_id=${order.order_id}" />
<c:url var="deleteUrl"
value="/order/deleteorder?order_id=${order.order_id}" />
<c:url var="addUrl" value="/order/" />
<tr>
<td><c:out value="${order.order_id}" /></td>
<td><c:out value="${order.customer.name}" /></td>
<td><c:out value="${order.customer.address}" /></td>
<td><c:out value="${order.product.name}" /></td>
<td><c:out value="${order.product.price}" /></td>
<td><c:out value="${order.quantity}" /></td>
<td><a href="${editUrl}">Edit</a></td>
<td><a href="${deleteUrl}">Delete</a></td>
<td><a href="${addUrl}">Add</a></td>
</tr>
</c:forEach>
</tbody>
[ 21 ]
[ 22 ]
Chapter 1
[ 23 ]
Summary
In this chapter, we learned how to install MongoDB and create a database and
collections. In MongoDB, we have used the latest version of spring that was available
during the writing of this chapter. We also learned how to integrate Spring MVC
with MongoDB. We have built a CRUD operation. We have also seen the usage of
annotations such as @Repository, @Document, and @Controller. In the next chapter,
let us see how we can integrate spring message brokers using jms templates.
[ 24 ]
www.PacktPub.com
Stay Connected: