Tuesday, May 20, 2014

Spring 4 MVC Using ModelAndView

In this POST, we show you how to develop a Form in Spring 4 MVC . 
We design a user form and input informations and show data in table.

Technologies used :

    Spring 4.0.4.RELEASE
    Logback 1.0.13
    jQuery 
    JSTL    

Create a POJO file:
    package com.spring.mvc.domain;
    
    import java.util.Date;
    
    public class User {
        private String firstName;
        private String lastName;
        private String sex;
        private Date dateofbirth;
    
        public User() {
        }
    
        public User(String firstName, String lastName, String sex) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.sex = sex;
        }
    
        public String getFirstName() {
            return firstName;
        }
    
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
    
        public String getLastName() {
            return lastName;
        }
    
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    
        public Date getDateofbirth() {
            return dateofbirth;
        }
    
        public void setDateofbirth(Date dateofbirth) {
            this.dateofbirth = dateofbirth;
        }
    }
    
      Create a Controller:
        package com.spring.mvc.controller;
        
        import java.util.ArrayList;
        import java.util.List;
        
        import org.slf4j.Logger;
        import org.slf4j.LoggerFactory;
        import org.springframework.stereotype.Controller;
        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.spring.mvc.domain.User;
        
        @Controller
        public class UserController {
        
            private static final Logger LOGGER = LoggerFactory
                    .getLogger(UserController.class);
        
            private static List<User> users = new ArrayList<User>();
            static {
                users.add(new User("firstName01", "lastName01", "M"));
                users.add(new User("firstName02", "lastName02", "M"));
                users.add(new User("firstName03", "lastName03", "M"));
            }
        
            /**
             * http://localhost:8080/springmvc
             * 
             * @return
             */
            @RequestMapping(method = RequestMethod.GET)
            public ModelAndView showUserForm() {
                LOGGER.debug("showUserForm: Show User Form");
        
                ModelAndView modelAndView = new ModelAndView("UserForm");
                modelAndView.addObject("userFormModel", users);
                modelAndView.addObject("userForm", new User());
        
                return modelAndView;
            }
            /**
             * 
             * @param user
             * @return
             */
            @RequestMapping(method = RequestMethod.POST)
            public String postUserForm(@ModelAttribute User user) {
                LOGGER.debug("postUserForm: Post User Form {}",user);
                users.add(user);
                return "redirect:";
            }
        }
        
          Create Logback.xml:
            <?xml version="1.0" encoding="UTF-8" ?>
            
            <configuration scan="true" scanPeriod="2 seconds">
                <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
                    <encoder>
                        <Pattern>%d{dd MMM yyyy HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
                        </Pattern>
                    </encoder>
                </appender>
            
                <appender name="fileappender" class="ch.qos.logback.core.FileAppender">
                    <file>springmvc.log</file>
                    <encoder>
                        <Pattern>%d{dd MMM yyyy HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
                        </Pattern>
                    </encoder>
                </appender>
            
                <root level="DEBUG">
                    <appender-ref ref="console" />
                    <appender-ref ref="fileappender" />
                </root>
            </configuration>
            
              Create UserForm.jsp:
                <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
                    pageEncoding="ISO-8859-1"%>
                <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
                <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
                
                <!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">
                
                <link rel="stylesheet"
                    href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
                <script src="//code.jquery.com/jquery-1.10.2.js"></script>
                <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
                <link rel="stylesheet" href="/resources/demos/style.css">
                
                <title>Spring MVC</title>
                <style type="text/css">
                span.label {
                    display: inline-block;
                    width: 100px;
                    text-align: right;
                    margin-right: 6px;
                }
                
                td {
                    margin: 4px;
                }
                
                .field {
                    width: 250px;
                }
                </style>
                
                
                <script>
                    $(function() {
                        $("#datepicker").datepicker();
                    });
                
                    $(function() {
                        $("input[type=submit], a, button").button().click(function(event) {
                            event.preventDefault();
                        });
                    });
                </script>
                
                </head>
                
                <body>
                    <form:form method="POST" modelAttribute="userForm">
                        <table>
                            <tr>
                                <td><span class="label">First Name:</span></td>
                                <td><form:input path="firstName" class="field" /></td>
                            </tr>
                            <tr>
                                <td><span class="label">Last Name:</span></td>
                                <td><form:input path="lastName" class="field" /></td>
                            </tr>
                            <tr>
                                <td><span class="label">Sex:</span></td>
                                <td><form:radiobutton path="sex" value="M" checked="checked" />Male
                                    <form:radiobutton path="sex" value="F" />Female</td>
                            </tr>
                            <tr>
                                <td><span class="label">Date Of Birth:</span></td>
                                <td><form:input path="dateofbirth" id="datepicker" /></td>
                            </tr>
                            <tr>
                                <td colspan="2"><span class="label"></span> <input
                                    type="submit" value="Submit" /></td>
                            </tr>
                        </table>
                    </form:form>
                
                    <br>
                
                    <table>
                        <tr>
                            <th>First Name</th>
                            <th>Last Name</th>
                            <th>Sex</th>
                            <th>Date Of Birth</th>
                            <th>&nbsp;</th>
                        </tr>
                        <c:forEach items="${userFormModel}" var="users">
                            <tr>
                                <td>${users.firstName}</td>
                                <td>${users.lastName}</td>
                                <td>${users.sex}</td>
                                <td>${users.dateofbirth}</td>
                            </tr>
                        </c:forEach>
                    </table>
                </body>
                </html>
                
                Source Code