Spring MVC

Working Example : https://github.com/teachkoka/spring-mvc-xml

Spring MVC Supports

.Form backup support(using Spring tags)  – for Presentation, we can hold bean data into bean classes and do validations
.Controllers support(MultiAction Controllers and MultiForm Controllers)
.Validation
.I18n
.Interceptors
.ViewResolver
.Exception Handling
.Modularazition Support

1. Spring MVC – Support upto Presentation to Controller only. 
2. IOC Container for SpringMVC -> WebApplicationContext Container

3.Spring mvc desinged based on jsp-model architecture -> multiple view request with single controller

4.Common validations, form data read operations and populate in to beans, redirect it to corresponding Controller and this is nothing but FrontController(multiple inputs to single controller). 

Front Controllers   – Model
—————-         ————
JSP                        – JSP-Model1 
Servlets                 – JSP-Model2 (Struts 1x, SpringMVC)
Filter                     – JSP-Model3 (Struts 2x)
Tag support           – JSP-Model4

FrontController for SpringMVC is DispactherServlet
FrontController for Struts1.x is ActionServlet
FrontController for Struts2.x is FilterDispatcher (Struts prepare and execute Filter)
FrontController for JSF is FacesServlet

<web-app>
       <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

Spring xml file name should be ${servlet-name}-servlet.xml

Tomcat supports 3 types of url patterns
1) Complete character sequence
2) /*
3) *.extension (any extension *.do, *.bell)


Programatic Approach
1)Controller
2)AbstractController
3)AbstractCommandController
4)SimpleFormController
5)AbstractWizardFormController
6)MultiActionController
Or 
Annotation through @Controller

<context:component-scan base-package="com.springapp.mvc"/>

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


${data}- OGNl->ObjectGraphNotationLanguage
–Controller Classes

1)CoreControllers
  Controller(I) -> handlerRequest
  AbstractController ->handleRequestInternal
2)FormControllers
  ParameterizableViewController  -> one additional method -> setViewName()
  UrlFileNameViewController  -> acts like simple forward requests
3)Command
 BaseCommand
 AbstractFormController
 AbstractWizardFormController
 SimpleFormController
 AbstractCommandController
4)ThrowAway Controller
 ThrowAwayController
5)MultiActionController (Recommended)

–HandlerMapping Classes:
 .BeanNameUrlMapping(Default)  – Mapping URL with corresponding bean
         <bean name="/hello.do" class="HelloController"/>
.SimpleUrlHandlerMapping(Recommended) – 
 <bean class="SimpleUrlHandlerMapping"> 
    <property name="mapping">
    <props><prop key="hello.ds">hc</prop></props>
 </bean>
 <bean id="hc" class="HelloController"/>
 .ControllerClassNameHandlerMapping – by following NamingConventions  hello.do <-> HelloController.java
           <bean class="ControllerURLMapping"/>
           <bean id="hc" class="HelloController"/>
 .CommonPathMapHandlerMapping

–ViewResolver Classes
 TilesViewResolver

 

Spring-MVC-Example-by-Crunchify

 

How to Configure Spring xml file
1)Using {servlet-name}-servlet.xml
2)Using init-param
<init-param>
<param-name>ContextConfigLocation<param-value>
</init-param>
3)Using ContextParams 
<listner>ContextLoaderListner</listner>
<context-param>
  <param-name></param-value>
  <param-value></param-value>
</context-param>


public class YourController implements Controller{
    
    public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse res){
        String name = req.getParameter("name");
        Map m = new HashMap();
        m.put("msg","Hey"+name);
        ModelAndView mav = new ModelAndView("success",m);
        return mav;

    }

}

Validations & ResultBinding

@Valid asks spring to validate the associated object(student). 
BindingResult contains the outcome of this validation and any error that might have occurred during this validation. Notice that BindingResult must come right after the validated object else spring won’t be able to validate and an exception been thrown.

Note that in case of validation failure, default/ generalized error messages are shown on screen which may not be desirable. Instead, you can override this behavior providing internationalized messages specific to each field. To do that, we need to configure MessageSource in application configuration class and provide properties files containing actual messages which we will do next.
https://docs.oracle.com/javaee/6/api/javax/validation/constraints/package-summary.html
https://docs.jboss.org/hibernate/validator/4.1/api/org/hibernate/validator/constraints/package-summary.html

Spring MVC dependencies sample pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.training.jdbctemplate</groupId>
  <artifactId>jdbctemplate-demo</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>jdbctemplate-demo Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
    <hibernate.version>4.2.0.Final</hibernate.version>
    <mysql.connector.version>5.1.21</mysql.connector.version>
    <spring.version>4.2.0.RELEASE</spring.version>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>${hibernate.version}</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>${hibernate.version}</version>
    </dependency>


    <!-- Servlet API and JSTL -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <version>1.1.0.Final</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- DB related dependencies -->
  <!--  <dependency>
      <groupId>org.postgresql</groupId>
      <artifactId>postgresql</artifactId>
      <version>9.3-1100-jdbc4</version>
    </dependency>-->

    <dependency>
      <groupId>org.postgresql</groupId>
      <artifactId>postgresql</artifactId>
      <version>42.2.1</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>5.1.0.Final</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.tiles</groupId>
      <artifactId>tiles-core</artifactId>
      <version>3.0.5</version>
    </dependency>

    <dependency>
      <groupId>org.apache.tiles</groupId>
      <artifactId>tiles-jsp</artifactId>
      <version>3.0.5</version>
    </dependency>

    <dependency>
      <groupId>org.apache.tiles</groupId>
      <artifactId>tiles-api</artifactId>
      <version>3.0.5</version>
    </dependency>
    <dependency>
      <groupId>org.apache.tiles</groupId>
      <artifactId>tiles-servlet</artifactId>
      <version>3.0.5</version>
    </dependency>
    <dependency>
      <groupId>org.apache.tiles</groupId>
      <artifactId>tiles-template</artifactId>
      <version>3.0.5</version>
    </dependency>
  </dependencies>

  <repositories>
    <repository>
      <id>spring-maven-milestone</id>
      <name>Spring Maven Milestone Repository</name>
      <url>http://maven.springframework.org/milestone</url>
    </repository>
  </repositories>

  <build>
    <finalName>jdbctemplate-demo</finalName>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

 

web.xml

with 2.4

<web-app version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

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

    <servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

 

web.xml 3.0

<?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_3_0.xsd"
    version="3.0">
 
	 <servlet>
	   <servlet-name>xmlconfig</servlet-name>
	   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	   <load-on-startup>1</load-on-startup>
	 </servlet>
	 
	 <servlet-mapping>
	  <servlet-name>xmlconfig</servlet-name>
	  <url-pattern>/</url-pattern>
	 </servlet-mapping>
 
</web-app>

mvc-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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <context:annotation-config/>
    <context:component-scan base-package="com.springapp.mvc"/>
    <mvc:annotation-driven/>

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


    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename">
            <value>messages</value>
        </property>
    </bean>

</beans>

JSP Pages Tags

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

Path/Location:  /src/main/resources/messages.properties  
{ValidationAnnotationClass}.{modelObject}.{fieldName}
you can also pass the arguments to these messages using {0},{1},..{i} 

Size.student.name = name should be minimum of {1} and maximum of {2};
NotNull.student.name = please provide student name
NotEmpty.student.name = blank student name not allowed

Controller Class  

@Controller
@RequestMapping(value ="/student")
public class StudentController {


    @RequestMapping(value="", method = RequestMethod.GET)
    public String getStudent(Model model){
        Student student = new Student();
        model.addAttribute("student", student);
        return "student-login";
    }

    @RequestMapping(value="", method = RequestMethod.POST)
    public String studentDetails(@Valid @ModelAttribute Student student, BindingResult result, Model model){

        if(result.hasErrors()){
            return "student-login";
        }
        model.addAttribute("message", "Hey...welcome "+student.getName());
        return "success";
    }
}

Student.java 

package com.springapp.mvc;

import org.hibernate.validator.constraints.NotEmpty;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 * Created by iue820 on 2/5/16.
 */

public class Student {

    @NotEmpty
    @Size(min=4, max=15)
    @NotNull
    private String name;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                '}';
    }

 

How to load images 

Load images in 3 steps

1. create a folder 'resources' under webapp and create sub-folders as required  and keep the images there.

Screen Shot 2016-02-24 at 11.51.22 AM

Add resources location in spring configuration file


 <mvc:resources mapping="/resources/**" location="/resources/"/>

Acess your image 

<img src= "<c:url value="/resources/images/simple.jpg"/>" alt="my image "/>