A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

Shopping Cart Web-Flow in Spring MVC

Spring Web Flow uses to build on Spring MVC Web Application. It allows us to create real implementation of  "FLOWS" of web application.

A flow means , It encapsulates multiple steps that instructs users while using web application. These applications are business applications. such as Amazon.in , paytm.com, and flipcart etc...

Since, these types of applications spans multiple HTTP requests at time, which has different states, has a consistent data flow on each states( May be dynamic or long running in Nature).

Use the following spring webflow maven dependency in your project POM.xml


<!-- https://mvnrepository.com/artifact/org.springframework.webflow/spring-webflow -->
<dependency>
    <groupId>org.springframework.webflow</groupId>
    <artifactId>spring-webflow</artifactId>
    <version>2.4.4.RELEASE</version>
</dependency>


Now, use the following steps to create project in maven:

step 1. you need to create base folder or package that contains folder like as below:

shoppingcart:
      |________    bean
      |
      |________   controller
      |
      |________   handler



step 2. Create a class in bean folder as below:


package com.programmingshifts.shoppingcart.bean;

import java.io.Serializable;

public class UserDetails implements Serializable
{

    private String id;
    private String name;
    private String password;

    private String email;

    private String address;

    private String mobile;

    public String getPassword() {
        return password;
    }
  
    //create setter and getter

 }



step 3.  create controller class that will contain a requestMapping for front-controller url like "\home" , which will used in hyperlink.



package com.programmingshifts.shoppingcart.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RegistrationController {

    @RequestMapping("home")
    public String home(){
        return "index";
    }
}



step 4. create a handler class in handler folder.



package com.programmingshifts.shoppingcart.handler;

import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.stereotype.Component;

import com.programmingshifts.shoppingcart.bean.UserDetails;

@Component
public class RegistrationHandler
{

    public UserDetails initFlow()
    {
        return new UserDetails();
    }

    public String validateDetails(UserDetails userDetails, MessageContext messageContext)
    {
        String status = "success";
        if(userDetails.getId().isEmpty())
        {
            messageContext.addMessage(new MessageBuilder().error().source(
                    "id").defaultText("UserId cannot be Empty").build());
            status = "failure";
        }
        if(userDetails.getName().isEmpty())
        {
            messageContext.addMessage(new MessageBuilder().error().source(
                    "name").defaultText("Name cannot be Empty").build());
            status = "failure";
        }
        if(userDetails.getPassword().isEmpty())
        {
            messageContext.addMessage(new MessageBuilder().error().source(
                    "password").defaultText("Password cannot be Empty").build());
            status = "failure";
        }
   
        if(userDetails.getEmail().isEmpty())
        {
            messageContext.addMessage(new MessageBuilder().error().source(
                    "email").defaultText("Email cannot be Empty").build());
            status = "failure";
        }
        if(userDetails.getMobile().isEmpty())
        {
            messageContext.addMessage(new MessageBuilder().error().source(
                    "mobile").defaultText("Mobile cannot be Empty").build());
            status = "failure";
        }
        if(userDetails.getAddress().isEmpty())
        {
            messageContext.addMessage(new MessageBuilder().error().source(
                    "address").defaultText("Address cannot be Empty").build());
            status = "failure";
        }
       
        return status;
    }
}


step 5. create the following jsp file for graphical users:


index.jsp page:


<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Shopping Cart</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="content">
<h1> <center>  Shopping Cart  </center></h1>
<hr color="blue" height="5">

<a href="memberShip.obj" style="margin: 50;">Register here</a>
</div>
</body>
</html>


MemberDetails.jsp:

<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Shopping Cart</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
<div class="content">
<fieldset>
<legend>Regiser Here</legend>
<a href="${flowExecutionUrl}&_eventId_home">Home</a>
<form:form modelAttribute="userDetails">
<br />
<form:label path="id">User ID:</form:label>
<form:input path="id" />
<br />
<!-- to display validation messages -->
<c:forEach
items="${flowRequestContext.messageContext.getMessagesBySource('id')}"
var="err">
<div>
<span>${err.text}</span>
</div>
</c:forEach>

<form:label path="name">User Name:</form:label>
<form:input path="name" />
<br />
<!-- to display validation messages -->
<c:forEach
items="${flowRequestContext.messageContext.getMessagesBySource('name')}"
var="err">
<div>
<span>${err.text}</span>
</div>
</c:forEach>

<form:label path="password">Password:</form:label>
<form:input type="password" path="password" />
<br />
<!-- to display validation messages -->
<c:forEach
items="${flowRequestContext.messageContext.getMessagesBySource('password')}"
var="err">
<div>
<span>${err.text}</span>
</div>
</c:forEach>

<form:label path="email">Email ID:</form:label>
<form:input path="email" />
<br />
<!-- to display validation messages -->
<c:forEach
items="${flowRequestContext.messageContext.getMessagesBySource('email')}"
var="err">
<div>
<span>${err.text}</span>
</div>
</c:forEach>

<form:label path="mobile">Mobile #:</form:label>
<form:input path="mobile" />
<br />
<!-- to display validation messages -->
<c:forEach
items="${flowRequestContext.messageContext.getMessagesBySource('mobile')}"
var="err">
<div>
<span>${err.text}</span>
</div>
</c:forEach>


<br />
<form:label path="address">Address: </form:label>
<form:input path="address" />
<br />
<c:forEach
items="${flowRequestContext.messageContext.getMessagesBySource('address')}"
var="err">
<div>
<span>${err.text}</span>
</div>
</c:forEach>
<br />
<input name="_eventId_submit" type="submit" value="Submit" />
<br />
</form:form>
</fieldset>
</div>
</body>
</html>



confirmDetails.jsp:


<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Spring Mvc WebFlow Demo</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
<div class="content">
<fieldset>
<legend>Confirm Details</legend>
<!-- for triggering webflow events using links,
the eventId to be triggered is given in "href" attribute as:
-->
<a href="${flowExecutionUrl}&_eventId_home">Home</a><br /> <br />
<sf:form modelAttribute="userDetails">
<sf:label path="id">User ID :</sf:label>${userDetails.id}
<br />
<br />
<sf:label path="name"> User Name:</sf:label>${userDetails.name}
<br />
<br />
<sf:label path="password">Password :</sf:label>${userDetails.password}
<br />


<sf:label path="email">Email:</sf:label>${userDetails.email}
<br />
<br />
<sf:label path="mobile">Mobile #:</sf:label>${userDetails.mobile}
<br />
<br />
<sf:label path="address">Address :</sf:label>${userDetails.address}
<br />
<br />
<input name="_eventId_edit" type="submit" value="Edit" />
<input name="_eventId_submit" type="submit" value="Confirm Details" />
<br />
</sf:form>
</fieldset>
</div>
</body>
</html>



exception.jsp:


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Shopping Cart</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="content" style="width: 60%">
<!-- here the href's value will be used to decide the 
controller to be executed on click of this link.
here "home" is mapped in spring mvc controller-->
<a href="home.obj">Home</a>
<fieldset>
<legend>Error occurred</legend>
${exception }
</fieldset>
</div>
</body>
</html>



welcome.jsp:


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Shopping Cart</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="content">
<fieldset>
<legend>Shopping Cart Home Page</legend>
<!-- here the href's value will be used to decide the 
controller to be executed on click of this link.
here "home" is mapped in spring mvc controller-->
<a href="home.obj">Home</a> <br />
<br />
<h2>
<!-- display the userId just entered -->
Welcome ${userDetails.name }
</h2>
<br />
</fieldset>
</div>
</body>
</html>


Step 6. create three xml file in WEB-INF as below:



web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>ShoppingCartRegistrationWebFlow</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<!-- make sure servlet-name is same as in <servlet> configuration -->
<servlet-name>dispatcher</servlet-name>
<!-- only url's with extension mentioned in url-pattern will be directed 
to spring controller -->
<url-pattern>*.obj</url-pattern>
</servlet-mapping>
</web-app>



dispatcher-servlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:webflow="http://www.springframework.org/schema/webflow-config"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/webflow-config
        http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd">

<!-- declare mvc to be annotation driven -->
<mvc:annotation-driven />
<context:annotation-config />

<!-- provide Your Base package to scan annotations for components -->
<context:component-scan base-package="com.niit" />

<!-- WebFlow Configuration -->
<webflow:flow-executor id="flowExecutor" />

<webflow:flow-registry id="flowRegistry"
flow-builder-services="flowBuilderServices" base-path="/WEB-INF">
<!-- here the id is mapped to invoke this flow -->
<webflow:flow-location id="memberShip" path="/memberShipFlow.xml" />
</webflow:flow-registry>

<webflow:flow-builder-services id="flowBuilderServices"
view-factory-creator="viewFactoryCreator" />

<bean id="viewFactoryCreator"
class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">
<property name="viewResolvers">
<list>
<ref bean="viewResolver" />
</list>
</property>
</bean>

<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>

<bean class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter">
<property name="flowExecutor" ref="flowExecutor" />
</bean>

<bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping">
<property name="flowRegistry" ref="flowRegistry" />
<property name="order" value="0" />
</bean>
</beans>

memberShipFlow.xml:

<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns="http://www.springframework.org/schema/webflow"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/webflow
                          http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">

<!-- Executed when webFlow is triggered -->
<on-start>
<evaluate expression="registrationHandler.initFlow()" result="flowScope.userDetails" />
</on-start>

<view-state id="start" view="memberDetails" model="flowScope.userDetails">
<transition on="submit" to="validate" />
</view-state>

<action-state id="validate">
<evaluate expression="registrationHandler.validateDetails(userDetails,messageContext)"></evaluate>
<transition on="success" to="confirmDetails"/>
<transition on="failure" to="start" />
</action-state>

<view-state id="confirmDetails" view="confirmDetails" model="flowScope.userDetails">
<transition on="edit" to="start" />
<transition on="submit" to="welcome" />
</view-state>

<end-state id="welcome" view="welcome" />

<end-state id="toHome" view="externalRedirect:contextRelative:index.jsp" />

<end-state id="toException" view="externalRedirect:contextRelative:exception.jsp" />

<!-- these events are available in every state -->
<global-transitions>
<transition on="home" to="toHome" />
<transition on="error" to="toException" />
</global-transitions>
</flow>

If you got any problem in Shopping Cart Web-Flow in Spring MVC, you can contact us.
Thank you to see at programmingshifts.com.

LEARN TUTORIALS

.

.