Spring MVC Tutorial

    Overview to MVC

MVC or Model View Controller is a controller  is a design pattern . This design pattern involves a Model(manages data and logic ), a view (interacting with user) and a controller(which is in between the model and view and controls  the commands between model and view).Spring MVC is a module in spring framework as we discussed earlier.This chapter gives a very simple Spring MVC Tutorial . We are discussing a simple Spring MVC example

    Concept of dispatcher servlet in Spring MVC

It is the central sevlet in Spring MVC which dispatches the requests from view to controller and vice versa. It does even more than that.It is integrated with Spring IoC container so that we can use every other feature that spring has.

Tools Used:

1)Eclipse
2)Apache Tomcat 8.0

Steps

1)Open Eclipse in suitable work space and create a new maven project
1

2)Select web app archetype while creating the project3_webapp_archtype
3)Give group id , artifact id version and  package properly and press Finish

4

4)Create a new server instance and add the project to it

5_addserver

5)Right click on the project and select the configure build path option , if the project is having errors after creation

6

6)Select Add Library option

7_addlibrray

7)Add server run time libraries. We are using Apache Tomcat

8

8)Edit the pom.xml


	4.0.0
	com.samples
	SpringSample
	war
	0.0.1-SNAPSHOT
	SpringSample Maven Webapp
	http://maven.apache.org
	
		4.1.0.RELEASE
	
	
		
			junit
			junit
			3.8.1
			test
		
		
			org.springframework
			spring-core
			${org.springframework-version}
		

		
			org.springframework
			spring-context
			${org.springframework-version}
		
		
			org.springframework
			spring-webmvc
			${org.springframework-version}
		
		
			org.springframework
			spring-beans
			${org.springframework-version}
		
		
			org.springframework
			spring-expression
			${org.springframework-version}
		
		
			javax.servlet
			jstl
			1.2
			



	
	
		SpringSample
	

9)We are developing a login form with an annotated controller. The index.jsp is the welcome file. From the index page , it is redirecting to the /login of the controller   and from there to loginpage.jsp.JSTL is using to do the redirect from index.jsp . The jsp page  loginpage.jsp  has the login form. When user submits the form ,the /login with  POST method is invoking  and the successpage.jsp will be rendered.

web.xml




	Archetype Created Web Application
	
		dispatcher
		
			org.springframework.web.servlet.DispatcherServlet
		
		
		1
		
	
	
		dispatcher
		/
	
	

   
        contextConfigLocation
        /WEB-INF/dispatcher-servlet.xml
        
    
 
    
    
    org.springframework.web.context.ContextLoaderListener
    

index.jsp


dispatcher-servlet.xml


 
	
 
	
		
			/WEB-INF/pages/
		
		
			.jsp
		
	

The servlet file defines the package where the container needs to look for dependencies . Also it provides the viewResolver bean which injects the view pages.

index.jsp

<%@ 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" %> 



Please Login





LoginController.java

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.sample.models.User;

@Controller
@RequestMapping("/")
public class LoginController {
	
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public ModelAndView login(Model model) {
		System.out.println("Re directing to login page");
		model.addAttribute("user", new User()); 
		return new ModelAndView("loginpage");
	}

	@RequestMapping(value = "login", method = RequestMethod.POST)
	public ModelAndView doLogin(@ModelAttribute("user") User user,BindingResult result) {
		System.out.println("Received User  Details : "+user);
		return new ModelAndView("successpage");
	}
}

 

Our controller class has two methods .

1)Method login() :- To control the redirect from the index.jsp

It returns a ModelAndView object.Also it is setting a User object as model attribute. This model attribute properties are mapped to the input fileds in the loginpage.jsp

2) Method doLogin() :- It is a POST operation.It accepts the userId and password in the already set model attribute.And it renders a login success page.

 

User.java

public class User {

	private String userId;
	private String password;

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String toString() {
		return "User Id = " + userId + " ; Password = " + password;
	}

}

loginpage.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>



Please Login


	
Login Id
Password

sucesspage.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>




Success


Welcome

10)Build and run the application.Login form will be rendered.Upon submitting the form success page will be rendered.

loginform

successpage

See More:

Spring Framework overview
Spring MVC Validation Example