Spring – MVC Framework Tutorial

In this Spring – MVC Framework Tutorial, learn about the spring framework with a simple example of Spring MVC framework with XML configuration.

Spring – MVC Framework Introduction

  • Spring MVC is a web framework like struts1, struts2, and JSF.
  • Spring MVC is used to develop web application easily and quickly with less maintenance.
  • Spring MVC covers web layer which includes presentation layer and controller layer.
  • Spring MVC is implemented based on:
    • MVC Architecture.
    • Front controller design pattern.
    • Servlets and JSP
  • The Model encapsulates the application data and in general, they will consist of POJO.
  • The View is responsible for rendering the model data and in general it generates HTML output that the client’s browser can interpret.
  • The Controller is responsible for processing user requests and building an appropriate model and passes it to the view for rendering.

Spring MVC Basic Architecture.

  • You should configure DispatcherServlet in web.xml as follows:
        <servlet>
      <servlet-name>xadmin</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
      <servlet-name>xadmin</servlet-name>
      <url-pattern>*xadmin</url-pattern>
    </servlet-mapping>

     

  • At the web, container startup
    • DispatcherServlet will be loaded, instantiated and initialized by calling the init() method.
    • Init() of dispatcher-servlet will try to identify the spring configuration document with the following naming convention. Servlet-name-servlet.xml (if custom spring XML is not defined)
  • DispatcherServlet creates the application context (XmlWebApplicationContext) object by reading all the beans specified in the spring configuration document.
  • If the spring configuration document is not found with the given naming conventions then ApplicationContext object will not be created by the dispatcher-servlet.

Example:-

public class DispatcherServlet extends HttpServlet {
ApplicationContext ctx=null;
public  void init(ServletConfig cfg) {

//1.try to get the spring configuration document with the default naming convention
String xml =”servlet-name”+Servlet.xml

// if found then creates the ApplicationContext object.

Ctx= new XmlWebApplicationContext(xml);
}
...
}

After deploying and starting the spring MVC based web application. Following tasks will happen at the web container startup.

  1. Web container loads create and initialize dispatcherServlet by calling init() method.
  2. DispatcherServlet’s init() performs the following:
    1. identifies spring configuration document files.
    2. Spring container instance will be created by reading all the beans from the identified spring configuration document.
    3. Initializes dispatcher-servlet servlet with spring container instances.

Following tasks will happen at web container shutdown time:

  1. Web container calls destroy() method of dispatcher-servlet.
  2. Destroy() method of dispatcher-servlet destroys the spring container instance

You can also create the application context object with the following configuration in web.xml

<context-param>
<param-name>contextconfiglocation</param-name>
<param-value>/WEB-INF/xadmin.xml</param-value>
</context-param>
<listener>
<listener-class> org.springframework.web.context.contextLoaderListener</listener-class>
</listener>

Example:

class contextLoaderListener implemets servletContextListener {
public void contextInitialized(servletContextEvent) {
servlet xml=sc.getInitParameter(“contextconfigLocation”);
if(xml!-null)
{
ctx=new xmlWebApplicationContext(xml);
}

}
...
}

Program with spring MVC

File required:

Index.jsp Show.jsp CourceController.java CourceServlet.java
Web.xml xadmin-servlet.xml

Index.jsp

<html> 
<body>
<br>
<h1> Xadmin.net website <br/>
<a href=”<c:url value=”cource.xadmin”/>”> Show Xadmin technologies </a>
</h1>
</body> </html>

show.jsp

<h2> xadmin information : </h2>
<ul> <jtc:forEach var=”cou” items=”${AL}”>
<li> <h1> ${cou} </h1>
</jtc:forEach></ul>

CourceController.java

package com.xadmin.spring.mvc;
import java.util.ArrayList;
import javax.servlet.http.*;
import org.springframework.beans.factory.Annotation.Autowired;
Import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class CourceController extends AbstractController
{
@Autowired
private courceService cs;
protected ModelAndViewhandleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
ArrayList<string> al =cs.getCources();
return new ModelAndView(“Show”,”AL”, “al);
}

CourceService.java

package comxadmin.spring.mvc;
import java.util.ArrayList;

public class CourseService {
public ArrayList<string>getCources() 
{
ArrayList<string> al=new ArrayList<string>();
al.add(“JAVA”);
al.add(“JDBC”);
al.add(“servlet”);
al.add(“JSP”);
return al;
]

Web.xml

<web-app>
<servlet>
<servlet-name>xadmin</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>xadmin</servlet-name>
<url-pattern>*.xadmin</url-pattern>
<servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

xadmin-servlet.xml

<beans .......
<context:annotation-config/>
  class=”org.spring.framework.web.servlet.view.InternalResourceViewResolver”>
  <property name=”viewclass”
    value=”org.springframework.web.servlet.view.internalResourceView”/>
  <property name=”prefix” value”/”/>
  <property name=”suffix” value”jsp”/>
</bean>

<bean name=”/cource.xadmin” class=”com.xadmin.spring.mvc.coursecontroller”/>
<bean id=”cs” class=”com.xadmin.spring.mvc.courceService”/>
<beans>

Spring Example using XML configuration

Files required

Index.jsp Show.jsp CourceController.java
CourceServlet.java Web.xml Xadmin-servlet.xml

Index.jsp

<html> 
<body>
<br>
<h1> Xadmin.net website <br/>
<a href=”<c:url value=”cource.xadmin”/>”> Show Xadmin technologies </a>
</h1>
</body> </html>

show.jsp

<h2> xadmin information : </h2>
<ul> <jtc:forEach var=”cou” items=”${AL}”>
<li> <h1> ${cou} </h1>
</jtc:forEach></ul>

CourceService.java

package comxadmin.spring.mvc;
import java.util.ArrayList;

public class CourseService {
public ArrayList<string>getCources() 
{
ArrayList<string> al=new ArrayList<string>();
al.add(“JAVA”);
al.add(“JDBC”);
al.add(“servlet”);
al.add(“JSP”);
return al;
]

Web.xml

<web-app>
<servlet>
<servlet-name>xadmin</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>xadmin</servlet-name>
<url-pattern>*.xadmin</url-pattern>
<servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

CourseContoller.java

package com.xadmin.spring.mvc;
import.java.util.*;
import javax.servlet.http.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.sterotype.controller;
import org.springframework.web.bind.annotation.requestMapping;

@Controller
public class CourseController {
@AutoWired
private courceService cs;

@RequestMapping(value=”/cource.xadmin”)
protected string getCourses(HttpServletRequest Request) throws Exception {
ArrayList<string al=cs.getCources();
request.setAttribute(“AL”, al);
return “show”;
}
}

xadmin-servlet.xml

<beans .......
// write the schema of the xml here....
<context:annotation-config/>
  class=”org.spring.framework.web.servlet.view.InternalResourceViewResolver”>
  <property name=”viewclass”
    value=”org.springframework.web.servlet.view.internalResourceView”/>
  <property name=”prefix” value”/”/>
  <property name=”suffix” value”jsp”/>
</bean>

<bean id=”cs” class=”com.xadmin.spring.mvc.courceService”/>
</beans>

Conclusion:
This article is designed for Java programmers with a need to understand the Spring MVC Framework in detail along with its architecture and actual usage.  This article will bring you at the intermediate level of expertise from where you can take yourself to a higher level of expertise. Please feel free to drop a comment in the below comment box, if you have a doubt regarding the topic or you want to share more information about the topic.