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
2)Select web app archetype while creating the project
3)Give group id , artifact id version and package properly and press Finish
4)Create a new server instance and add the project to it
5)Right click on the project and select the configure build path option , if the project is having errors after creation
6)Select Add Library option
7)Add server run time libraries. We are using Apache Tomcat
8)Edit the pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
<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.samples</groupId> <artifactId>SpringSample</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringSample Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <org.springframework-version>4.1.0.RELEASE</org.springframework-version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>SpringSample</finalName> </build> </project> |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <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> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/dispatcher-servlet.xml</param-value> <description></description> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> |
dispatcher-servlet.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.sample.controllers" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/pages/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans> |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<%@ 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"> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Please Login</title> </head> <body> <c:redirect url="/login"></c:redirect> </body> </html> |
LoginController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<%@ 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"> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Please Login</title> </head> <body> <form action="/SpringSample/login" method="post"> <table> <tr> <td><form:label path="user.userId">Login Id</form:label></td> <td><form:input path="user.userId" /></td> </tr> <tr> <td><form:label path="user.password">Password</form:label></td> <td><form:input path="user.password" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="Submit" /></td> </tr> </table> </form> </body> </html> |
sucesspage.jsp
1 2 3 4 5 6 7 8 9 10 11 12 |
<%@ 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>Success</title> </head> <body> <p>Welcome</p> </body> </html> |
10)Build and run the application.Login form will be rendered.Upon submitting the form success page will be rendered.
See More:
Spring Framework overview
Spring MVC Validation Example
Spring MVC Validation Example