SpringMVC example with Maven

Spring MVC is part of Springframework. It allow us to create application based on MVC design pattern in way that, we can leverage other features of Spring like authentication, ORM, AOP and others.

In Spring MVC core component is the DispatcherServlet{link}, It works as front-controller. All request are processed by DispatcherServlet. It is also responbile for deleting request to suitable handlers.

Structure

We are using standard Maven web project structure
spring-mvc-example-project-structure

Dependencies

        <!-- for compile only, your container will provide this  -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <!-- Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.0.0.RELEASE</version>
        </dependency>
        <!-- JSTL -->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

Request Controller

You can use or extend any of controller that comes from Spring or create you own by extendng AbstractController and implement handleRequestInternal method.

package com.techartifact.example.springmvc.controller;


import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloController extends AbstractController {

    private String message;

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView modelAndView = new ModelAndView("hello");
        modelAndView.addObject("message", message);
        return modelAndView;
    }
}

Flow in a Spring MVC application is as follows:

The request is received by our DispatcherServlet

  1. DispatcherServlet has responsibility to find the controller for request. This process would be done in HandlerMapping phase.
  2. After controller has been found, DispatcherServlet will forward the request to Controller.
  3. Controller has the business logic to compute what model it will return to Dispatcher. It means Controller will return Model and view where it needs to displayed
  4. Once the ModelAndView has been dispatched to the DispatcherServlet from controller, DispatcherServlet will asociate the view name sent by the Controller with the specified view.
  5. After the view had been resolved, our DispatcherServlet will pass our Model object to the concrete View.

View

In this example we are using jsp for view

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>SpringMVC Hello world</title>
</head>
<body>
Message from Spring "${message}"
</html>

Spring Configuration

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

    <bean name="/hello.htm" class="com.techartifact.example.springmvc.controller.HelloController">
        <property name="message" value="This is sample message"/>
    </bean>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
</beans>

 Web descriptor

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">

    <display-name>Spring MVC example</display-name>

    <servlet>
        <servlet-name>springapp</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springapp</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

Run example

Download full example code from here spring-webmvc-example

Go to project directory [spring-webmvc-example] in command shell and run following command using maven

mvn clean package
mvn -Pcargo-run

You should see following output in your browser

http://localhost:8080/springmvc/hello.htm

List and ArrayList Example:

List and ArrayList Example: Hi friends this is my first post on core java. I think you know the basics of Collections. I am not explaining basics here. When i am learning java I saw so &nbsp;many sites are giving examples only on Collections to add integer or string or float.&nbsp;Little bit&nbsp;sites only giving example on adding objects and&nbsp;retrieving&nbsp; then from Collections. this is my first example using java.util.List and java.util.Arraylist. i am not explaining anything about this example.I think you can understand by seeing this example.

 

 

the usage of this example is understanding List and ArrayList and contains method. we are adding employee to a list and avoiding duplicates while adding to list by overriding equals method. and&nbsp;retrieving&nbsp;all employees and displaying them from List. have any questions contact me or post a comment below.

Employee.java;

package com.jagadeesh.domain;

public interface Employee {

public Integer getId();

public void setId(Integer id);

public String getFirstName();

public void setFirstName(String firstName);

public String getLastName();

public void setLastName(String lastName);

public void setEmail(String email);

public String getEmail();

public int getPriority();

public void setPriority(int priority);

public String getDesignation();

public void setDesignation(String designation);

public String toDisplayString();

}

EmployeeImpl.java

package com.jagadeesh.domain.impl;

import java.io.Serializable;

import com.jagadeesh.domain.Employee;

import com.jagadeesh.utils.EmployeeIO;

public class EmployeeImpl extends EmployeeIO

implements Employee {

private static final long serialVersionUID = 5058287999709032283L;

private Integer id;

private String firstName;

private String lastName;

private String email;

private int priority;

private String designation;

@Override

public Integer getId() {

return id;

}

@Override

public void setId(Integer id) {

this.id = id;

}

@Override

public String getFirstName() {

return firstName;

}

@Override

public void setFirstName(String firstName) {

this.firstName = firstName;

}

@Override

public String getLastName() {

return lastName;

}

@Override

public void setLastName(String lastName) {

this.lastName = lastName;

}

@Override

public String getEmail() {

return email;

}

@Override

public void setEmail(String email) {

this.email = email;

}

@Override

public int getPriority() {

return priority;

}

@Override

public void setPriority(int priority) {

this.priority = priority;

}

@Override

public String getDesignation() {

return designation;

}

@Override

public void setDesignation(String designation) {

if ("CEO".equalsIgnoreCase(designation)) {

setPriority(1);

} else if ("MD".equalsIgnoreCase(designation)) {

setPriority(2);

} else if ("HR".equalsIgnoreCase(designation)) {

setPriority(3);

} else {

setPriority(4);

}

this.designation = designation;

}

@Override

public String toString() {

StringBuffer buffer = new StringBuffer();

buffer.append("EmployeeImpl [id=");

buffer.append(id);

buffer.append(", firstName=");

buffer.append(firstName);

buffer.append(", lastName=");

buffer.append(lastName);

buffer.append(", email=");

buffer.append(email);

buffer.append(", priority=");

buffer.append(priority);

buffer.append(", designation=");

buffer.append(designation);

buffer.append("]");

return buffer.toString();

}

@Override

public boolean equals(Object object) {

if (object == null)

return false;

if (object == this)

return true;

if (this.getClass() != object.getClass())

return false;

Employee employee = (Employee) object;

if (this.id == employee.getId()

this.firstName.equalsIgnoreCase(employee.getFirstName())

this.lastName.equalsIgnoreCase(employee.getLastName())

this.email.equalsIgnoreCase(employee.getEmail())

this.designation.equalsIgnoreCase(employee.getDesignation()))

return true;

return false;

}

@Override

public String toDisplayString() {

StringBuffer buffer = new StringBuffer();

buffer.append(this.getId());

buffer.append("\t");

buffer.append(this.getFirstName());

buffer.append("\t");

buffer.append(this.getLastName());

buffer.append("\t");

buffer.append(this.getEmail());

buffer.append("\t");

buffer.append(this.getDesignation());

return buffer.toString();

}

}

&lt;/pre&gt;

&lt;b&gt;EmployeeService.java&lt;/b&gt;

&lt;pre class="brush:java"&gt;package com.jagadeesh.service;

import java.util.List;

import com.jagadeesh.domain.Employee;

public interface EmployeeService {

List&amp;lt;Employee&amp;gt; getAll();

void addEmployee(Employee employee);

}

&lt;/pre&gt;

&lt;b&gt;EmployeeServiceImpl.java&lt;/b&gt;

&lt;pre class="brush:java"&gt;package com.jagadeesh.service.impl;

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

import com.jagadeesh.domain.Employee;

import com.jagadeesh.service.EmployeeService;

public class EmployeeServiceImpl implements EmployeeService {

private List&amp;lt;Employee&amp;gt; employees = new ArrayList&amp;lt;Employee&amp;gt;();

@Override

public List&amp;lt;Employee&amp;gt; getAll() {

List&amp;lt;Employee&amp;gt; employees = new ArrayList&amp;lt;Employee&amp;gt;(this.employees);

return Collections.unmodifiableList(employees);

}

@Override

public void addEmployee(Employee employee) {

if (employees.contains(employee)) {

System.out.println("Employee already exists");

} else {

this.employees.add(employee);

}

}

}

EmployeeIO.java

package com.jagadeesh.utils;

import java.util.List;

import com.jagadeesh.domain.Employee;

import com.jagadeesh.domain.impl.EmployeeImpl;

public class EmployeeIO {

public static Employee read() {

Employee employee = new EmployeeImpl();

employee.setId(KeyBoard.readInt("Enter Id :"));

employee.setFirstName(KeyBoard.read("Enter First Name :"));

employee.setLastName(KeyBoard.read("Enter Last Name :"));

employee.setEmail(KeyBoard.read("Enter Email :"));

employee.setDesignation(KeyBoard.read("Enter Designation :"));

return employee;

}

public static void out(List&amp;lt;Employee&amp;gt; employees) {

StringBuilder builder = new StringBuilder();

builder.append("Id\t\tFirst Name\t\tLast Name\t\tEmail\ttDesignation\n");

for (int i = 0; i &amp;lt; employees.size(); i++) {

builder.append(employees.get(i).toDisplayString());

builder.append("\n");

}

System.out.println(builder);

}

}

KeyBoard.java

package com.jagadeesh.utils;

import java.util.Scanner;

public class KeyBoard {

public static int readInt(String message) {

System.out.print(message);

Scanner scanner = new Scanner(System.in);

try {

int number = Integer.parseInt(scanner.next());

return number;

}

catch(NumberFormatException e) {

System.out.println("Invalid Number");

return readInt(message);

}

}

public static String read(String message) {

System.out.print(message);

Scanner scanner = new Scanner(System.in);

return scanner.nextLine();

}

}

EmployeeMain.java

package com.jagadeesh.main;

import com.jagadeesh.domain.Employee;

import com.jagadeesh.service.EmployeeService;

import com.jagadeesh.service.impl.EmployeeServiceImpl;

import com.jagadeesh.utils.EmployeeIO;

import com.jagadeesh.utils.KeyBoard;

public class EmployeeMain {

public static void main(String[] args) throws Exception {

int option = 1;

EmployeeService empService = new EmployeeServiceImpl();

do {

Employee employee = EmployeeIO.read();

empService.addEmployee(employee);

option = KeyBoard.readInt(

"Do you want add another employee(1/0) :");

} while(option == 1);

System.out.println("Reading from List");

EmployeeIO.out(empService.getAll());

}

}

Out put of the program

Enter Id :1

Enter First Name :jagadeesh

Enter Last Name :kumar

Enter Email :[email protected]

Enter Designation :developer

Do you want add another employee(1/0) :1

Enter Id :2

Enter First Name :jagadeesh

Enter Last Name :kumar

Enter Email :[email protected]

Enter Designation :developer

Do you want add another employee(1/0) :1

Enter Id :1

Enter First Name :jagadeesh

Enter Last Name :kumar

Enter Email :[email protected]

Enter Designation :developer

Employee already exists

Do you want add another employee(1/0) :testing invalid option

Invalid Number

Do you want add another employee(1/0) :1

Enter Id :3

Enter First Name :jagadeesh

Enter Last Name :kumar

Enter Email :[email protected]

Enter Designation :developer

Do you want add another employee(1/0) :0

Reading from List

Id First Name Last Name Email  Designation

1 jagadeesh kumar [email protected] developer
2 jagadeesh kumar [email protected] developer
3 jagadeesh kumar [email protected] developer

Pin it